This post has already been read 1542 times!

1. Human Readable Random String

This code will create a human readable string that will look more close to dictionary words, useful for captchas.

/**************
*@length - length of random string (must be a multiple of 2)
**************/
function readable_random_string($length = 6){
$conso=array("b","c","d","f","g","h","j","k","l",
"m","n","p","r","s","t","v","w","x","y","z");
$vocal=array("a","e","i","o","u");
$password="";
srand ((double)microtime()*1000000);
$max = $length/2;
for($i=1; $i<=$max; $i++)
{
$password.=$conso[rand(0,19)];
$password.=$vocal[rand(0,4)];
}
return $password;
}

2. Generate a Random String

If you don’t need human readable string, then use this function instead, which will create a random string you can use for user id’s etc.

/*************
*@l - length of random string
*/
function generate_rand($l){
  $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  srand((double)microtime()*1000000);
  for($i=0; $i<$l; $i++) {
	  $rand.= $c[rand()%strlen($c)];
  }
  return $rand;
 }

3. Encode Email Address

With this snippet, you can encode any email address into HTML entities so that spam bots do not find it.

function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' )
{
	// remplazar aroba y puntos
	$email = str_replace('@', '@', $email);
	$email = str_replace('.', '.', $email);
	$email = str_split($email, 5);

	$linkText = str_replace('@', '@', $linkText);
	$linkText = str_replace('.', '.', $linkText);
	$linkText = str_split($linkText, 5);
	
	$part1 = '<a href="ma';
	$part2 = 'ilto:';
	$part3 = '" '. $attrs .' >';
	$part4 = '</a>';

	$encoded = '<script type="text/javascript">';
	$encoded .= "document.write('$part1');";
	$encoded .= "document.write('$part2');";
	foreach($email as $e)
	{
			$encoded .= "document.write('$e');";
	}
	$encoded .= "document.write('$part3');";
	foreach($linkText as $l)
	{
			$encoded .= "document.write('$l');";
	}
	$encoded .= "document.write('$part4');";
	$encoded .= '</script>';

	return $encoded;
}

4. Validate email Address

E-mail validation is perhaps the most used validation in web forms, this code will validate email address and also optionally check the MX records of the domain provided in email address to make email validation more robust.

function is_valid_email($email, $test_mx = false)
{
	if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
		if($test_mx)
		{
			list($username, $domain) = split("@", $email);
			return getmxrr($domain, $mxrecords);
		}
		else
			return true;
	else
		return false;
}

5. List Directory Contents

function list_files($dir)
{
	if(is_dir($dir))
  	{
  		if($handle = opendir($dir))
  		{
  			while(($file = readdir($handle)) !== false)
  			{
  				if($file != "." && $file != ".." && $file != "Thumbs.db")
  				{
  					echo ''.$file.'
'."\n";
  				}
  			}
  			closedir($handle);
  		}
	}
}

6. Destroy Directory

Delete a directory including its contents.

/*****
*@dir - Directory to destroy
*@virtual[optional]- whether a virtual directory
*/
function destroyDir($dir, $virtual = false)
{
	$ds = DIRECTORY_SEPARATOR;
	$dir = $virtual ? realpath($dir) : $dir;
	$dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
	if (is_dir($dir) && $handle = opendir($dir))
	{
		while ($file = readdir($handle))
		{
			if ($file == '.' || $file == '..')
			{
				continue;
			}
			elseif (is_dir($dir.$ds.$file))
			{
				destroyDir($dir.$ds.$file);
			}
			else
			{
				unlink($dir.$ds.$file);
			}
		}
		closedir($handle);
		rmdir($dir);
		return true;
	}
	else
	{
		return false;
	}
}

7. Parse JSON Data

$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php

8. Parse XML Data

//xml string
$xml_string="

   
      Foo
      foo@bar.com
   
   
      Foobar
      foobar@foo.com
   
";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml->user as $user)
{
   //access attribute
   echo $user['id'], '  ';
   //subnodes are accessed by -> operator
   echo $user->name, '  ';
   echo $user->email, '
';
}

9. Create Post Slugs

Create user friendly post slugs from title string to use within URLs.

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

10. Get Real IP Address of Client

This function will fetch the real IP address of the user even if he is behind a proxy server.

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

11. Force file Download

Provide files to the user by forcing them to download.

/********************
*@file - path to file
*/
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";
    }
}

Leave a Reply

Post Navigation