Code Snippets

 
 

GnasheR

PHP as it's known today is actually the successor to a product named PHP/FI. Created in 1994 by Rasmus Lerdorf, the very first incarnation of PHP was a simple set of Common Gateway Interface (CGI) binaries written in the C programming language. Originally used for tracking visits to his online resume, he named the suite of scripts "Personal Home Page Tools," more frequently referenced as "PHP Tools." Over time, more functionality was desired, and Rasmus rewrote PHP Tools, producing a much larger and richer implementation. This new model was capable of database interaction and more, providing a framework upon which users could develop simple dynamic web applications such as guestbooks. In June of 1995, Rasmus released the source code for PHP Tools to the public, which allowed developers to use it as they saw fit. This also permitted and encouraged users to provide fixes for bugs in the code, and to generally improve upon it.

JQuery -  change pointer on hover, with on click event:

$("#selector").hover(function() {
    $(this).css('cursor','pointer');
}, function() {
    $(this).css('cursor','auto');
});

/* THE ONCLICK EVENT */
$( "#selector" ).click(function() {
    alert( "Handler for .click() called." );
});

PHP - Connect to MySQL database:

// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

PHP - Get real ip address of user:

function getRealIpAddr()  
{  
    if (!empty($_SERVER['HTTP_CLIENT_IP']))  
    {  
        $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;  
}

PHP - Convert seconds into Hours, Minutes and Seconds:

function secsToStr($secs) {
    if($secs >= 86400) {
        $days = floor($secs/86400);
        $secs = $secs%86400;
        $r = $days . ' day';
        if($days <> 1) {
            $r .= 's';
        }
        if($secs>0) {
            $r .= ', ';
        }
    }
    if($secs >= 3600) {
        $hours = floor($secs/3600);
        $secs = $secs%3600;
        $r .= $hours . ' hour';
        if($hours <> 1) {
            $r.='s';
        }
        if($secs > 0) {
            $r .= ', ';
        }
    }
    if($secs >= 60) {
        $minutes = floor($secs/60);
        $secs = $secs%60;
        $r .= $minutes . ' minute';
        if($minutes <> 1) {
            $r.='s';
        }
        if($secs > 0) {
            $r .= ', ';
        }
    }
    $r .= $secs . ' second';
    if($secs <> 1) {
        $r .= 's';
    }
    return $r;
}

/* SYNTAX */
/*

$seconds = "56789";
$output = secsToStr($seconds);
echo $output;

*/

PHP - Add th,st,nd or rd to the end of a number:

function ordinal($cdnl){ 
    $test_c = abs($cdnl) % 10; 
    $ext = ((abs($cdnl) %100 < 21 && abs($cdnl) %100 > 4) ? 'th' 
            : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) 
            ? 'th' : 'st' : 'nd' : 'rd' : 'th')); 
    return $cdnl.$ext; 
}

/* SYNTAX */
/*

$number = 10;
echo ordinal($number); //output is 10th

*/

PHP - Base64 Encode and Decode Strings:

function base64url_encode($plainText) {
    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
}
 
function base64url_decode($plainText) {
    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;
}

PHP - Directory Listing:

function list_files($dir)
{
    if(is_dir($dir))
    {
        if($handle = opendir($dir))
        {
            while(($file = readdir($handle)) !== false)
            {
                if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
                {
                    echo " " . $file . " " . "\n";
                }
            }
            closedir($handle);
        }
    }
}
 
/* SYNTAX */
/*

list_files("images/");

*/

PHP - Browser Detection:

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

PHP - Random Password Generator:

//generates a random password which contains all letters (both uppercase and lowercase) and all numbers

function generatePassword($length) {
    $password='';

    for ($i=0;$i<=$length;$i++) {
	$chr='';
	switch (mt_rand(1,3)) {
		case 1:
			$chr=chr(mt_rand(48,57));
			break;
		case 2:
			$chr=chr(mt_rand(65,90));
			break;
		case 3:
			$chr=chr(mt_rand(97,122));
	}
	$password.=$chr;
    }	
    return $password;
}

PHP - Convert HEX value to RBG:

function hextorgb($hexvalue) {
    if($hexvalue[0] == '#') {
        $hexvalue = substr( $hexvalue, 1);
    }
    if(strlen( $hexvalue ) == 6) {
        list($r, $g, $b) = array($hexvalue[0] . $hexvalue[1], $hexvalue[2] . $hexvalue[3], $hexvalue[4] . $hexvalue[5]);
    }
    elseif (strlen($hexvalue) == 3) {
        list($r,$g,$b) = array($hexvalue[0] . $hexvalue[0], $hexvalue[1] . $hexvalue[1], $hexvalue[2] . $hexvalue[2]);
    }
    else {
        return false;
    }
    $r = hexdec($r);
    $g = hexdec($g);
    $b = hexdec($b);
    return array('R' => $r, 'G' => $g, 'B' => $b);
}

/* SYNTAX */
/*

$rgb = hextorgb('#fff000');
print_r($rgb);

*/

PHP - Convert PDF to JPG:

function pdfToJpg($pdf, $jpg) {
    $im = new Imagick();
    $im->setResolution(300,300);
    $im->readimage($pdf);
    $im->setImageFormat('jpeg');
    $im->writeImage($jpg);
    $im->clear();
    $im->destroy();
}

/* SYNTAX */
/*

This function is to convert PDF files into image file. It takes two params:

    string $pdf – Path to the initial PDF file
    string $jpg – Path to the image file

*/

PHP - Get age by birth date:

function getAge($birthdate = '0000-00-00') {
    if ($birthdate == '0000-00-00') return 'Unknown';

    $bits = explode('-', $birthdate);
    $age = date('Y') - $bits[0] - 1;

    $arr[1] = 'm';
    $arr[2] = 'd';

    for ($i = 1; $arr[$i]; $i++) {
        $n = date($arr[$i]);
        if ($n < $bits[$i])
            break;
        if ($n > $bits[$i]) {
            ++$age;
            break;
        }
    }
    return $age;
}

// This function is to get age by given birthday (format: YYYY-MM-DD)