Very useful 9 pieces of PHP code snippets _php Tips

Source: Internet
Author: User
Tags explode get ip xpath

In this article, let's share some of the super useful PHP snippets I've collected. Let's take a look at it!
1. Create a data URI

Data URIs are useful when embedding images into HTML/CSS/JS to save HTTP requests, and can reduce the time to load a Web site. The following function can create a data URI based on $file.

function Data_uri ($file, $mime) {
 $contents =file_get_contents ($file);
 $base 64=base64_encode ($contents);
 echo "Data: $mime; base64, $base";
}

2. Merge JavaScript and CSS files

Another good advice to minimize HTTP requests and save page load times is to merge your CSS and JS files. While I recommend using a dedicated plug-in (such as minify), using PHP to merge files is also very easy. Let's take a look at:

function Combine_my_files ($array _files, $destination _dir, $dest _file_name) {
 if!is_file ($destination _dir. $ Dest_file_name)) {//continue only if file doesn ' t exist
 $content = ' ";
 foreach ($array _files as $file) {//loop through array list
 $content. = file_get_contents ($file);//read each file
 //you can use some sort of minifier here
 //minify_my_js ($content);
 $new _file = fopen ($destination _dir. $dest _file_name, "w"); Open file for writing
 fwrite ($new _file, $content);//write to Destination
 fclose ($new _file);
 Return ' <script src= '. $destination _dir. $dest _file_name. ' " ></script> '; Output combined file
 }else{
 //use stored file return
 ' <script src= '. $destination _dir. $dest _file _name. ' " ></script> '; Output combine file
 }
}

And, the usage is this:

$files = Array (
 ' http://example/files/sample_js_file_1.js ', ' http://example/files/sample_js_file_2.js ',
 ' http://example/files/beautyquote_functions.js ',
 ' http://example/files/crop.js ', '
 http://example/ Files/jquery.autosize.min.js ',
 );
Echo combine_my_files ($files, ' minified_files/', MD5 ("My_mini_file"). " JS ");

3. Check to see if your email has been read

When you send an e-mail message, you will want to know if your message has been read. Here's a very interesting piece of code that can record the IP address of your email and the actual date and time.

