15 Very useful PHP Snippet _php tutorial

Source: Internet
Author: User
Here are 15 of the most useful snippets of PHP code. You may also want to use any code or you can also share your code snippets in the comments section if you think it might be useful to others.
1. Send mail using the Mail function in PHP
Synchronize with the webmaster PHP tutorial
$to = "viralpatel.net@gmail.com";
$subject = "Viralpatel.net";
$body = "Body of your message" Here's 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) {
$base = Base64_encode ($plainText);
$base 64url = STRTR ($base 64, ' +/= ', '-_, ');
return $base 64url;
}

function Base64url_decode ($plainText) {
$base 64url = STRTR ($plainText, '-_, ', ' +/= ');
$base = Base64_decode ($base 64url);
return $base 64;
}
3. Get 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 function is used to obtain the real IP address of the customer.

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 period of the given time period 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 Snippet 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 was an invalid email. ';
}
6. An easy way to parse XML using PHP

Required Extensions: 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 is accessted by
echo $record [' name '], ';
Node is 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 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 into the address bar.
# only files connecting with in the same directory as this
# file'll is able to use it as well.
function send_404 ()
{
Header (' http/1.x 404 Not Found ');
print ''." N ".
''." N ".
' <title>404 Not Found</title>'." N ".
''." N ".
'

Not Found

'." N ".
'

The requested URL '.
Str_replace (strstr ($_server[' Request_uri '), '? '), ', $_server[' Request_uri ']).
' is not found on the this server.

'." N ".
''." n ";
Exit
}

# in any file you 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 in PHP

The following is the PHP code to create the JSON data format, 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 the JSON data into a 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 process 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 fragment will create a random authentication code, or just a random string.

# This particular code would generate a random string
# That's charicters long comes from the number
# That's 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 can save the string in
# there, and send the user an e-mail with the code in
# It they then can click a link or copy the code
# and you can then verify, that's the correct email
# or verify what ever you want to verify
?>
11. Date format validation 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 listing 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. Detecting scripts in the Php browser

$useragent = $_server [' http_user_agent '];
echo " Your User Agent is: " . $useragent;
?>
15. Zip file to extract a

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 do you do such a small collection of PHP code snippets. You may want to share your code snippets with others in comments.
Author: ssoftware

http://www.bkjia.com/PHPjc/478012.html www.bkjia.com true http://www.bkjia.com/PHPjc/478012.html techarticle Here are 15 of the most useful snippets of PHP code. You may also want to use any code or you can also share your code snippets in the comments section if you think it might be useful to others. ...

  • 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.