9 Practical PHP code snippets

Source: Internet
Author: User
Tags get ip
This article mainly introduces nine Practical PHP code snippets, this article explains how to check whether emails have been read, extract keywords from webpages, search for all links on the page, and automatically convert URLs to clickable hyperlinks. For more information, see 1. check whether the email has been read

When you send an email, you are sure to know whether your email has been viewed by the recipient. The following code records the IP address of your email, as well as the actual reading date and time.

The code is as follows:


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 );
?>


Source code: http://www.emoticode.net/php/code-to-find-out-if-your-email-has-been-read.html

2. extract keywords from webpages

This excellent code can be used to extract keywords from webpages.

The code is as follows:


$ Meta = get_meta_tags ('http: // www.emoticode.net /');
$ Keywords = $ meta ['keyword'];
// Split keywords
$ Keywords = explode (',', $ keywords );
// Trim them
$ Keywords = array_map ('trim', $ keywords );
// Remove empty values
$ Keywords = array_filter ($ keywords );
Print_r ($ keywords );


Source code: http://www.emoticode.net/php/extract-keywords-from-any-webpage.html

3. search for all links on the page

With DOM, you can capture links on any page, as shown in the following example.

The code is as follows:


$ Html = file_get_contents ('http: // www.php100.com ');
$ Dom = new DOMDocument ();
@ $ Dom-> loadHTML ($ html );
// Grab all the on the page
$ Xpath = new DOMXPath ($ dom );
$ Hrefs = $ xpath-> evaluate ("/html/body // ");
For ($ I = 0; $ I <$ hrefs-> length; $ I ++ ){
$ Href = $ hrefs-> item ($ I );
$ Url = $ href-> getAttribute ('href ');
Echo $ url .'';
}


Source code: http://snipplr.com/view/70489/find-all-links-on-a-page/

4. automatically convert URLs to clickable hyperlinks

In Wordpress, if you want to automatically convert all URLs to clickable hyperlinks, you can use the built-in function make_clickable. When you operate outside WordPress, you can refer to the source code in wp-uplodes/formatting. php.

The code is as follows:


Function _ make_url_clickable_cb ($ matches ){
$ Ret = '';
$ Url = $ matches [2];

If (empty ($ url ))
Return $ matches [0];
// Removed 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]. "$ 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 URL
If (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 was found to be 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 is not in an array because we need it to run last, for cleanup of accidental links within links
$ Ret = preg_replace ("# (] +?> |>)] +?> ([^>] + ?) # I "," $1 $3 ", $ ret );
$ Ret = trim ($ ret );
Return $ ret;
}


Source code: http://zenverse.net/php-function-to-auto-convert-url-into-hyperlink/

5. create a data URI

Data URI can help embed images into HTML, CSS, and JS to save HTTP requests. The following functions can use $ file to create a data URI.

The code is as follows:


Function data_uri ($ file, $ mime ){
$ Contents = file_get_contents ($ file );
$ Base64 = base64_encode ($ contents );
Echo "data: $ mime; base64, $ base64 ";
}


Source code: http://css-tricks.com/snippets/php/create-data-uris/

6. download and save remote images to your server

When you build a website, you may download images from the remote server and save them to your own server. the following code can help you implement this function.

The code is as follows:


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


Source code: http://www.catswhocode.com/blog/snippets/download-save-a-remote-image-on-your-server-using-php

7. remove Microsoft Word HTML tags

When you use Microsoft Word, you will create many tag tags, such as font, span, style, and class. these tags are very useful in Word, however, when you paste text from Word to a webpage, many useless labels will appear. The following practical functions can help you clear all the Word HTML tags.

The code is as follows:


Function cleanHTML ($ html ){
///
/// Removes all FONT and SPAN tags, and all Class and Style attributes.
/// Designed to get rid of non-standard Microsoft Word HTML tags.
///
// Start by completely removing all unwanted tags
$ Html = ereg_replace ("<(/)? (Font | span | del | ins) [^>] *> "," ", $ html );
// Then run another pass over the html (twice), removing unwanted attributes
$ Html = ereg_replace ("<([^>] *) (class | lang | style | size | face) = ("[^"] * "| '[^'] * '| [^>] +) ([^>] *)> ", "<\ 1>", $ html );
$ Html = ereg_replace ("<([^>] *) (class | lang | style | size | face) = ("[^"] * "| '[^'] * '| [^>] +) ([^>] *)> ", "<\ 1>", $ html );
Return $ html
}


Source code: http://tim.mackey.ie/CommentView,guid,2ece42de-a334-4fd0-8f94-53c6602d5718.aspx

8. check the browser language

If your website is in multiple languages, the following code can help you detect the browser language. it will return the default language of the client browser.

The code is as follows:


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


Source code: http://snipplr.com/view/12631/detect-browser-language/

9. display the number of Facebook fans

If you link a Facebook page to your website or blog, you may want to display the number of followers on Facebook. the following code can help you get the number of followers, in addition, do not forget to add your page ID in the second line of code.

The code is as follows:


$ Page_id = "your page-ID ";
$ Xml = @ simplexml_load_file ("http://api.facebook.com/restserver.php? Method = facebook. fql. query & query = SELECT % 20fan_count % 20 FROM % 20 page % 20 WHERE % 20page_id = ". $ page_id. "") or die ("a lot ");
$ Fans = $ xml-> page-> fan_count;
Echo $ fans;
?>


Source code: http://www.wprecipes.com/display-number-of-facebook-fans-in-full-text-on-your-wordpress-blog

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.