?
error_reporting (0);
Header ("Content-type:image/jpeg");
Get IP
if (!empty ($_server[' http_client_ip '))
{
 $ip =$_server[' http_client_ip '];
}
ElseIf (!empty ($_server[' http_x_forwarded_for '))
{
 $ip =$_server[' http_x_forwarded_for '];
}
else
{
 $ip =$_server[' remote_addr '];
}
Time
$actual _time = time ();
$actual _day = Date (' Y.m.d ', $actual _time);
$actual _day_chart = Date (' d/m/y ', $actual _time);
$actual _hour = Date (' h:i:s ', $actual _time);
Get Browser
$browser = $_server[' http_user_agent '];
LOG
$myFile = "Log.txt";
$fh = fopen ($myFile, ' A + ');
$stringData = $actual _day. ' ' . $actual _hour. ' ' . $ip. ' ' . $browser. ' ' . "\ r \ n";
Fwrite ($FH, $stringData);
Fclose ($FH);
Generate Image (Es. Dimesion is 1x1)
$newimage = Imagecreate (1,1);
$grigio = Imagecolorallocate ($newimage, 255,255,255);
Imagejpeg ($newimage);
Imagedestroy ($newimage);
? >

4. Extract keywords from web pages

As this little headline says: This snippet allows you to easily extract meta keywords from a Web page.

$meta = get_meta_tags (' http://www.emoticode.net/');
$keywords = $meta [' keywords '];
Split keywords
$keywords = explode (', ', $keywords);
Trim them
$keywords = Array_map (' Trim ', $keywords);
Remove empty values
$keywords = Array_filter ($keywords);
Print_r ($keywords);

5. Find all the links on the page

With DOM, you can easily crawl all the links on the page. Here's a working example:

$html = file_get_contents (' http://www.example.com ');
$dom = new DOMDocument ();
@ $dom->loadhtml ($html);
Grab all of the page
$xpath = new Domxpath ($dom);
$hrefs = $xpath->evaluate ("/html/body//a");
for ($i = 0; $i < $hrefs->length; $i + +) {
 $href = $hrefs->item ($i);
 $url = $href->getattribute (' href ');
 echo $url. ' <br/> ';
}

6. Automatically convert URLs to clickable hyperlinks

In WordPress, if you want to automatically convert all URLs into clickable hyperlinks in a string, then use the built-in function make_clickable () to make your own. If you need to do this outside of WordPress, then you can refer to the source code for the function in wp-includes/formatting.php:

function _MAKE_URL_CLICKABLE_CB ($matches) {$ret = '; $url = $matches [2]; if (empty ($url)) return $matches [0];//Remo Ved trailing [.,;:] from URL if In_array (substr ($url,-1), Array ('. ', ', ', '; ', ', ') = = True) {$ret = substr ($url,-
1);
$url = substr ($url, 0, strlen ($url)-1); return $matches [1]. "<a href=\" $url \ "rel=\" nofollow\ "> $url </a>".
$ret; function _MAKE_WEB_FTP_CLICKABLE_CB ($matches) {$ret = '; $dest = $matches [2]; $dest = ' http://'. $dest; if (Empty ($d
EST)) return $matches [0]; removed trailing [,;:] from URL if (substr ($dest,-1), Array ('. ', ', ', '; ', ', ') = = True) {$ret = substr (
$dest,-1);
$dest = substr ($dest, 0, strlen ($dest)-1); return $matches [1]. "<a href=\" $dest \ "rel=\" nofollow\ "> $dest </a>".
$ret; The function _MAKE_EMAIL_CLICKABLE_CB ($matches) {$email = $matches [2]. '@' .
$matches [3]; return $matches [1].
"<a href=\" mailto: $email \ "> $email </a>"; } function Make_clickable ($ret) {$ret = '.
$ret; In testing, the using arrays here is found to is faster $ret = Preg_replace_callback ([\s>]) ([\w]+?:/
/[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*) #is ', ' _MAKE_URL_CLICKABLE_CB ', $ret); $ret = Preg_replace_callback ([\s>]) ((WWW|FTP) \.[
\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*) #is ', ' _MAKE_WEB_FTP_CLICKABLE_CB ', $ret); $ret = Preg_replace_callback (' # ([\s>]) ([. 0-9a-z_+-]+) @ ([0-9a-z-]+\.)
+[0-9a-z]{2,}) #i ', ' _MAKE_EMAIL_CLICKABLE_CB ', $ret); This one isn't in a array because we need it to run last, for cleanup of accidental links within links $ret = Preg_re Place ("#" (<a ([^>]+?>|>)) <a [^>]+?> ([^>]+?)
</a></a> #i "," $1$3</a> ", $ret);
$ret = Trim ($ret);
return $ret;
 }

7. Download and save remote images on your server

Downloading an image on a remote server and saving it on your own server is useful when building a Web site, and it's also easy to do. The following two lines of code can be done for you.

$image = file_get_contents (' yun_qi_img/image.jpg ');
File_put_contents ('/images/image.jpg ', $image); Where to save the image

8. Detect Browser language

If your site uses multiple languages, it is useful to detect the browser language and use the language as the default language. The following code returns the language used by the client's browser.

function Get_client_language ($availableLanguages, $default = ' en ') {
if (isset ($_server[' http_accept_language ')) {
$langs =explode (', ', $_server[' http_accept_language '));
foreach ($langs as $value) {
$choice =substr ($value, 0,2);
if (In_array ($choice, $availableLanguages)) {return
$choice
} 
}} return $default;
}

9. Full text shows the number of Facebook fans

If your site or blog has a Facebook page, then you may want to show how many fans you have. This code snippet will help you get the number of Facebook fans. Don't forget to add your page ID to the second line. The page ID can be found at address Http://facebook.com/yourpagename/info.

<?php
$page _id = "302807633129400";
$xml = @simplexml_load_file ("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT% 20fan_count%20from%20page%20where%20page_id= ". $page _id." ") Or Die ("a lot");
$fans = $xml->page->fan_count;
echo $fans;
? >

The above is the entire content of this article, I hope to help you learn.

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.