19 ultra-practical PHP code snippets _ php instance-php Tutorial

Source: Internet
Author: User
Every Programmer and developer likes to discuss their favorite code snippets, especially when PHP developers spend several hours coding for webpages or creating applications, they know the importance of these codes. To save coding time, the editor collects some useful code snippets to help developers improve their work efficiency. 1) Whois query using PHP -- get Whois requests using PHP

Using this code, you can obtain whois information in a specific domain name. Take the domain name as a parameter and display the relevant information of all domain names.

The code is as follows:

Function whois_query ($ domain ){

// Fix the domain name:
$ Domain = strtolower (trim ($ domain ));
$ Domain = preg_replace ('/^ http: \\// I', '', $ domain );
$ Domain = preg_replace ('/^ www \./I', '', $ domain );
$ Domain = explode ('/', $ domain );
$ Domain = trim ($ domain [0]);

// Split the TLD from domain name
$ _ Domain = explode ('.', $ domain );
$ Lst = count ($ _ domain)-1;
$ Ext = $ _ domain [$ lst];

// You find resources and lists
// Like these on wikipedia:
//
// Http://de.wikipedia.org/wiki/Whois </a>
//
$ Servers = array (
"Biz" => "whois. neulevel. biz ",
"Com" => "whois.internic.net ",
"Us" => "whois. nic. us ",
"Coop" => "whois. nic. coop ",
"Info" => "whois.nic.info ",
"Name" => "whois. nic. name ",
"Net" => "whois.internic.net ",
"Gov" => "whois.nic.gov ",
"Edu" => "whois.internic.net ",
"Mil" => "rs.internic.net ",
"Int" => "whois.iana.org ",
"Ac" => "whois. nic. ac ",
"AE" => "whois. uaenic. AE ",
"At" => "whois.ripe.net ",
"Au" => "whois.aunic.net ",
"Be" => "whois. dns. be ",
"Bg" => "whois.ripe.net ",
"Br" => "whois.registro.br ",
"Bz" => "whois. belizenic. bz ",
"Ca" => "whois. cira. ca ",
"Cc" => "whois. nic. cc ",
"Ch" => "whois. nic. ch ",
"Cl" => "whois. nic. cl ",
"Cn" => "whois.cnnic.net.cn ",
"Cz" => "whois. nic. cz ",
"De" => "whois.nic.de ",
"Fr" => "whois. nic. fr ",
"Hu" => "whois. nic. hu ",
"Ie" => "whois. domainregistry. ie ",
"Il" => "whois.isoc.org. il ",
"In" => "whois. ncst. ernet. in ",
"Ir" => "whois. nic. ir ",
"Mc" => "whois.ripe.net ",
"To" => "whois. tonic. ",
"TV" => "whois. TV ",
"Ru" => "whois.ripn.net ",
"Org" => "whois.pir.org ",
"Aero" => "whois. information. aero ",
"Nl" => "whais. domain-registry.nl"
);

If (! Isset ($ servers [$ ext]) {
Die ('Error: No matching nic server found! ');
}

$ Nic_server = $ servers [$ ext];

$ Output = '';

// Connect to whois server:
If ($ conn = fsockopen ($ nic_server, 43 )){
Fputs ($ conn, $ domain. "\ r \ n ");
While (! Feof ($ conn )){
$ Output. = fgets ($ conn, 128 );
}
Fclose ($ conn );
}
Else {die ('Error: cocould not connect to '. $ nic_server .'! ');}

Return $ output;
}


2) Text messaging with PHP using the TextMagic API -- use TextMagic API to get PHP Test information

TextMagic introduces powerful core APIs to easily send SMS messages to mobile phones. This API is billed.

The code is as follows:


The TextMagic PHP lib
Require ('textmagic-sms-api-php/TextMagicAPI. php ');

// Set the username and password information
$ Username = 'myusername ';
$ Password = 'mypassword ';

// Create a new instance of TM
$ Router = new TextMagicAPI (array (
'Username' => $ username,
'Password' => $ password
));

// Send a text message to '2017-123-4567'
$ Result = $ router-> send ('Wake up! ', Array (9991234567), true );

