Tuesday 31 December 2019

How to create and manage log file in php?


Create and manage crud operation log data PHP

<?php
function crud_log($action = '',$message = '',$array_data = array()){
    global $handle_crud_log;
    date_default_timezone_set("Australia/Sydney"); //Ex. set australia/sydney timezone   
    $crud_log_dir = "crud-log"; //Create this DIR(crud-log) on file dir location
   
    if (!file_exists($crud_log_dir)){
        // create directory/folder uploads.
        mkdir($crud_log_dir, 755, true);
    }   

    $quote_log_file_name =  "/crud_log_".date("m_Y").".log";
    $ip_address = @$_SERVER['REMOTE_ADDR']." #### ". @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $date_time = date("d/m/Y H:i:s");
    $action_name = $action; // (Ex. Create/Read/Update/Delete)
    $crud_msg = $message; //Create, Read, Update and Delete message;
    $array_data = $array_data; //Array data type Like $_POST
       
    $handle_crud_log = fopen($crud_log_dir.$quote_log_file_name, "a");
    fwrite($handle_crud_log, "=================================================\r\n");   
    fwrite($handle_crud_log, "At: {$date_time}\r\n");
    fwrite($handle_crud_log, "From: {$ip_address}\r\n");
    fwrite($handle_crud_log, "Action: {$action_name} \r\n");
    fwrite($handle_crud_log, "Message: {$crud_msg}\r\n");
    fwrite($handle_crud_log, "Data: ". print_r($array_data, true));
    fwrite($handle_crud_log, "=================================================\r\n\r\n");
}
$action = "Update";
$message = "Update emplyee detail";
$array_data = array("f_name"=>"PHP", "l_name"=>"Kishan");
crud_log($action, $message, $array_data); // call function for create log
?>

Saturday 14 December 2019

PHP Run Script For Specific IP Address


<?php
// Write your IP instead of xxx.xxx.xxx.xxx

if(@$_SERVER['REMOTE_ADDR'] == 'xxx.xxx.xxx.xxx'|| @$_SERVER['HTTP_X_FORWARDED_FOR'] == 'xxx.xxx.xxx.xxx' ){
    define( 'TESTINGMOD',TRUE);
}else{
    define( 'TESTINGMOD',FALSE);
}

if(TESTINGMOD){
    error_reporting(E_ALL);    ini_set('display_errors', 1);
    // Write test code for specific IP address in live site
}else{
    error_reporting(0);
}
?>

Friday 15 November 2019

How can I remove a particular value from an array in JavaScript with Example?


<!DOCTYPE html>
<html>  
<head>
    <title>How can I remove a particular value from an array in JavaScript with Example? -PHP Kishan</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" crossorigin="anonymous"></script>
    <script>  
    jQuery(document).ready(function(){
        orig_array = ['BattleGrounds', 'Fornite Battle Royale', 'League of Legends (LOL)', 'Counter-Strike: Global Offensive (CS: GO)', 'HearthStone', 'Minecraft', 'DOTA 2', 'Apex Legends', 'The Division 2', 'Splatoon 2', 'Rummy'];    //Ex: Game List
        document.getElementById("orig_array").innerHTML = orig_array;
      
      
        remove_game = orig_array.indexOf('Fornite Battle Royale'); // You can remove only one value (Game name)
        if (remove_game > -1) {
          orig_array.splice(remove_game, 1);
        }          
        document.getElementById("new_array").innerHTML = orig_array;
    });
    </script>
</head>
<body>
    <p><strong>Array Games List: </strong><br>=> <span id="orig_array"></span></p>  
    <p><strong>Reomve Game From List: </strong><br>=> Fornite Battle Royale</p>  
    <p><strong>New Array Games List: </strong><br>=> <span id="new_array"></span></p>  
</body>
</html>

Monday 7 October 2019

How to redirect another webpage using JavaScript?



<!DOCTYPE html>
<html>   
<head>
    <title>How to redirect another webpage using JavaScript? -PHP Kishan</title>
    <script>   
        function new_Location(newurl) {       
            /* The wwindow.location method redirect to another webpage location. */
            window.location = newurl;
           
            // OR //
            /* The window.location.href() method redirect to another webpage location. */
            window.location.href = newurl;
           
            // OR //
            /* The window.location.assign() method loads a new location in the browser. */
            window.location.assign(newurl);
           
            // OR //
            /* The window.location.replace() method current location to redirect a new location in the browser. */
            window.location.replace(newurl);
        }

        var new_url = "https://phpkishan.blogspot.com/"; // Assigen New URL Location
    </script>
