10 Useful PHP Code Snippets For Programmers

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInShare on RedditPin on Pinterest

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:

With this script, you can know if your server is HTTPS or not.

<?php>

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.

<?php>

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.

<?php>

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.

<?php>

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.

<?php>

 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.

<?php>

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:
<?php>

    $useragent = $_SERVER ['HTTP_USER_AGENT'];
    echo "<b-->Your User Agent is: " . $useragent;
?>
 
8. Check String For Html:

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

<?php>

   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<br />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.

<?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.

<?php>

   $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).

<?php>

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);

?>
 

Run WPF application at Window startup

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInShare on RedditPin on Pinterest

Download Sample Demo

The following snippet will allow you to add your WPF application in the registry so it will launch when Windows start. Alternative you can use Environment.SpecialFolder.Startup to place a shortcut of your application in the startup folder which will have the same effect.

Note that this snippet will add WPF application in window start up if the current user has administration rights then demo app will add entry to (HKEY_LOCAL_MACHINE) in registry which will works for all user’s startup otherwise it will add to current user’s startup entry (HKEY_CURRENT_USER) in registry.

StartUpManager Class

public class StartUpManager
    {
        public static void AddApplicationToCurrentUserStartup()
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
            }
        }

        public static void AddApplicationToAllUserStartup()
        {
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
            }
        }

        public static void RemoveApplicationFromCurrentUserStartup()
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                key.DeleteValue("My ApplicationStartUpDemo", false);
            }
        }

        public static void RemoveApplicationFromAllUserStartup()
        {
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                key.DeleteValue("My ApplicationStartUpDemo", false);
            }
        }

        public static bool IsUserAdministrator()
        {
            //bool value to hold our return value
            bool isAdmin;
            try
            {
                //get the currently logged in user
                WindowsIdentity user = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(user);
                isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch (UnauthorizedAccessException ex)
            {
                isAdmin = false;
            }
            catch (Exception ex)
            {
                isAdmin = false;
            }
            return isAdmin;
        }


    }


Register program to start with Windows:
private void btnAddInStartUp_Click(object sender, RoutedEventArgs e)
        {
            if (StartUpManager.IsUserAdministrator())
            {
                // Will Add application to All Users StartUp
                StartUpManager.AddApplicationToAllUserStartup();
            }
            else
            {
                // Will Add application to Current Users StartUp
                StartUpManager.AddApplicationToCurrentUserStartup();
            }
        }
Stop program from starting with Windows:
private void btnRemoveFromStartUp_Click_1(object sender, RoutedEventArgs e)
        {
            if (StartUpManager.IsUserAdministrator())
            {
                // Will Remove application to All Users StartUp
                StartUpManager.RemoveApplicationFromAllUserStartup();
            }
            else
            {
                // Will Remove application to Current Users StartUp
                StartUpManager.RemoveApplicationFromCurrentUserStartup();
            }
        }

StartUpManager.IsUserAdministrator() will check if the current user have administrator permissions or not. you can also make your application to run with administrator permissions by adding

 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

into your application app.manifest file.

Create shortcut programmatically in C#

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInShare on RedditPin on Pinterest

If we required to create a shortcut for our application or for any other reason, the Windows Script Host Object Model library allows us to do just that.

we need to add the Windows Script Host Object Model library as a reference to our project first in order to access the classes which helps us creating shortcut.

1. Right click on your project
2. Click “Add Reference…”
3. Select the “COM” tab on the left
4. Search for Windows Script Host Object Model and add it as a reference

After you successfully add the reference in your project you should be able to use the snippet bellow to create shortcuts as you please.

Create shortcut Function:

public static void CreateShortcut(string shortcutName, string shortcutPath, string targetFileLocation)
{
    string shortcutLocation = System.IO.Path.Combine(shortcutPath, shortcutName + ".lnk");
    WshShell shell = new WshShell();
    IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutLocation);
 
    shortcut.Description = "My shortcut detail";   // The description of the shortcut
    shortcut.IconLocation = @"c:\app.ico";           // The icon of the shortcut
    shortcut.TargetPath = targetFileLocation;                 // The path of the file that will launch when the shortcut is run
    shortcut.Save();                                    // Save the shortcut
}

We can use this function later as:

CreateShortcut("my shortcut", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Assembly.GetExecutingAssembly().Location);

Useful jQuery Code Snippets

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInShare on RedditPin on Pinterest

Jquery is used on thousands upon thousands of web pages. It’s one of the most common libraries to insert into pages, and it makes DOM manipulation a snap. Using Jquery  you will be able to change an existing element within a number of ways as well as: decreasing page load time and thereby giving your end users a better experience when visiting your site.

I have put together a series of  helpful jQuery code snippets you may save and copy to use at your own discretion.

Scroll to top of page

(more…)

Introducing the .NET Platform

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInShare on RedditPin on Pinterest

As a C#.net, VB.net developer, it’s important to understand the environment you are building applications on: Microsoft .NET (pronounced “Dot Net”). After all, your design and development decisions will often be influenced by code-compilation practicalities, the results of compilation, and the behaviour of applications in the run time environment.

This article will help your in understanding .NET and .NET architecture.

(more…)