// Result: Result is: Array ([messages] => Array ([19896128] => 9991234567) [sent_text] => Wake up! [Parts_count] => 1)


3) Get info about your memory usage -- Get memory usage

This code helps you get the memory usage.

The code is as follows:


Echo "Initial:". memory_get_usage (). "bytes \ n ";
/* Prints
Initialize: 361400 bytes
*/

// Let's use up some memory
For ($ I = 0; I I <100000; $ I ++ ){
$ Array [] = md5 ($ I );
}

// Let's remove half of the array
For ($ I = 0; I I <100000; $ I ++ ){
Unset ($ array [$ I]);
}

Echo "Final:". memory_get_usage (). "bytes \ n ";
/* Prints
Final: 885912 bytes
*/

Echo "Peak:". memory_get_peak_usage (). "bytes \ n ";
/* Prints
Peak: 13687072 bytes
*/


4) Display source code of any webpage -- view the source code of any web page

If you want to view the source code of the webpage, you only need to change the URL of the second line and the source code will be displayed on the webpage.

The code is as follows:

$ Line ){
// Loop thru each line and prepend line numbers
Echo "Line # {$ line_num}:". htmlspecialchars ($ line )."
\ N ";
}


5) Create data uri's -- Create data uri

By using this code, you can create a data Uri, which is very useful for embedding images in HTML/CSS and can help save HTTP requests.

The code is as follows:


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


6) Detect location by IP -- retrieve the geographical location through IP

This code helps you find a specific IP address. you only need to enter an IP address in the function parameter to check the location.

The code is as follows:


Function detect_city ($ ip ){

$ Default = 'unknown ';

If (! Is_string ($ ip) | strlen ($ ip) <1 | $ ip = '2017. 0.0.1 '| $ ip = 'localhost') $ ip = '8. 8.8.8 '; $ curlopt_useragent = 'mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: 1.9.2) Gecko/20100115 Firefox/3.6 (. net clr 3.5.30729) '; $ url = 'http: // ipinfodb.com/ip_locator.php? Ip = '. urlencode ($ ip); $ ch = curl_init (); $ curl_opt = array (CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $ curlopt_useragent,
CURLOPT_URL => $ url,
CURLOPT_TIMEOUT => 1,
CURLOPT_REFERER => 'http: // '. $ _ SERVER ['http _ host'],
);

Curl_setopt_array ($ ch, $ curl_opt );

$ Content = curl_exec ($ ch );

If (! Is_null ($ curl_info )){
$ Curl_info = curl_getinfo ($ ch );
}

Curl_close ($ ch );

If (preg_match ('{
City: ([^ <] *)
} I ', $ content, $ regs) {$ city = $ regs [1];} if (preg_match ('{

State/Province: ([^ <] *)

} I ', $ content, $ regs) {$ state = $ regs [1];} if ($ city! = "& $ State! = ") {$ Location = $ city. ','. $ state; return $ location;} else {return $ default ;}}


7) Detect browser language -- view the browser language

Detects the code scripting language used by the 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;
}


8) Check if server is HTTPS -- Check whether the server is HTTPS

The code is as follows:

If ($ _ SERVER ['https']! = "On "){
Echo "This is not HTTPS ";
} Else {
Echo "This is HTTPS ";
}


9) Generate CSV file from a PHP array--generate a. CSV file in the PHP Group

The code is as follows:

Function generateCsv ($ data, $ delimiter = ',', $ enclosure = '"'){
$ Handle = fopen ('php: // temp ', 'R + ');
Foreach ($ data as $ line ){
Fputcsv ($ handle, $ line, $ delimiter, $ enclosure );
}
Rewind ($ handle );
While (! Feof ($ handle )){
$ Contents. = fread ($ handle, 8192 );
}
Fclose ($ handle );
Return $ contents;
}

10. find the distance between Longitudes and Latitudes

The code is as follows:

