Chủ Nhật, 9 tháng 9, 2012

Các hàm hữu dụng PHP

1. Send Mail using mail function in PHP

$to = "viralpatel.net@gmail.com";
$subject = "VIRALPATEL.net";
$body = "Body of your message here you can use HTML too. e.g. <br> <b> Bold </b>";
$headers = "From: Peter\r\n";
$headers .= "Reply-To: info@yoursite.com\r\n";
$headers .= "Return-Path: info@yoursite.com\r\n";
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$body,$headers);
?>

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

3. Get Remote IP Address in PHP

function getRemoteIPAddress() {
    $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;
}
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']))   //check ip from share internet
    {
        $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;
}

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

5. Email validation snippet in PHP

$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&amp;'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
    echo 'This is a valid email.';
} else{
    echo 'This is an invalid email.';
}

6. Parsing XML in easy way using PHP

Required Extension: SimpleXML
//this is a sample xml string
$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>";
//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);
//loop through the each node of molecule
foreach ($xml->molecule as $record)
{
   //attribute are accessted by
   echo $record['name'], '  ';
   //node are accessted by -> operator
   echo $record->symbol, '  ';
   echo $record->code, '<br />';
}

7. Database Connection in PHP

<?php
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost";        //Location Of Database usually its localhost
$dbUser = "xxxx";            //Database User Name
$dbPass = "xxxx";            //Database Password
$dbDatabase = "xxxx";       //Database Name
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
# This function will send an imitation 404 page if the user
# types in this files filename into the address bar.
# only files connecting with in the same directory as this
# file will be able to use it as well.
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;
}
# In any file you want to connect to the database,
# and in this case we will name this file db.php
# just add this line of php code (without the pound sign):
# include"db.php";
?>

8. 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);
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);
//print the parsed data
echo $obj->name; //displays rolf
echo $obj->office[0]; //displays google

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

10. Generate An Authentication Code in PHP

This basic snippet will create a random authentication code, or just a random string.


<?php
# This particular code will generate a random string
# that is 25 charicters long 25 comes from the number
# that is in the for loop
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<25;$i++){
$pos = rand(0,36);
$str .= $string{$pos};
}
echo $str;
# If you have a database you can save the string in
# there, and send the user an email with the code in
# it they then can click a link or copy the code
# and you can then verify that that is the correct email
# or verify what ever you want to verify
?>


11. Date format validation in PHP

Validate a date in “YYYY-MM-DD” format.


function checkDateFormat($date)
{
//match the format of the date
if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
{
//check weather the date is valid of not
if(checkdate($parts[2],$parts[3],$parts[1]))
return true;
else
return false;
}
else
return false;
}

12. HTTP Redirection in PHP


<?php
header('Location: http://you_stuff/url.php'); // stick your url here
?>
13. Directory Listing in PHP
<?php

function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db"/*pesky windows, images..*/)
{
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
}
}
closedir($handle);
}
}
}

/*
To use:

<?php
list_files("images/");
?>
*/
?>

14. Browser Detection script in PHP



<?php
$useragent = $_SERVER ['HTTP_USER_AGENT'];
echo "<b>Your User Agent is</b>: " . $useragent;
?>

15. 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;
}
}
?>
//Use the code as following:
<?php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
echo 'Success!';
else
echo 'Error';
?>

How you like this small collection of PHP code snippets. You may want to paste your code snippet in the comment section below and share it with others.

**************************************************************************

array_push()



Inserts one or more elements to the end of an array.

Code: PHP
$arr = array('Shabbir','Pradeep');    //Add one more element  array_push($arr,'Tanaz');    print_r($arr);    /*  Output:  Array  (      [0] => Shabbir      [1] => Pradeep      [2] => Tanaz  )  */

array_pop()



Deletes the last element of an array.

Code: PHP
$stack = array("orange", "banana", "apple", "raspberry");  $fruit = array_pop($stack);  print_r($stack);    /*  After this, $stack will have only 3 elements:  Array  (      [0] => orange      [1] => banana      [2] => apple  )    and raspberry will be assigned to $fruit.  */

array_shift()



Removes the first element from an array, and returns the value of the removed element.

Code: PHP
$stack = array("orange", "banana", "apple", "raspberry");  $fruit = array_shift($stack);  print_r($stack);    /*  This would result in $stack having 3 elements left:  Array  (      [0] => banana      [1] => apple      [2] => raspberry  )    and orange will be assigned to $fruit.  */

array_unshift()



Adds one or more elements to the beginning of an array.

