Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Monday, 4 January 2021

Perfect Ranking With Ties Using By PHP Array

 


<?php

#Ex:  Short Set Ranking Hosting Provider Founded By Year

// INPUT

$Hosting_Years = array(

    'Bluehost' => 2003,

    'Dreamhost' => 1996,

    'Hostinger' => 2004,

    'HostGator' => 2002,

    'A2 Hosting' => 2001,

    'GreenGeeks' => 2008,

    'WP Engine' => 2010,

    'Inmotion' => 2001,

    'SiteGround' => 2004,

    'Nexcess' => 2000,

);


function setRanking($standings) {

    $rankings = array();

    arsort($standings);

    $rank = 1;

    $tie_rank = 0;

    $prev_score = -1;

    foreach ($standings as $name => $score) {

        if ($score != $prev_score) {  //this score is not a tie

            $count = 0;

            $prev_score = $score; 

            $rankings[$name] = array('score' => $score, 'rank' => $rank);

        } else { //this score is a tie

            $prev_score = $score;

            if ($count++ == 0) {

                $tie_rank = $rank - 1;

            }

            $rankings[$name] = array('score' => $score, 'rank' => $tie_rank);

        }

        $rank++;

    }

    return $rankings;

}


// OUTPUT 

$set_Host_Ranking = setRanking($Hosting_Years);

foreach($set_Host_Ranking as $host => $value){

    echo "<br> Rank: ".sprintf("%03d", $value['rank']). " &emsp; Founded in  : ".$value['score']. "&emsp; Host: ".$host;

}

?>

According To Question:

#Ranking/Position on value of array in PHP

#Rank Of An Element In An Array

#What Is Rank Of An Array

#Array Ascending Order In PHP

#PHP Sort Multidimensional Array By Value Alphabetically

#Ksort Multidimensional Array PHP

#PHP Sort Multidimensional Array By Key

Sunday, 3 January 2021

Formatting A Number With Leading Zeros In PHP


<?php

#Ex:  Make 4 Digit Integer Or Zerofill An Integer In PHP

// INPUT

$start_number = 1;

$end_number = 100;

for($i=$start_number; $i <= $end_number; $i++ ){

    echo "<br> #: ".sprintf("%04d",  $i);  

}

// OUTPUT

#: 0001

#: 0002

#: 0003

#: 0004

#: 0005

#: 0006

#: 0007

#: 0008

#: 0009

#: 0010

.

.

.

#: 0100

?> 

According To Question:

#add zero after number in php

#php number format: 0001, 0002, 0003 ...

#make number 2 digit php

#php leftpad number

#php force two digit number

#php sprintf

#str_pad in php

#php left fill

Thursday, 10 December 2020

Create A Folder If It Doesn't Already Exist In WordPress Or PHP


 <?php 

if (!file_exists('home/public_html/example.com/wp-content/uploads/blog')) {

    mkdir('home/public_html/example.com/wp-content/uploads/blog', 0777, true);

}

?>


According To Question:

#mkdir php

#check if directory exists php

#how to create directory dynamically in php

#create directory in php file upload

#create folder inside folder in php

#php mkdir not working

#php mkdir 777

#php mkdir()

Saturday, 12 September 2020

How to Custom Pagination For Custom Post in WordPress?

 

There are very simple steps for Pagination for any type of Post in WordPress by Shortcode with Ajax.

  1.  Write this below code in you active WordPress theme's funcntion.php file.
    • ie: \wp-content\themes\twentytwenty\functions.php
  2.  Put this shortcode in your page where you want to display WordPress Custome Post or Post with Ajax Pagination.
    • <?php echo do_shortcode('[php_kishan_wp_portfolio_post_list per_page="30" total="90" post_type="post"]'); ?> OR
    • [php_kishan_wp_portfolio_post_list per_page="30" total="90" post_type="post"]