Function getDistanceBetweenPointsNew ($ latitude1, $ longitude1, $ latitude2, $ longitude2 ){
$ Theta = $ longitude1-$ longitude2;
$ Miles = (sin (deg 2rad ($ latitude1) * sin (deg 2rad ($ latitude2) + (cos (deg 2rad ($ latitude1 )) * cos (deg 2rad ($ latitude2) * cos (deg 2rad ($ theta )));
$ Miles = acos ($ miles );
$ Miles = rad2deg ($ miles );
$ Miles = $ miles * 60*1.1515;
$ Feet = $ miles * 5280;
$ Yards = $ feet/3;
$ Kilometers = $ mileage * 1.609344;
$ Meters = $ kilometers * 1000;
Return compact ('Miles ', 'feet', 'yards ', 'kilometers', 'meters ');
}

$ Point1 = array ('lat' => 40.770623, 'long' =>-73.964367 );
$ Point2 = array ('lat' => 40.758224, 'long' =>-73.917404 );
$ Distance = getDistanceBetweenPointsNew ($ point1 ['lat'], $ point1 ['long'], $ point2 ['lat'], $ point2 ['long']);
Foreach ($ distance as $ unit => $ value ){
Echo $ unit. ':'. number_format ($ value, 4 ).'
';
}



The example returns the following:

The code is as follows:

Miles: 2.6025
Feet: 13,741.4350
YSAS: 4,580.4783
Kilometers: 4.1884
Meters: 4,188.3894

11. Improve the cURL function

The code is as follows:

Function xcurl ($ url, $ ref = null, $ post = array (), $ ua = "Mozilla/5.0 (X11; Linux x86_64; rv: 2.2a1pre) gecko/20110324 Firefox/4.2a1pre ", $ print = false ){
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_AUTOREFERER, true );
If (! Empty ($ ref )){
Curl_setopt ($ ch, CURLOPT_REFERER, $ ref );
}
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_HEADER, 0 );
Curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, 1 );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
If (! Empty ($ ua )){
Curl_setopt ($ ch, CURLOPT_USERAGENT, $ ua );
}
If (count ($ post)> 0 ){
Curl_setopt ($ ch, CURLOPT_POST, 1 );
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post );
}
$ Output = curl_exec ($ ch );
Curl_close ($ ch );
If ($ print ){
Print ($ output );
} Else {
Return $ output;
}
}


12. clear user input

The code is as follows:

Function cleanInput ($ input ){

$ Search = array (
'@ ] *?>. *? Script @ Si', // Strip out javascript
'@ <[\/\!] *? [^ <>] *?> @ Si', // Strip out HTML tags
'@ ] *?>. *?@ SiU ', // Strip style tags properly
'@ @ '// Strip multi-line comments
);

$ Output = preg_replace ($ search, '', $ input );
Return $ output;
}
?>
Function sanitize ($ input ){
If (is_array ($ input )){
Foreach ($ input as $ var => $ val ){
$ Output [$ var] = sanitize ($ val );
}
}
Else {
If (get_magic_quotes_gpc ()){
$ Input = stripslashes ($ input );
}
$ Input = cleanInput ($ input );
$ Output = mysql_real_escape_string ($ input );
}
Return $ output;
}
?>


13. check geographic location by IP address (city or country)

The code is as follows:

