Share 10 sections of PHP common code _php Instance

Source: Internet
Author: User
Tags explode extract zip file

This article brings together 10 pieces of code that are often used in PHP development, including email, 64-bit encoding and decoding, decompression, 64-bit encoding, parsing json, and so on, and I hope to help you.

1, use the PHP mail function to send email

$to = "viralpatel.net@gmail.com"; 
$subject = "Viralpatel.net"; 
$body = "Body of your message is here for 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, PHP 64-bit coding and decoding

function Base64url_encode ($plainText) {
$base) = Base64_encode ($plainText);
$base 64url = STRTR ($base, ' +/= ', '-_, ');
return $base 64url;
}
function Base64url_decode ($plainText) {
$base 64url = STRTR ($plainText, '-_, ', ' +/= ');
$base = Base64_decode ($base 64url);
return $base 64;

3. Get 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;
}

4. Date 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 to not
if (Checkdate ($parts [2], $parts [3], $parts [1])) return
true;
else return
false;
else return
false;

5. Verify Email

$email = $_post[' email '];
if (Preg_match) ("~ ([a-za-z0-9!#$%& ') *+-/=?^_`{|} ~]) @ ([a-za-z0-9-]).
   ([a-za-z0-9]{2,4}) ~ ", $email)) {
echo ' is a valid email.]
else{
Echo ' is a invalid email. '
}

6. Parse XML easily 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﹥ ";
The 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

﹤?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 would send an imitation 404 page if the user # types in this files to the address bar.
# only files, connecting with the same directory as this # file ' would be able to ' use it as a.
 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 ']). ' is not foundOn this server.﹤/p﹥ '. '
 N ". ' ﹤/body﹥﹤/html﹥ '.
 n ";
Exit  # in any file with want to connect to the database, # and in this case we'll name this file db.php # just add this line of PHP code (without the pound sign): # include "db.php";? ﹥

8. Create and parse JSON data

$json _data = array (' ID ' =﹥1, ' name ' =﹥ ' Rolf ', ' country ' =﹥ ' Russia ', '
Office ' =﹥array ("Google", "Oracle");
Echo Json_encode ($json _data);

9, processing MySQL time stamp

$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. Extract 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 ';
? ﹥

PHP common functions are as follows

1.PHP string

The string declares the variable = ' or ' (usually using single quotes because it is easier to write)

$str = ' Hello PHP ';
Echo $str;

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

$str = ' Hello PHP ';
Echo Strpos ($str, ' o '); Calculates the position of a character in a string
Echo ' <br/> ';
Echo Strpos ($str, ' PH ');

SUBSTR Intercept string

$str = ' Hello PHP ';
Intercept string
$str 1 = substr ($str, 2, 3);//intercept from 2-bit, intercept string
echo $str 3 with length 1;

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

Str_split split string fixed-length segmentation (default length is 1)

$str = ' Hello PHP ';
Split string
$result = Str_split ($STR);//Save the result to an array
print_r ($result);//Use Print_r to enter an array of
echo ' <br/> ' ;
$result 1 = str_split ($STR, 2);
Print_r ($result 1);

Explode (split character, string to be split) split by Space

$str = ' Hello PHP Java C # C + + ';
$result = Explode (", $str);
Print_r ($result);

Connection of strings

$str = ' Hello PHP Java C # C + + ';
The connection of the string
$num =;
$str 1 = $str. ' <br/>objective-c '. $num;
echo $str 1;
Echo ' <br/> ';
$str 2 = "$str <br/>objective-c $num"; Another simple method of writing
echo $str 2;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.