Share 10 common PHP Codes

Source: Internet
Author: User
This article collects time-frame code frequently used in PHP development, including Email, decompression, 64-bit encoding, and JSON parsing. For more information about common php code, see

This article collects time-frame code frequently used in PHP development, including Email, decompression, 64-bit encoding, and JSON parsing. For more information about common php code, see

1. Use the PHP Mail function to send an 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: 100 '. "\ 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

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

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 is a valid email. ';} else {echo 'this is an invalid email .';}

6. Easily Parse XML in PHP

// This is a sample xml string $ xml_string = "<? Xml version = '1. 0 '? > <Moleculedb> <molecule> <symbol> ben </symbol> <code> A </code> </molecule> <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 moleculeforeach ($ 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

<? Phpif (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") ordie ("Error connecting to database. "); mysql_select_db (" $ dbDatabase ", $ db) or die (" Couldn't sele Ct 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 ". '

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. Process MySQL Timestamp

$ 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. 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. 'http: // www.jb51.net/'.w.file,$newlocation.'http://www.jb51.net/'.w.file); unlink ($ location. 'http: // www.jb51.net/'.w.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 ';? >

Common PHP functions are as follows:

1. PHP string

String declaration variable = ''or" "(single quotation marks are generally used, 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 the character in the string.
Echo'
';
Echo strpos ($ str, 'ph ');

Substr truncated string

$ Str = 'Hello php'; // capture string $ str1 = substr ($ str, 2, 3); // start from 2, truncate a string of 3 echo $ str1;

If the length parameter is not input, it is intercepted from the specified position until the end of the string.

Str_split: Splits a string with a fixed length (the default length is 1)

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.