1. Base64 Encode and Decode String in PHP
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;
}
Code language: PHP (php)
2. Get Remote IP Address in PHP
function getRemoteIPAddress() {
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
Code language: PHP (php)
The above code will not work in case your client is behind proxy server. In that case use below function to get real IP address of client.
function getRealIPAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
Code language: PHP (php)
3. Seconds to String
This function will return the duration of the given time period in days, hours, minutes and seconds.
e.g. secsToStr(1234567) would return “14 days, 6 hours, 56 minutes, 7 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;
}
Code language: PHP (php)
4. Email validation snippet in PHP
$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
echo 'This is a valid email.';
} else{
echo 'This is an invalid email.';
}
Code language: PHP (php)
5. Parsing XML in easy way using PHP
Required Extension:
SimpleXML
$xml_string="<?xml version='1.0'?>
<moleculedb>
<molecule name='Benzine'>
<symbol>ben</symbol>
<code>A</code>
</molecule>
<molecule name='Water'>
<symbol>h2o</symbol>
<code>K</code>
</molecule>
</moleculedb>";
$xml = simplexml_load_string($xml_string);
foreach ($xml->molecule as $record)
{
echo $record['name'], ' ';
echo $record->symbol, ' ';
echo $record->code, '<br />';
}
Code language: PHP (php)
6. Database Connection in PHP
<?php
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost";
$dbUser = "xxxx";
$dbPass = "xxxx";
$dbDatabase = "xxxx";
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
function send_404()
{
header('HTTP/1.x 404 Not Found');
print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."n".
'<html><head>'."n".
'<title>404 Not Found</title>'."n".
'</head><body>'."n".
'<h1>Not Found</h1>'."n".
'<p>The requested URL '.
str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
' was not found on this server.</p>'."n".
'</body></html>'."n";
exit;
}
?>
Code language: PHP (php)
7. Creating and Parsing JSON data in PHP
Following is the PHP code to create the JSON data format of above example using array of PHP.
$json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
echo json_encode($json_data);
Code language: PHP (php)
Following code will parse the JSON data into PHP arrays.
$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
$obj=json_decode($json_string);
echo $obj->name;
echo $obj->office[0];
Code language: PHP (php)
8. Process MySQL Timestamp in PHP
$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records))
{
echo $row;
}
Code language: PHP (php)
9. Generate An Authentication Code in PHP
This basic snippet will create a random authentication code, or just a random string.
<?php
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<25;$i++){
$pos = rand(0,36);
$str .= $string{$pos};
}
echo $str;
?>
Code language: PHP (php)
10. Date format validation in PHP
Validate a date in “YYYY-MM-DD” format.
function checkDateFormat($date)
{
if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
{
if(checkdate($parts[2],$parts[3],$parts[1]))
return true;
else
return false;
}
else
return false;
}
Code language: PHP (php)
11. HTTP Redirection in PHP
<?php
header('Location: http://you_stuff/url.php');
?>
Code language: PHP (php)
12. Directory Listing in PHP
<?php
function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "." && $file != ".." && $file != "Thumbs.db")
{
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
}
}
closedir($handle);
}
}
}
?>
Code language: PHP (php)
13. Browser Detection script in PHP
<?php
$useragent = $_SERVER ['HTTP_USER_AGENT'];
echo "<b>Your User Agent is</b>: " . $useragent;
?>
Code language: PHP (php)
14. Unzip a Zip File
<?php
function unzip($location,$newLocation){
if(exec("unzip $location",$arr)){
mkdir($newLocation);
for($i = 1;$i< count($arr);$i++){
$file = trim(preg_replace("~inflating: ~","",$arr[$i]));
copy($location.'/'.$file,$newLocation.'/'.$file);
unlink($location.'/'.$file);
}
return TRUE;
}else{
return FALSE;
}
}
?>
Comments
Post a Comment