### Code: ###
<?php
function function_php_kishan_wp_portfolio_post_list($atts, $content = null) {
    ob_start();
    $atts = shortcode_atts(
    array(
        'per_page' => '',
        'total' => '',
        'post_type' => '',
    ), $atts);
    $per_page = $atts['per_page'] ? $atts['per_page'] : '9';
    $total_post = $atts['total'] ? $atts['total'] : '-1';
    $post_type = $atts['post_type'] ? $atts['post_type'] : 'post';

    global $wpdb;
    $post_type = $post_type; // define your custom post type slug here
    // A sql query to return all post titles
    $results = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE post_type = '$post_type'  and post_status = 'publish' order by post_title ASC limit 0,$per_page");
.
.
.
.
return ob_get_clean();
}
add_shortcode('php_kishan_wp_portfolio_post_list', 'function_php_kishan_wp_portfolio_post_list');
#### [php_kishan_wp_portfolio_post_list per_page="30" total="90" post_type="post"] ####

Click here for download full code.

Tuesday, 11 August 2020

How To Search In PHP Array Element Containing String | Like Binod


$example = array(
        "who" => "Who is Binod?",
        "name" => "Dose Binod Tharu is Binod?",
"where" => "Where is Binod?",
"whose" => "Whose name is binod?",
"YouTube" => "Dose Binod in the YouTube?",
"meaning" => "What is Binod meaning?",
"fullform" => "What is Binod full form?",
"pronunciation" => "What is Binod pronunciation?",
"english" => "Dose Vinod in english",
"how" => "How to write Vinod in sanskrit?",
"nickname" => "Which best nickname for Vinod?",
"kon" => "Binod kon he?",
"kaha" =>"Binod kaha he?",
"kiska" =>"Binod kiska name he?"
);

$searchword = 'Binod';

$search_results = array_filter($example, function($var) use ($searchword) {
return preg_match("/\b$searchword\b/i", $var); 
});

echo "Search Word: ".$searchword;
echo "<br>Search Results";
echo "<pre>";
echo "Total Search: ".count($search_results);
echo "<hr>";
print_r($search_results);
echo "</pre>";

OutPut:

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, 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...!";
}
?>

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, 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

Saturday, 29 December 2018

How to set default image on image loaded broken?



<!DOCTYPE html>
<html class="" lang="en-US">
<head>
<meta charset="UTF-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script>
<!-- or -->
<!-- <script src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.js"></script> -->
<style type="text/css">.image-thumb {display: inline-block;margin: 10px;}</style>
</head>
<body>
<div id="product_div">
<div class="image-thumb"><img src="image/product_01.jpg" class="thumbnail-img" width="100" height="100"></div>
<div class="image-thumb"><img src="image/product_02.jpg" class="thumbnail-img" width="100" height="100"></div>
<div class="image-thumb"><img src="image/product_03.jpg" class="thumbnail-img" width="100" height="100"></div>
<div class="image-thumb"><img src="image/product_04.jpg" class="thumbnail-img" width="100" height="100"></div>
<div class="image-thumb"><img src="image/product_05.jpg" class="thumbnail-img" width="100" height="100"></div>
<div class="image-thumb"><img src="image/image/product_06.jpg" class="thumbnail-img" width="100" height="100"></div>
<div class="image-thumb"><img src="image/image/product_07.jpg" class="thumbnail-img" width="100" height="100"></div>
</div>

<script type="text/javascript">
jQuery(document).ready(function(){
if (jQuery('#product_div').length) {
jQuery('#product_div').imagesLoaded().always( function( instance ) {
console.log('all images loaded');
}).done( function( instance ) {
console.log('all images successfully loaded');
}).fail( function(instance2) {
console.log('all images loaded, at least one is broken');
}).progress( function( instance, image ) {
var result = image.isLoaded ? 'loaded' : 'broken';
console.log( 'image is => ' + result + ' for ' + image.img.src );
if(result == 'broken'){
var default_images = ["default_01.jpg","default_02.jpg","default_03.jpg","default_04.jpg","default_05.jpg"];
var new_image_name = default_images[Math.floor(Math.random()*default_images.length)];
console.log("default image is" + new_image_name); /* Random image select */
var default_img = 'default_images/' + new_image_name;
image.img.src = default_img;
}
});
}
});
</script>
</body>
</html>

Thursday, 6 December 2018

Export Database From MySQL






# Open CMD
# Step1: Change the directory folder current directory to mysql bin directory.
C:\Users\PHPKishan> cd D:\wamp64\bin\mysql\mysql5.7.19\bin ↲