Function detect_city ($ ip ){

$ Default = 'Hollywood, Ca ';

If (! Is_string ($ ip) | strlen ($ ip) <1 | $ ip = '2017. 0.0.1 '| $ ip = 'localhost') $ ip = '8. 8.8.8 '; $ curlopt_useragent = 'mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: 1.9.2) Gecko/20100115 Firefox/3.6 (. net clr 3.5.30729) '; $ url = 'http: // ipinfodb.com/ip_locator.php? Ip = '. urlencode ($ ip); $ ch = curl_init (); $ curl_opt = array (CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $ curlopt_useragent,
CURLOPT_URL => $ url,
CURLOPT_TIMEOUT => 1,
CURLOPT_REFERER => 'http: // '. $ _ SERVER ['http _ host'],
);

Curl_setopt_array ($ ch, $ curl_opt );

$ Content = curl_exec ($ ch );

If (! Is_null ($ curl_info )){
$ Curl_info = curl_getinfo ($ ch );
}

Curl_close ($ ch );

If (preg_match ('{


City: ([^ <] *)
} I ', $ content, $ regs) {$ city = $ regs [1];} if (preg_match ('{

State/Province: ([^ <] *)

} I ', $ content, $ regs) {$ state = $ regs [1];} if ($ city! = ''& $ State! = '') {$ Location = $ city. ','. $ state; return $ location;} else {return $ default ;}}


14. set password strength

The code is as follows:


Function password_strength ($ string ){
$ H = 0;
$ Size = strlen ($ string );
Foreach (count_chars ($ string, 1) as $ v ){
$ P = $ v/$ size;
$ H-= $ p * log ($ p)/log (2 );
}
$ Strength = ($ h/4) * 100;
'If ($ strength> 100 ){
$ Strength = 100;
}
Return $ strength;
}

Var_dump (password_strength ("Correct Horse Battery Staple "));
Echo"
";
Var_dump (password_strength ("Super Monkey Ball "));
Echo"
";
Var_dump (password_strength ("Tr0ub4dor & 3 "));
Echo"
";
Var_dump (password_strength ("abc123 "));
Echo"
";
Var_dump (password_strength ("sweet "));


15. check the browser language. only available $ availableLanguages can be used as an array ('en', 'Del', 'els ')

The code is as follows:

Function get_client_language ($ availableLanguages, $ default = 'en '){

If (isset ($ _ SERVER ['http _ ACCEPT_LANGUAGE ']) {

$ Langs = explode (',', $ _ SERVER ['http _ ACCEPT_LANGUAGE ']);

// Start going through each one
Foreach ($ langs as $ value ){

$ Choice = substr ($ value, 0, 2 );
If (in_array ($ choice, $ availableLanguages )){
Return $ choice;

}

}
}
Return $ default;
}

16. create a data URL

The code is as follows:

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


17. create a more friendly page title SEO URL

Input example: $ title = "This foo's bar is rockin 'Cool !"; Echo makeseoname ($ title); // RETURNS: // this-foos-bar-is-rockin-cool

The code is as follows:

Function make_seo_name ($ title ){
Return preg_replace ('/[^ a-z0-9 _-]/I', '', strtolower (str_replace ('', '-', trim ($ title ))));
}


18. ultimate encryption

The code is as follows:

// F (ucking) u (ncrackable) e (ncryption) function by BlackHatDBL (www.netforme.net)
Function fue ($ hash, $ times ){
// Execute the encryption (s) as frequently times as the user wants
For ($ I = $ times; $ I> 0; $ I --){
// Encode with base64...
$ Hash = base64_encode ($ hash );
// And md5...
$ Hash = md5 ($ hash );
// Sha1...
$ Hash = sha1 ($ hash );
// Sha256... (one more)
$ Hash = hash ("sha256", $ hash );
// Sha512
$ Hash = hash ("sha512", $ hash );

}
// Finaly, when done, return the value
Return $ hash;
}


19a. Tweeter Feed Runner -- use any twitter name to load user resources on any page.

The code is as follows:


Public function loadTimeline ($ user, $ max = 20 ){
$ This-> twitURL. = 'statuses/user_timeline.xml? Screen_name = '. $ user.' & count = '. $ max;
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ this-> twitURL );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );
$ This-> xml = curl_exec ($ ch );
Return $ this;
}
Public function getTweets (){
$ This-> twitterArr = $ this-> getTimelineArray ();
$ Tweets = array ();
Foreach ($ this-> twitterArr-> status as $ status ){
$ Tweets [$ status-> created_at->__ toString ()] = $ status-> text->__ toString ();
}
Return $ tweets;
}
Public function getTimelineArray (){
Return simplexml_load_string ($ this-> xml );
}
Public function formatTweet ($ tweet ){
$ Tweet = preg_replace ("/(http (. + ?)) (| $)/"," $1 $3 ", $ tweet );
$ Tweet = preg_replace ("/# (. + ?) (\ H | \ W | $)/"," #$1 $2 ", $ tweet );
$ Tweet = preg_replace ("/@ (. + ?) (\ H | \ W | $)/"," @ $1 $2 ", $ tweet );
Return $ tweet;
}


19b. Tweeter Feed Runner -- used to create files in a topic, for example, example. php

The code is as follows:


LoadTimeline ("phpsnips")-> getTweets ();
Foreach ($ feed as $ time => $ message ){
Echo"

". $ Twitter-> formatTweet ($ message )."
At: ". $ time ."

";
}
Related Article

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.