</head>
<body>
    <p>You can use any one method as per requirement for redirect your document location.</p>
    <input type="button" value="Redirect to new location" onclick="new_Location(new_url)">
</body>
</html>

Friday 6 September 2019

How to prevent SQL injection in PHP?

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    //unsafe data
    $unsafe_name = mysqli_real_escape_string($con, $_POST['fname']);
    $unsafe_email = mysqli_real_escape_string($con, $_POST['email']); 

    //safe data
    $safe_name = mysqli_real_escape_string($con, $_POST['fname']);
    $safe_email = mysqli_real_escape_string($con, $_POST['email']); 

    $sql = "INSERT INTO my_db (fname, email)  VALUES ('".$safe_name."', '".$safe_email."')";

    if (!mysqli_query($con,$sql)) {
        die('Error: ' . mysqli_error($con));
    }
    echo "1 record added";
    mysqli_close($con);  
}
?>

<form action="" method="post">
    Name: <input type="text" name="fname"><br>
    E-mail: <input type="text" name="email"><br>
    <input type="submit">
</form>

Thursday 5 September 2019

How to connect to mysqli database in php?


Create connection.php file and include all CRUD operation's file for connect database.

<?php
error_reporting(0);
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME =  'mysql';
$conn = mysqli_connect($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
// Check connection
if (!$conn) {
    echo "Failed to Connect to MySQL: " . mysqli_connect_error();
}else{
    echo "Success Connection to MySQL...!";
}
?>

Tuesday 3 September 2019

How to Replace Text of the_content in WordPress

If you want to replace keywords and text in the_content? Add the following code to the functions.php file of your WordPress active theme OR in custom plugin.

<?php
function replace_text($text) {
    $text = str_replace('Have a coupon?', 'Haben Sie einen Gutschein?', $text);
    $text = str_replace('Apply Coupon', 'Gutschein anwenden', $text);
    $text = str_replace('Product', 'Produkt', $text);
    $text = str_replace('Price', 'Preis', $text);
    $text = str_replace('Coupon code', 'Gutschein Code', $text);
    $text = str_replace('Update Cart', 'Warenkorb aktualisieren', $text);
    $text = str_replace('Billing Details', 'Rechnungsdetails', $text);
    $text = str_replace('Additional Information', 'Zusätzliche Informationen', $text);
    $text = str_replace('Your order', 'Ihre Bestellung', $text);
    $text = str_replace('Shipping address', 'Lieferadresse', $text);
   
    return $text;
}
add_filter('the_content', 'replace_text',99);
?>

Thursday 1 August 2019

How to define an empty object in PHP?

<?php   
    $ObjAraay = new stdClass();
    $ObjAraay->fname = "PHP";
    $ObjAraay->lname = "Beginner";

    echo "<pre>";
    print_r($ObjAraay);
    echo "</pre>";
?>

Result: 


Sunday 28 July 2019

How to compare dates greater than in php?



<?php
$today = date('d-m-Y'); // Date must be in 'd-m-Y' format
$date = "07-07-2020";

if(strtotime($date) < strtotime($today)){
   echo $date .' date is smaller than today '.$today .' date';
}else{
    echo $today .' date is larger than today '.$date .' date';
}
?>

Wednesday 10 July 2019

How do I set and get a cookie with jQuery?

<script type='text/javascript'>
function setCookie(key, value) {
         var expires = new Date();
         expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
         document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
setCookie('Name','Kishan');

function getCookie(key) {
          var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
          return keyValue ? keyValue[2] : null;
}
getCookie('Name');

// Output: "Kishan"
</script>

Wednesday 3 July 2019

How to import an SQL file using the command line in MySQL?









#Step1: Create just databse in your phpMyAdmin
 Ex: test_table.sql

#Step2: put sql databse file in bin folder
 Ex: E:\wamp64\bin\mysql\mysql5.7.26\bin\DB\test_table.sql

# Open CMD
# Step3: Change the directory folder current directory to mysql bin directory.
 C:\Users\kishanvk>CD E:\wamp64\bin\mysql\mysql5.7.26\bin ↲
 C:\Users\kishanvk>E: ↲
 E:\wamp64\bin\mysql\mysql5.7.26\bin>

# Step4: write below command line and in this cmd
 E:\wamp64\bin\mysql\mysql5.7.26\bin>mysql -u [Username] -p [DBNAME] < DB\[DBNAME.sql] ↲

 Ex: E:\wamp64\bin\mysql\mysql5.7.26\bin>mysql -u root -p test_table < DB\test_table.sql ↲

# Step5: Enter password
 Enter password:***** ↲

# Step6: You can see imported database in your phpMyAdmin

Sunday 19 May 2019

HTML to PDF Example






<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>HTML to PDF Example - PHP Kishan</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<style>
.center{text-align: center;}
.pdfdiv{background-color: #d9ec58;margin: 50px;padding:30px;}
.innerdiv{padding: 10px;margin: 15px 0;border: 2px solid #ea5555;}
.loader-div {position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(0, 0, 0, 0.66);z-index: 9;bottom: 0;display: block;text-align:center;color: #fff;font-size: 22px;padding: 30% 0;}
.dp-img{border: 1px solid #e65959;border-radius: 50%;padding: 12px;margin: 6px;}
.btn-div{margin: 58px auto;}
.downloadpdf{text-align: center;background-color: #27d848;width: max-content;padding: 10px;border-radius: 10px;margin: 0 auto;font-size: 30px;text-decoration-line: none;}
.downloadpdf:hover{background-color: #d1d451;}
</style>
</head>
<body>
    <div class="btn-div center">
        <a class="downloadpdf" href="javascript:;" data-pdf="html2pdf" data-target="pdfdiv">Download PDF</a>
    </div>
    <div id="pdfdiv" class="pdfdiv center">
        <div class="innerdiv">
            <h1>This is a Heading</h1>
            <p>This is a paragraph.</p>
            <h5>This is a image.</h5>
            <div>
                <img class="dp-img" src="image.png" alt="HTML to PDF">
            </div>
        </div>
        <div class="innerdiv">
            <h1>This is a Heading</h1>
            <p>This is a paragraph.</p>
            <h5>This is a image.</h5>
            <div>
                <img class="dp-img" src="image.png" alt="HTML to PDF">
                <img class="dp-img" src="image.png" alt="HTML to PDF">
                <img class="dp-img" src="image.png" alt="HTML to PDF">
                <img class="dp-img" src="image.png" alt="HTML to PDF">
                <img class="dp-img" src="image.png" alt="HTML to PDF">
                <img class="dp-img" src="image.png" alt="HTML to PDF">
                <img class="dp-img" src="image.png" alt="HTML to PDF">
                <img class="dp-img" src="image.png" alt="HTML to PDF">
            </div>
        </div>
        <div class="innerdiv">
            <h1>This is a Heading</h1>
            <p>This is a paragraph.</p>
            <h5>This is a image.</h5>
            <div>
                <img class="dp-img" src="image.png" alt="HTML to PDF">
            </div>
        </div>       
    </div>
    <div class="btn-div center">
        <a class="downloadpdf" href="javascript:;" data-pdf="html2pdf" data-target="pdfdiv">Download PDF</a>
    </div>
    <div class="loader-div">Loading...</div>
<footer>
<script>
jQuery(document).ready(function(){
    jQuery('.loader-div').hide();
    jQuery(".downloadpdf").click(function(e){   
        jQuery('.loader-div').show();
        var pdfname = jQuery(this).data('pdf');
        var pdftarget = jQuery(this).data('target');
        console.log("PDF NAME:" + pdfname + "PDF HTML Div: " + pdftarget);   
       

        var pdfw = jQuery('#'+pdftarget).width();
        var pdfh = jQuery('#'+pdftarget).height();
        // console.log  ('div width: '+ pdfw + ' div height: '+pdfh);       

        html2canvas(document.getElementById(pdftarget)).then(function(canvas) {
            var imgData = canvas.toDataURL("image/jpeg");
            // console.log(imgData);
           
            var pdf = new jsPDF('','px',[pdfw,pdfh]);          
            var pwidth = pdf.internal.pageSize.getWidth();
            var pheight = pdf.internal.pageSize.getHeight();
            // console.log('PDF pwidth: '+ pwidth + ' PDF height: '+pheight);   

            pdf.addImage(imgData, 'JPEG', 0, 0, pwidth, pheight);                  
            pdf.save(pdfname+'.pdf');             
            jQuery('.loader-div').hide();
        }).catch(function(M) {
             console.log(M);   
        });
    });
});
</script>
</footer>
</body>
</html>

Note: All images of HTML page must be on the current domain.