Thursday, 17 July 2014

Useful PHP code snippets for PHP web development

Posted by M2Software Solutions Solutions Pvt. Ltd | 23:06 Categories: ,

Hello friends...

Today i am here with some very useful PHP code snippets for PHP developer... have a look at this..

PHP code, PHP web development

1. Send Mail using mail function inEmail validation snippet in PHP.

$to = "";
$subject = "";
$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:\r\n";
$headers .= "Return-Path:\r\n";
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

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

3. Parsing XML in easy way using PHP.


//this is a sample xml string
$xml_string="<?xml version='1.0'?>
    <molecule name='Benzine'>
    <molecule name='Water'>
//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 />';

4. Generate An Authentication Code in 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";
    $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

5. HTTP Redirection in PHP

    header('Location: http://you_stuff/url.php'); // stick your url here


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

 7. Database Connection in 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".
    '<title>404 Not Found</title>'."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".
# 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";

Share your experience with us via comment...

Regards : M2 Software Solutions Pvt. Ltd.


Post a Comment

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube