10 Useful PHP Code Snippets For Programmers

I am going to share most useful PHP code snippets that a PHP developer will need at any point in his career. Few of the snippets are shared from my projects and few are taken from useful php websites from internet.

1. Detect HTTPS Server:

you can know if your server is HTTPS or not.
if ($_SERVER['HTTPS'] != "on") { 
 echo "This is not HTTPS";
}else{
 echo "This is HTTPS";
}

2. Get User IP Address:

The above code will work even in case your client is behind proxy server. Below function to get real IP address of client.

function getRealIPAddress()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
        $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

3. Validate email Address:

E-mail validation is perhaps the most used validation in web forms, this code will validate email address.

 
function is_valid_email($email)
{
    if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
        return true
    else
        return false;
}  

4. Detect if Ajax Request:

scope of this function is to check whether request is done via ajax or not.

 
public function isAjaxRequest(){
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        // an ajax call
        return true;
    }
    else{
        // non ajax call
        return false;
    }
} 

5. HTTP Redirection in PHP:

Use this to Redirect user to other page.

 

 header('Location: http://www.site.com/index.php'); // add your url


6. Force file Download:

Provide files to the user by forcing them to download.

 

function force_download($file)
{
    if ((isset($file))&&(file_exists($file))) {
       header("Content-length: ".filesize($file));
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename="' . $file . '"');
       readfile("$file");
    } else {
       echo "No file selected";
    }
}  

7. Browser Detection script in PHP:

Test a string to see if it contains HTML within it.

 

 $useragent = $_SERVER ['HTTP_USER_AGENT'];
    echo "Your User Agent is: " . $useragent;

8. Check String For Html:

Test a string to see if it contains HTML within it.

 

function has_html($string){
    if(strlen($string) != strlen(strip_tags($string))){
        return true;
    }
    return false;
} 

var_dump(has_html("This string doesn't have any html"));
var_dump(has_html("This string has a
line break"));

9. Creating and Parsing JSON :

Following is the PHP code to create the JSON data format of above example using array of PHP.

 
$json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
   echo json_encode($json_data);

Following code will parse the JSON data into PHP arrays.
 
$json_string='{"id":1,"name":"Zahid","country":"Pakistan","office":["hotmail","oracle"]} ';
   $obj=json_decode($json_string);
   //print the parsed data
   echo $obj->name; //displays rolf
   echo $obj->office[0]; //displays hotmail

10. PHP Strong Password Generator :

This code an generate strong password of any length and any complexity (1 to 5).

 

function generate_password($length = 8, $complex=3) {
   $min = "abcdefghijklmnopqrstuvwxyz";
   $num = "0123456789";
   $maj = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   $symb = "!@#$%^&*()_-=+;:,.?";
   $chars = $min;
   if ($complex >= 2) { $chars .= $num; }
   if ($complex >= 3) { $chars .= $maj; }
   if ($complex >= 4) { $chars .= $symb; }
   $password = substr( str_shuffle( $chars ), 0, $length );
   return $password;
}
echo generate_password(8);

Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment