PHP is the most widely used web based programming language that powers millions of websites including some of the most popular ones like Facebook.
Even after using PHP for years, we stumble upon functions and features that we did not know about. Some of these can be quite useful, yet underused. So, every web developer should keep useful code snippets in a personal library for future reference.

In today’s post we will show you 8 useful code snippets that you probably never heard of.

Generate a Random String

This function will create a random string that you can use for user id’s etc.

function generate_rand($l){  
  $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";  
  for($i=0; $i<$l; $i++) {  
      $rand.= $c[rand()%strlen($c)];  
  return $rand;  

Display source code of any webpage

Want to be able to display the source code of any webpage, with line numbering? Here is a simple code snippet to do it. Just modify the url on line 2 at your convenience. Or even better, make a pretty function according to your needs.

$lines = file('');
foreach ($lines as $line_num => $line) { 
	// loop thru each line and prepend line numbers
	echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";

Check if server is HTTPS

if ($_SERVER['HTTPS'] != "on") { 
	echo "This is not HTTPS";
	echo "This is HTTPS";

Determine the dominant color of an image

This code will be super useful for people managing images or photography website. With it, you can analyze any image and get its dominant color (R, G, or B).

$i = imagecreatefromjpeg("image.jpg");

for ($x=0;$x<imagesx($i);$x++) {
    for ($y=0;$y<imagesy($i);$y++) {
        $rgb = imagecolorat($i,$x,$y);
        $r   = ($rgb >> 16) & 0xFF;
        $g   = ($rgb >>  & 0xFF;
        $b   = $rgb & 0xFF;

        $rTotal += $r;
        $gTotal += $g;
        $bTotal += $b;

$rAverage = round($rTotal/$total);
$gAverage = round($gTotal/$total);
$bAverage = round($bTotal/$total);

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 . '"');  
    } else {  
       echo "No file selected";  

In order to optimize your scripts, you may definitely want to know how many amount of RAM they use on your server. This snippet will check memory and then print initial, final and peak usages.

echo "Initial: ".memory_get_usage()." bytes \n";
/* prints
Initial: 361400 bytes
// let's use up some memory
for ($i = 0; $i < 100000; $i++) {
    $array []= md5($i);
// let's remove half of the array
for ($i = 0; $i < 100000; $i++) {
echo "Final: ".memory_get_usage()." bytes \n";
/* prints
Final: 885912 bytes
echo "Peak: ".memory_get_peak_usage()." bytes \n";
/* prints
Peak: 13687072 bytes

When talking about compression, we usually think about files, such as ZIP archives. It is possible to compress long strings in PHP, without involving any archive files. In the following example we are going to utilize the gzcompress() and gzuncompress() functions:

"Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. ";
$compressed= gzcompress($string);
echo"Original size: ". strlen($string)."\n";
/* prints
Original size: 800
echo"Compressed size: ". strlen($compressed)."\n";
/* prints
Compressed size: 418
// getting it back
$original= gzuncompress($compressed);

Detect browser language

When developing a multilingual website, I really like to retrieve the browser language and use this language as the default language for my website. Here’s how I get the language used by the client browser:

function get_client_language($availableLanguages, $default='en'){

		foreach ($langs as $value){
			if(in_array($choice, $availableLanguages)){
				return $choice;
	return $default;