Home > Backend Development > PHP Tutorial > Share 10 common PHP codes and share 10 php_PHP tutorials

Share 10 common PHP codes and share 10 php_PHP tutorials

WBOY
Release: 2016-07-12 09:05:05
Original
1181 people have browsed it

Share 10 pieces of commonly used PHP code, share 10 pieces of php

This article collects ten pieces of code frequently used in PHP development, including Email, 64-bit encoding and decoding, and decompression , 64-bit encoding, parsing JSON, etc. I hope it will be helpful to you.

1. Use PHP Mail function to send email

$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); 
?﹥
Copy after login

2. 64-bit encoding and decoding 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;
} 
Copy after login

3. Obtain the remote IP address

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;
}
Copy after login

4. Date formatting

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;
}
Copy after login

5. Verification Email

$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.';
}
Copy after login

6. Easily parse XML in PHP

//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 /﹥';
}

Copy after login

7. Database connection

﹤?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";
?﹥
Copy after login

8. Create and parse JSON data

$json_data = array ('id'=﹥1,'name'=﹥"rolf",'country'=﹥'russia',
"office"=﹥array("google","oracle"));
echo json_encode($json_data);
Copy after login

9. Processing MySQL timestamps

$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;
}
Copy after login

10. Decompress the 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';
?﹥
Copy after login

Common functions of PHP are as follows

1.PHP string

String declaration variable ='' or "" (usually single quotes are used because it is more convenient to write)

$str = 'Hello PHP';
echo $str;

strpos calculates the position of the character in the string (starting from 0)

$str = 'Hello PHP';
echo strpos($str,'o'); //Calculate the position of the character in the string
echo '
';
echo strpos($str,'PH');

substr intercepts the string

$str = 'Hello PHP';
//截取字符串
$str1 = substr($str,2,3); //从2位置开始截取,截取长度为3的字符串
echo $str1;
Copy after login

If the length parameter is not passed in, it will be intercepted from the specified position to the end of the string

str_split splits string fixed-length split (default length is 1)

$str = 'Hello PHP';
//分割字符串
$result = str_split($str); //将结果保存到一个数组中
print_r($result); //使用print_r输入一个数组
echo '<br/>';
$result1 = str_split($str,2);
print_r($result1);
Copy after login

explode (split character, string to be split) Split according to spaces

$str = 'Hello PHP Java C# C++';
$result = explode(' ',$str);
print_r($result);
Copy after login

Concatenation of strings

$str = 'Hello PHP Java C# C++';
//字符串的连接
$num = 100;
$str1 = $str.'<br/>Objective-C '.$num;
echo $str1;
echo '<br/>';
$str2 = "$str<br/>Objective-C $num"; //另一中简便的写法
echo $str2;
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1070273.htmlTechArticle Share 10 pieces of commonly used PHP code, share 10 pieces of php. This article collects ten pieces of code that are often used in PHP development. Including Email, 64-bit encoding and decoding, decompression, 64-bit encoding, parsing JSON, etc., hope...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template