Every programmer and developer likes to talk about their favorite pieces of code, especially when PHP developers spend hours coding or creating apps for the web, they know the importance of the code. In order to save the coding time, the author collects some useful code snippets to help the developers improve their work efficiency. >>>
1 whois query using php--use PHP to get WHOIS requests
Using this code, WHOIS information can be obtained in a particular domain. Take the domain name as a parameter and display information about all the domain names.
The code is as follows |
Copy Code |
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];
Lists
Like this on Wikipedia:
//
<a href= "Http://de.wikipedia.org/wiki/Whois" >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.to",
"TV" => "Whois.tv",
"Ru" => "whois.ripn.net",
"org" => "whois.pir.org",
"Aero" => "Whois.information.aero",
"NL" => "whois.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. " RN ");
while (!feof ($conn)) {
$output. = Fgets ($conn, 128);
}
Fclose ($conn);
}
else {die (' error:could not connect to '. $nic _server. '!'); }
return $output;
} |
2) Text Messaging with PHP using the textmagic api--use the textmagic API to obtain PHP test information
Textmagic introduces a powerful core API that makes it easy to send SMS to your phone. The API is to be paid for.
The
code is as follows |
copy code |
the textmagic PHP lib require (' textmagic-sms-api-php/textmagicapi.php '); &NBSP //Set the username and password information $username = ' myusername '; $password = ' mypassword '; &N Bsp //Create A new instance of TM $router = new Textmagicapi Array ( ' username ' => $usernam E, ' password ' => $password )); //Send a text message to ' 999-123-4567 ' $result = $router->send (' Wake up! ', Array (9991234567), Tru e); //result: result Is:array ([messages] => Array ([19896128] => 9991234567) [Sent_text] =&G T Wake up! [Parts_count] => 1) |
3 Get info about your memory usage--getting memory usage
This code helps you get memory usage.
code is as follows |
copy code |
echo" Initial: ". Memory_get_usage ()." Bytes n "; /* Prints initial:361400 bytes */ //Let ' s with up some memory for ($i = 0; $i < 100000 ; $i + +) { $array []= MD5 ($i); } &NBSP //Let's remove half of the array for ($i = 0; $i < 100000; $i + +) { unset ($a rray[$i]); } Echo Final:. Memory_get_usage (). "Bytes n"; /* Prints final:885912 bytes */ &NBSP ; echo "Peak:". Memory_get_peak_usage (). "Bytes n"; /* Prints peak:13687072 bytes */ |
4 Display Source Code of any webpage--view any Web page sources
If you want to see the source code for the page, just change the URL of the second line and the source code will be displayed on the page.
The code is as follows |
Copy Code |
<?php//Display source Code $lines = file (' http://google.com/'); foreach ($lines as $line _num => $line) { loop thru each line and prepend line numbers echo "line #{$line _num}:". Htmlspecialchars ($line). " n "; } |
5 The Create Data URI ' s--creates the date URI
By using this code, you can create a data URI that is useful for embedding pictures in Html/css to help save HTTP requests.
The code is as follows |
Copy Code |
function Data_uri ($file, $mime) { $contents =file_get_contents ($file); $base 64=base64_encode ($contents); echo "Data: $mime; base64, $base 64"; } |
6) Detect location by ip--retrieves the location via IP
This code helps you to find a specific IP, just enter the IP on the function parameters, you can detect the location.
The code is as follows |
Copy Code |
function Detect_city ($IP) {
$default = ' UNKNOWN ';
if (!is_string ($IP) | | strlen ($IP) < 1 | | $ip = = ' 127.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 Browser language
Detects the code scripting language used by the browser.
The code is as follows |
Copy Code |
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 The check if server is https--detects if it is HTTPS
The code is as follows |
Copy Code |
if ($_server[' HTTPS ']!= "on") { echo "This isn't HTTPS"; }else{ echo "This is HTTPS"; } |
9 Generate csv file from a PHP array--generates. CSV files in a PHP array
The code is as follows |
Copy Code |
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; } |
First, see if the message has been read
When you are sending a message, you may be wondering if the email has been read by the other person. Here's a very interesting piece of code that shows the actual date and time that the other IP address records the read.
The code is as follows |
Copy Code |
?
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);
?> |
Second, extract keywords from the Web page
A great piece of code can easily extract keywords from a Web page.
The code is as follows |
Copy Code |
$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); |
Find all the links on the page
Using the DOM, you can easily crawl links from any page, as shown in the code example:
The code is as follows |
Copy Code |
$html = file_get_contents (' http://www.php100.com ');
$dom = new DOMDocument (); @ $dom->loadhtml ($html);
Grab the on 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/> '; } |
Four, the automatic conversion URL, jump to the hyperlink
In WordPress, if you want to automatically convert the URL, jump to the hyperlink page, you can use the built-in function make_clickable () to perform this operation. If you want to operate the program based on WordPress, then you can refer to the wp-includes/formatting.php source code.
The code is as follows |
Copy Code |
function _MAKE_URL_CLICKABLE_CB ($matches) {
$ret = ';
$url = $matches [2];
if (empty ($url))
return $matches [0];
Removed trailing [.,;:] from URL
if (In_array ($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 ($dest))
return $matches [0];
removed trailing [,;:] from URL
if (In_array ($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;
}
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, using arrays This 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 isn't in a array because we need it to run last, for cleanup of accidental links within links
$ret = Preg_replace (<a ([^>]+?>|>)) <a [^>]+?> ([^>]+?) </a></a> #i "," $1$3</a> ", $ret);
$ret = Trim ($ret);
return $ret;
} |
V. Create a data URL
Data URLs can be embedded directly into the HTML/CSS/JS to save a lot of HTTP requests. The following code makes it easy to create a data URL using $file.
The code is as follows |
Copy Code |
function Data_uri ($file, $mime) { $contents =file_get_contents ($file); $base 64=base64_encode ($contents); echo "Data: $mime; base64, $base 64"; } |
Download & Save a remote picture from the server
When you build a website, download a picture from a remote server and save it on your own server, which is often used. The code is as follows:
The code is as follows |
Copy Code |
$image = file_get_contents (' yun_qi_img/image.jpg '); File_put_contents ('/images/image.jpg ', $image);//where to save the image |
Vii. removing remove Microsoft Word HTML Tag
When you use Microsoft Word, you will create many tags, such as font,span,style,class. These tags are very useful for word itself, but when you paste it into a Web page from Word, you'll find a lot of unwanted tag. So the following code can help you delete all useless word HTML tags.
The code is as follows |
Copy Code |
function cleanhtml ($html) { <summary> Removes all FONT and SPAN tags, and all Class and Style attributes. Designed to get rid of non-standard Microsoft Word HTML tags. </summary> 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 } |
Eight, the detection browser language
If you have multiple languages on your site, you can use this code as the default language to detect the browser language. This code will return to the initial language used by the browser client.
The code is as follows |
Copy Code |
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; } |
Show the number of Facebook fans
If your site or blog has an inline Facebook page, you might want to know how many fans you have. This code will help you check the number of Facebook fans, remember, and don't forget to add the code to the second line of your page ID.
The code is as follows |
Copy Code |
<?php $page _id = "YOUR Page-id"; $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; ?> |