Archive for the 'PHP' Category

Random Password in PHP

A simple way to create a random password in PHP

$password = substr(md5(time()), 0, rand(4,8));

Force Download Dialog with PHP using octect-stream

Use this code to force a download of any type of content with PHP

header('Content-Disposition: attachment; filename=filename_' . date('Y-m-d') . '.sql');
print "Hello World";

Compress PHP Output from .htaccess

Compress all PHP output by adding this line to .htaccess file

php_value output_handler ob_gzhandler 

301 Redirect using PHP

301 Redirect using PHP

header ('HTTP/1.1 301 Moved Permanently');
header ('Location: '.$new_location);

CSV Export/Import Functions in PHP

Functions to Export and import CSV data using PHP

//*Get the result of the query as a CSV stream.
function CSVExport($query) {
	global $sql;
	$sql_csv = $sql->getSqlHandle($query);
	while($row = mysql_fetch_row($sql_csv)) {
		$row = $sql->_stripsls($row);
		print '"' . implode('","',$row) . "\"\n";

HTTP Digest Authentication with PHP

The code for using HTTP Digest Authentication with PHP.

$realm = 'Restricted area';

if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
    die('Text to send if user hits Cancel button');

if (!empty($_SERVER['PHP_AUTH_DIGEST'])) {
	$data = parseHttpDigest($_SERVER['PHP_AUTH_DIGEST']);
	if(!$data) die('Wrong Credentials!');

	// generate the valid response
	$password = 'mypass';//$sql->getOne("SELECT password FROM User WHERE username=".$data['username']);
	$A1 = md5($data['username'] . ':' . $realm . ':' . $password);
	$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
	$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

	if ($data['response'] != $valid_response) die('Wrong Credentials!');

	// ok, valid username & password
	print 'Doors open, beds made - welcome home';

//Function to parse the http auth header
function parseHttpDigest($digest) {
	//username="admin", realm="Restricted area", nonce="467f579606f46", uri="/Projects/Nexty/Tests/auth.php", algorithm="MD5", qop="auth", cnonce="zaR5Of4nOsWwx9nA", nc=00000001, response="27212bf93d58fc12b5b7f5b0b95dc38b", opaque="cdce8a5c95a1427d74df7acbf41c9ce0"

    //Protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);

    $data = array();
    $parts = explode(", ", $digest);

    foreach ($parts as $element) {
		$bits = explode("=", $element);
		$data[$bits[0]] = str_replace('"','', $bits[1]);

    return $needed_parts ? false : $data;


Searching text in a directory using find and grep

Use find and grep to search for a specific text in a directory. In this example, we search for files which uses the PHP short tag – <?

find -name '*.php' -exec grep '<?[^p\=]' {} \;

Find Difference Between 2 Dates in PHP

This function will find the difference between two given times. Does PHP already have a native function for that?

//The difference between 2 given time
function dateDifference($day_1,$day_2) {
	$diff = strtotime($day_1) - strtotime($day_2);

	$sec   = $diff % 60;
	$diff  = intval($diff / 60);
	$min   = $diff % 60;
	$diff  = intval($diff / 60);
	$hours = $diff % 24;
	$days  = intval($diff / 24);
	return array($sec,$min,$hours,$days);

If you just want the day difference…

$diff = strtotime($day_1) - strtotime($day_2) + 1; //Find the number of seconds
$day_difference = ceil($diff / (60*60*24)) ;  //Find how many days that is

This can be done using the DATEDIFF function in MySQL 5


Using PHP’s Curl functions behind a Proxy

Using PHP’s Curl functions even if the net is accessible only thru a proxy. This is the only way curl can be used if you use GoDaddy’s hosting.

$ch = curl_init("");

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXY, "");
curl_setopt($ch, CURLOPT_PROXYPORT, 80);
//curl_setopt ($ch, CURLOPT_PROXYUSERPWD, "username:password");

$data = curl_exec ($ch);
print $data;