Code: PHP
$queue = array("orange", "banana");  array_unshift($queue, "apple", "raspberry");  print_r($queue);      /*  Output  Array  (      [0] => apple      [1] => raspberry      [2] => orange      [3] => banana  )  */

array_unique()



Removes duplicate values from an array.array_unique() takes input array and returns a new array without duplicate values.

Code: PHP
$input = array("a" => "green", "red", "b" => "green", "blue", "red");  $result = array_unique($input);  print_r($result);    /*  Output  Array  (      [a] => green      [0] => red      [1] => blue  )  */

in_array()



Checks if a value exists in an array.

Code: PHP
$os = array("Mac", "NT", "Irix", "Linux");  if (in_array("Irix", $os))  {      echo "Got Irix";  }  if (in_array("mac", $os))  {      echo "Got mac";  }    /*  The second condition fails because in_array() is case-sensitive, so the program above will display:    Got Irix  */

array_walk()



Apply a user function to every member of an array.

Code: PHP
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");    function test_alter(&$item1, $key, $prefix)  {      $item1 = "$prefix: $item1";  }    function test_print($item2, $key)  {      echo "$key. $item2<br />\n";  }    echo "Before ...:\n";  array_walk($fruits, 'test_print');    array_walk($fruits, 'test_alter', 'fruit');  echo "... and after:\n";    array_walk($fruits, 'test_print');    /*  The above example will output:  Before ...:  d. lemon  a. orange  b. banana  c. apple  ... and after:  d. fruit: lemon  a. fruit: orange  b. fruit: banana  c. fruit: apple  */

array_combine()



Creates an array by using one array for keys and another for its values.

Code: PHP
$a = array('green', 'red', 'yellow');  $b = array('avocado', 'apple', 'banana');  $c = array_combine($a, $b);    print_r($c);    /*  The above example will output:    Array  (      [green]  => avocado      [red]    => apple      [yellow] => banana  )  */

end()



Sets the internal pointer of an array to its last element.This function can be used to get the last element of an array.

Code: PHP
$fruits = array('apple', 'banana', 'cranberry');  echo end($fruits); // cranberry  
These functions make our work a bit more easier, I consider these are the most frequently used array functions, but this is not all that PHP offers, a lot more can be found at the PHP website. 


7 Useful functions to tighten the security in PHP


Security is a very important aspect of programming. In PHP, there are few useful functions which is very handy for preventing your website from various attacks like SQL Injection Attack , XSS attack etc.Let’s check few useful functions available in PHP to tighten the security in your project. But note that this is not a complete list, it just list of functions which I found useful for using in your project.
1) mysql_real_escape_string() - This function is very useful for preventing from SQL Injection Attack in PHP . This function adds backslashes to the special characters like quote , double quote , backslashes to make sure that the user supplied input are sanitized before using it to query. But, make sure that you are connected to the database to use this function.
2) addslashes() – This function works similar as mysql_real_escape_string(). But make sure that you don’t use this function when “magic_quotes_gpc” is “on” in php.ini. When “magic_quotes_gpc” is on in php.ini then single quote(‘) and double quotes (“) are escaped with trailing backslashes in GET, POST and COOKIE variables. You can check it using the function “get_magic_quotes_gpc()” function available in PHP.
3) htmlentities() – This function is very useful for to sanitize the user inputted data. This function converts the special characters to their html entities. Such as, when the user enters the characters like “<” then it will be converted into it’s HTML entities < so that preventing from XSS and SQL injection attack.
4) strip_tags() – This function removes all the HTML, JavaScript and php tag from the string. But you can also allow particular tags to be entered by user using the second parameter of this function. For example,
echo strip_tags(“<script>alert(‘test’);</script>”);
will output
alert(‘test’);
5) md5() – Some developers store plain password in the database which is not good for security point of view. This function generates md5 hash of 32 characters of the supplied string. The hash generated from md5() is not reversible i.e can’t be converted to the original string.
6) sha1() – This function is similar to md5 but it uses different algorithm and generates 40 characters hash  of a string compared to 32 characters by md5().
7) intval() – Please don’t laugh. I know this is not a security function, it is function which gets the integer value from the variable. But you can use this function to secure your php coding. Well, most the values supplied in GET method in URL are the id from the database and if you’re sure that the supplied value must be integer then you can use this function to secure your code.
$sql=”SELECT * FROM product WHERE id=”.intval($_GET['id']);
As, you can see above, if you’re sure that the input value is integer you can use intval() as a secrity function as well.


Không có nhận xét nào:

Đăng nhận xét