# Step2: write below command line and in this cmd
D:\wamp64\bin\mysql\mysql5.7.19\bin>mysqldump --databases --user=[Username] --password [DBNAME] > [DIR PATH]\[DBNAME.sql] ↲

 EX D:\wamp64\bin\mysql\mysql5.7.19\bin>mysqldump --databases --user=root --password test_table > DB\test_table_bk.sql ↲

# Step3: Enter password
Enter password:***** ↲

# Step4: See exported database in you directory

Friday, 2 November 2018

reCAPTCHA V3 Example in PHP


<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
## reCAPTCHA V3 key define ##
#client-side
define('RECAPTCHA_SITE_KEY', 'reCAPTCHA_site_key'); // define here reCAPTCHA_site_key
#server-side
define('RECAPTCHA_SECRET_KEY', 'reCAPTCHA_secret_key'); // define here reCAPTCHA_secret_key

class Captcha {
public function getCaptcha($SecretKey) {
$data = array(
'secret' => RECAPTCHA_SECRET_KEY,
'response' => $SecretKey
);
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response_data = curl_exec($verify);
$response_data = json_decode($response_data);
curl_close($verify);
//echo "<pre>"; print_r($response_data); echo "</pre>";
return $response_data;
}
}

///////////////////////////// OR /////////////////////////////
/*
class Captcha {
public function getCaptcha($SecretKey) {
$Resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . RECAPTCHA_SECRET_KEY . "&response={$SecretKey}");
$Retorno = json_decode($Resposta);
return $Retorno;
}
}
*/

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//echo "<pre>"; print_r($_REQUEST); echo "</pre>";
$ObjCaptcha = new Captcha();
$Retorno = $ObjCaptcha->getCaptcha($_POST['g-recaptcha-response']);
//echo "<pre>"; print_r($Retorno); echo "</pre>";
if ($Retorno->success) {
echo '<p style="color: #0a860a;">CAPTCHA was completed successfully!</p>';
} else {
$error_codes = 'error-codes';
if (isset($Retorno->$error_codes) && in_array("timeout-or-duplicate", $Retorno->$error_codes)) {
$captcha_msg = "The verification expired due to timeout, please try again.";
} else {
$captcha_msg = "Check to make sure your keys match the registered domain and are in the correct locations.<br> You may also want to doublecheck your code for typos or syntax errors.";
}
echo '<p style="color: #f80808;">reCAPTCHA error: ' . $captcha_msg . '</p>';
}
}
?>

<div class="contact_form">
<div class="" style="margin-top:0px;margin-bottom:15px;">
<div class="" style="width:50%">
<form id="Form1" name="Form1" action="" method="POST">
<label for="fname">First Name*</label><br>
<input type="text" name="fname" id="fname" required autofocus><br><br>

<label for="lname">Last Name*</label><br>
<input type="text" name="lname" id="lname" required><br><br>

<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"><br>
<input type="submit">
</form>
</div>
</div>
</div>

<script src="https://www.google.com/recaptcha/api.js?render=<?php echo RECAPTCHA_SITE_KEY; ?>"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('<?php echo RECAPTCHA_SITE_KEY; ?>', {action: 'homepage'}).then(function (token) {
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
</body>
</html>

Thursday, 1 November 2018

Multiple words of string replace with str_replace in PHP

<?php
    ## Converting utf8 characters to iso-88591 manually in PHP
    echo "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />";   
    function str_replace_char(){ 
        $find = array('â€Å“', '’', '…', 'â€"', 'â€"', '‘', 'é', 'Â', '•', 'Ëœ', 'â€'); // en dash
        $replace = array('"', '’', '…', '—', '–', '‘', 'é', '', '•', '˜', '"'); // original
        $new_str_content = str_replace( $find,$replace,$str_content);
        return $new_str_content;
    }
   
    $string = "It’s Getting the Best of Me";
    echo $new_string = str_replace_char($string);
?>

Wednesday, 25 April 2018

How to get Last Month's record data from MySQL Database?



SELECT * from product_order WHERE YEAR(order_date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) and MONTH(order_date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)



Tuesday, 24 April 2018

How to get This Month's record data from MySQL Database?


SELECT * from product_order WHERE MONTH(order_date) = MONTH(NOW()) and YEAR(order_date) = YEAR(NOW())