Share 10 sections of PHP common code, Share 10 Section php_php tutorial

Source: Internet
Author: User

Share 10 sections of PHP common code, share 10 paragraphs PHP


This article brings together 10 pieces of code commonly used in PHP development, including email, 64-bit encoding and decoding, decompression, 64-bit encoding, parsing json, and so on, hoping 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" Here's 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.64-bit encoding and decoding in PHP

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

4. Date formatting

function Checkdateformat ($date) {//match The format of the Dateif (Preg_match ("/^ ([0-9]{4})-([0-9]{2})-([0-9]{2}) $/", $ Date, $parts) {//check Weather the date is valid of Notif (Checkdate ($parts [2], $parts [3], $parts [1])) return true; Elsereturn false;} Elsereturn 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 ' This was a valid email. ';} Else{echo ' This was an invalid email. ';}

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 E Ach node of Moleculeforeach ($xml-﹥molecule as $record) {//attribute is accessted by echo $record [' name '], ';//node ar e accessted by-﹥operator Echo $record-﹥symbol, "; echo $record-﹥code, ' ﹤br/﹥ ';}

7. Database connection

﹤?phpif (basename (__file__) = = basename ($_server[' php_self ')) send_404 (); $dbHost = "localhost"; Location of the 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 filename to the address bar.# only file  s connecting with in the same directory as this# file would be a 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 ']). ' is not found in this Server.﹤/p﹥ '. " N. ' ﹤/body﹥﹤/html﹥ '. " n "; Exit;} # in any file, want to connect to the database,# and in this case we'll name this file db.php# just add the PHP code (without the pound sign): # include "db.php";? ﹥

8. Creating and parsing JSON data

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

9. Processing MySQL Timestamp

$query = "Select Unix_timestamp (Date_field) as mydate from  mytable where 1=1", $records = mysql_query ($query) or Die (my Sql_error ()); while ($row = Mysql_fetch_array ($records)) {echo $row;}

10. Unzip 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:﹤?phpinclude ' 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 ' (the general case uses single quotes because it is easier to write)

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

Strpos to calculate the position of a character in a string (starting at 0)

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

SUBSTR Intercept string

$str = ' Hello PHP ';//intercept string $str1 = substr ($str, 2, 3); Intercept from 2 position, intercept string of length 3 echo $str 1;

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

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

$str = ' Hello PHP ';//split string $result = Str_split ($STR); Saves the result to an array of print_r ($result); Use Print_r to enter an array of echo '
'; $result 1 = Str_split ($STR, 2);p Rint_r ($result 1);

Explode (split character, string to be split) separated by space

$str = ' Hello PHP Java C # C + + '; $result = explode (', $str);p Rint_r ($result);

Connection of strings

$str = ' Hello PHP Java C # C + + ';//String Connection $num = +, $str 1 = $str. '
Objective-c '. $num, echo $str 1;echo '
'; $str 2 = "$str
Objective-c $num "; Another easy way to do echo $str 2;

http://www.bkjia.com/PHPjc/1070273.html www.bkjia.com true http://www.bkjia.com/PHPjc/1070273.html techarticle share 10 sections of PHP common code, share 10 sections of PHP This article collects PHP development often used in the 10 code, including email, 64-bit encoding and decoding, decompression, 64-bit encoding, parsing JSON, etc., I hope ...

  • Related Article

    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.