15 useful PHP code snippets

Source: Internet
Author: User
The following are the fifteen most useful PHP code snippets. You may also want to share your code snippets with any code or comments if you think it may be useful to others. 1. Use the email sending function to synchronize the first mail with the PHP Tutorial of the webmaster in PHP & lt ;? Php $ to & quot; virphosphatase... SyntaxHighlighter. a below are fifteen most useful PHP code snippets. You may also want to share your code snippets with any code or comments if you think it may be useful to others.
1. Use the email sending function in PHP
Starting with the webmaster encyclopedia PHP Tutorial
$ To = "viralpatel.net@gmail.com ";
$ Subject = "VIRALPATEL.net ";
$ Body = "Body of your message here you can use HTML too. e.g.
Bold";
$ 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. Base64 encoding and decoding strings 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 in PHP
 
Function getRemoteIPAddress (){
$ Ip = $ _ SERVER ['remote _ ADDR '];
Return $ ip;
}
 
The above code will not work, in case your client proxy server is behind. In this case, the customer uses a function to obtain the real 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. Seconds to string
 
This function returns the time range in days, hours, minutes, and seconds.
For example, secsToStr (1234567) will return "14 days, 6 hours, 56 minutes, 7 Seconds"
 
Function secsToStr ($ secs ){
If ($ secs> = 86400) {$ days = floor ($ secs/86400); $ secs = $ secs % 86400; $ r = $ days. 'day'; if ($ days <> 1) {$ r. ='s ';} if ($ secs> 0) {$ r. = ',';}}
If ($ secs >=3600) {$ hours = floor ($ secs/3600); $ secs = $ secs % 3600; $ r. = $ hours. 'hour'; if ($ hours <> 1) {$ r. ='s ';} if ($ secs> 0) {$ r. = ',';}}
If ($ secs> = 60) {$ minutes = floor ($ secs/60); $ secs = $ secs % 60; $ r. = $ minutes. 'Minute '; if ($ minutes <> 1) {$ r. ='s ';} if ($ secs> 0) {$ r. = ',';}}
$ R. = $ secs. 'second'; if ($ secs <> 1) {$ r. ='s ';}
Return $ r;
}
5. Email verification code snippets in PHP
 
$ 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. Simple XML Parsing method using PHP
 
Required extension: SimpleXML
 
// This is a sample xml string
$ Xml_string ="


Ben
A


H2o
K

";
 
// 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
Echo $ record ['name'], '';
// Node are accessted by-> operator
Echo $ record-> symbol ,'';
Echo $ record-> code ,'
';
}
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''. "N ".
''. "N ".
' 404 Not Found'. "N ".
''. "N ".
'Not Found '. "n ".
'

The requested URL '.
Str_replace (strstr ($ _ SERVER ['request _ URI '],'? '), '', $ _ SERVER ['request _ URI']).
'Was not found on this server.

'. "N ".
''. "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 ";
?>
8. Create and parse JSON data in PHP
 
The following is the JSON data format created by the PHP code. the above example uses the PHP array.
 
$ Json_data = array ('id' => 1, 'name' => "rolf", 'Country' => 'Russia ', "office" => array ("google", "oracle "));
Echo json_encode ($ json_data );
 
The following code parses JSON data to the PHP array.
 
$ Json_string = '{"id": 1, "name": "rolf", "country": "russia", "office": ["google ", "oracle"]} ';
$ Obj = json_decode ($ json_string );
// Print the parsed data
Echo $ obj-> name; // displays rolf
Echo $ obj-> office [0]; // displays google
9. MySQL timestamp in PHP
 
$ 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. Generate an authentication code in PHP
 
This basic code snippet creates a random authentication code, or just a random string.
 
# This particle code will generate a random string
# That is 25 charicters long 25 comes from the number
# That is in the for loop
$ String = "abcdefghijklmnopqrstuvwxyz0123456789 ";
For ($ I = 0; $ I <25; $ I ++ ){
$ 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 is the correct email
# Or verify what ever you want to verify
?>
11. Verify the date format in PHP
 
Verify that a date is in the "yyyy mm dd" 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 of not
If (checkdate ($ parts [2], $ parts [3], $ parts [1])
Return true;
Else
Return false;
}
Else
Return false;
}
12. HTTP redirection in PHP
 
Header ('Location: http: // you_stuff/url. php'); // stick your url here
?>
13. Directory list in PHP
 
 
 
Function list_files ($ dir)
{
If (is_dir ($ dir ))
{
If ($ handle = opendir ($ dir ))
{
While ($ file = readdir ($ handle ))! = False)
{
If ($ file! = "." & $ File! = "..." & $ File! = "Thumbs. db"/* pesky windows, images ..*/)
{
Echo ''. $ file .'
'. "\ N ";
}
}
Closedir ($ handle );
}
}
}
 
/*
To use:
 
List_files ("images /");
?>
*/
?>
14. Check scripts in the PHP browser
 
$ Useragent = $ _ SERVER ['http _ USER_AGENT '];
Echo" Your User Agent is: ". $ Useragent;
?>
15. Decompress a Zip file
 
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:
Include 'functions. php ';
If (unzip ('zipedfiles/test.zip ', 'unziped/myNewZip '))
Echo 'Success! ';
Else
Echo 'error ';
?>
 
How can you collect small PHP code snippets like this. You may want to share your code snippets with others in comments.
Author: ssoftware

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.