5 Random Useful PHP Code Snippets / Function

Here I have complied 5 Random Useful PHP Code Snippets / Function, which are very handy to use in any web based project, you can simply add these snippets and functions in you code library and use anywhere in project. It is good idea to have good pre defined php function so that you can quickly use in your project as per your requirement.


1. Download & save a remote image on your server using PHP

Quickest super easy and efficient way to download a remote image and save it on your own server’s local folder.

<?php
$img = file_get_contents('http://www.example.com/images/image.jpg');
file_put_contents('/img/image.jpg', $img); //save the image on your local folder
?>

2. Generate a Random String in PHP

Below function will random string quickly, will help you create captcha of random otp password.

<?php
// where $len = length of the random string you want to set.
function generateRandStrg($l){  
  $char= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";  
  srand((double)microtime()*1000000);  
  for($i=0; $i<$len; $i++) {  
      $rand.= $c[rand()%strlen($char)];  
  }  
  return $rand;  
 }  
?>



3. Create URL / POST Slugs and make url seo friendly

<?php
function createSlug($string){  
    $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);  
    return $slug;  
}  
?>

4. Detect browser language in php

If you are developing a multilingual website, Following function will help you to detect browser’s language and redirect to native home page.

function getLanguage($availableLanguages, $default='en'){
	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
 
		foreach ($langs as $value){
			$choice=substr($value,0,2);
			if(in_array($choice, $availableLanguages)){
				return $choice;
			}
		}
	} 
	return $default;
}

5. Detect AJAX Request in php

Most of the JavaScript frameworks like jQuery, mootools send and additional HTTP_X_REQUESTED_WITH header when they make an AJAX request, so that you can detect AJAX request on server side.

<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){  
    // Yes!! This is ajax request
} else {  
   //something else  
}  
?>
Posted in PHP