Very useful 9 PHP code snippets, _php tutorial

Source: Internet
Author: User
Tags xpath

A very useful 9 PHP code fragment,


In this article, we'll share some of the super-useful PHP snippets I've collected. Let's have a look!
1. Create a data URI

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

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

2. Merging JavaScript and CSS files

Another good idea to minimize HTTP requests and save page load times is to merge your CSS and JS files. Although I would recommend that you use a dedicated plugin (such as minify), it is also easy to use PHP to merge files. Let's take a look:

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 '; Output combined file}else{//use stored file return ';//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. 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, as well as the actual date and time.

<?error_reporting (0); Header ("Content-type:image/jpeg"),//get ipif (!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 ($grigio) = Imagecolorallocate ($newimage, 255,255,255); imagejpeg ($newimage); Imagedestroy ($newimage); >

4. Extracting keywords from web pages

As the 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 ($k Eywords);p Rint_r ($keywords);

5. Find all links on the page

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

$html = file_get_contents (' http://www.example.com '); $dom = new DOMDocument (); @ $dom->loadhtml ($html);//Grab all the On the Page$xpath = new Domxpath ($dom), $hrefs = $xpath->evaluate ("/html/body//a"); for ($i = 0; $i < $hrefs->lengt H $i + +) {$href = $hrefs->item ($i); $url = $href->getattribute (' href '); Echo $url. '
';}

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 get you going. If you need to do this outside of WordPress, then you can refer to the source code of the function in wp-includes/formatting.php:

function _MAKE_URL_CLICKABLE_CB ($matches) {$ret = '; $url = $matches [2];if (Empty ($url)) return $matches [0];//removed tr ailing [.,;:] from Urlif (In_array (substr ($url,-1), Array ('. ', ', ', '; ', ': ')) = = = True) {$ret = substr ($url,-1); $url = substr ($url, 0, strlen ($url)-1);} return $matches [1]. "$url". $ret;} function _MAKE_WEB_FTP_CLICKABLE_CB ($matches) {$ret = '; $dest = $matches [2]; $dest = ' http://'. $dest; if (empty ($dest)) return $matches [0];//removed trailing [,;:] from Urlif (In_array (substr ($dest,-1), Array ('. ', ', ', '; ', ': ')) = = = = True {$ret = substr ($dest,-1); $dest = substr ($dest, 0, strlen ($dest)-1);} return $matches [1]. "$dest". $ret;} function _MAKE_EMAIL_CLICKABLE_CB ($matches) {$email = $matches [2]. '@' . $matches [3];return $matches [1]. "$email";} function Make_clickable ($ret) {$ret = '. $ret;//In testing, using arrays-here is found to be faster$ret = Preg_replac E_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 was not in a array because we need it to run last, for CL Eanup of accidental links within Links$ret = Preg_replace ("# (]+?>|>)")]+?> ([^>]+?) #i "," $1$3 ", $ret); $ret = Trim ($ret); return $ret;}

7. Download and save the remote image on your server

Downloading an image on a remote server and saving it on its own server is useful when building a website, and it's easy to do. The following two lines of code will do it for you.

$image = file_get_contents (' http://www.url.com/image.jpg '); file_put_contents ('/images/image.jpg ', $image); Where to save the image

8. Detecting Browser language

If your site uses multiple languages, it can be useful to detect the browser language and use that language as the default language. The following code returns the language used by the client 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 showing the number of Facebook fans

If your site or blog has a Facebook page, you may want to show how many fans you have. This snippet can help you get the number of Facebook fans. Don't forget to add your page ID on 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 whole content of this article, I hope that everyone's study has helped.

Articles you may be interested in:

    • 7 super-useful PHP code Snippets
    • 10 useful snippets of PHP code
    • Common string processing code snippet collation in PHP
    • Super-Functional 7 PHP snippet sharing
    • PHP Security Detection Code snippet (share)
    • 19 Super-useful PHP code Snippets
    • 9 Classic PHP Code snippets to share
    • 10 super-useful PHP code Snippets
    • 46 very useful snippets of PHP code

http://www.bkjia.com/PHPjc/1120001.html www.bkjia.com true http://www.bkjia.com/PHPjc/1120001.html techarticle very useful 9 PHP code Snippets, this article we will share some of the super useful PHP code Snippets I collected. Let's have a look! 1. Create data URI data URI in embed diagram ...

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