19 Ultra-Practical PHP code Snippets _php Instances

Source: Internet
Author: User
1) Whois query using php--using PHP for WHOIS requests

With this code, WHOIS information is available in a specific domain name. Takes the domain name as a parameter and displays information about all domain names.
Copy CodeThe 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
//
$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. " \ r \ n ");
while (!feof ($conn)) {
$output. = Fgets ($conn, 128);
}
Fclose ($conn);
}
else {die (' error:could does connect to '. $nic _server. '!'); }

return $output;
}
2) Text Messaging with PHP using the textmagic api--use the textmagic API to get PHP test information

The

Textmagic introduces a powerful core API that makes it easy to send SMS to your phone. The API is required for a fee. The
copy Code 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,
' Passwo Rd ' = $password
));

//Send a text message to ' 999-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 RAM usage

This code helps you get memory utilization. The
copy Code code is as follows:
echo "Initial:". Memory_get_usage (). "Bytes \ n";
/* Prints
initial:361400 bytes
* *

//Let's use up some memory
for ($i = 0; $i < 100000; $i + +) {
$array []= MD5 ($i);
}

//Let's remove half of the array
for ($i = 0; $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 any page source codes

If you want to view the source code of the Web page, just change the URL of the second line, and the source code will be displayed on the page.
Copy the Code code as follows: $line) {
Loop thru prepend Line numbers
echo "line #{$line _num}:". Htmlspecialchars ($line). "
\ n ";
}
5) Create data URI ' s--.

By using this code, you can create data URIs, which are useful for embedding images in Html/css, and can help save HTTP requests.
Copy the Code code as follows:
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--to retrieve geolocation via IP

This code helps you to find a specific IP, just enter the IP on the function parameters, you can detect the location.
Copy CodeThe code is as follows:
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

The

detects the code scripting language used by the browser. The
copy Code 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--to detect if the servers are HTTPS

Copy the code as follows: if ($_server[' HTTPS ']! = "on") {
echo "This was not HTTPS";
}else{
echo "This is HTTPS";
}
9) Generate csv file from a php array--generate. CSV Files in PHP array
Copy the Code code 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

Copy CodeThe code is as follows: function getdistancebetweenpointsnew ($latitude 1, $longitude 1, $latitude 2, $longitude 2) {
$theta = $longitude 1-$longitude 2;
$miles = (sin (Deg2rad ($latitude 1)) * Sin (Deg2rad ($latitude 2)) + (cos (Deg2rad ($latitude 1)) * cos (Deg2rad ($latitude 2)) * Cos (Deg2rad ($theta)));
$miles = ACOs ($miles);
$miles = Rad2deg ($miles);
$miles = $miles * 60 * 1.1515;
$feet = $miles * 5280;
$yards = $feet/3;
$kilometers = $miles * 1.609344;
$meters = $kilometers * 1000;
Return compact (' Miles ', ' feet ', ' yards ', ' kilometers ', ' meters ');
}

$point 1 = Array (' lat ' = = 40.770623, ' long ' =-73.964367);
$point 2 = Array (' lat ' = = 40.758224, ' long ' =-73.917404);
$distance = getdistancebetweenpointsnew ($point 1[' lat '), $point 1[' long '], $point 2[' lat '), $point 2[' long ']);
foreach ($distance as $unit = = $value) {
echo $unit. ': '. Number_format ($value, 4). '
';
}

The example returns the following:
Copy CodeThe code is as follows: miles:2.6025
feet:13,741.4350
yards:4,580.4783
kilometers:4.1884
meters:4,188.3894

11. Perfect Curl function
Copy CodeThe 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. Clean up user input
Copy CodeThe code is as follows: function CleanInput ($input) {

$search = Array (
' @ @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. Location detection via IP (city, country)
Copy CodeThe code is as follows: function detect_city ($IP) {

$default = ' Hollywood, CA ';

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;}}
14. Set Password strength
Copy CodeThe 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. Detect the browser language, only provide the available $availablelanguages as an array (' en ', ' de ', ' es ')
Copy the code code 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
Copy the Code code as follows: function Data_uri ($file, $mime) {
$contents =file_get_contents ($file);
$base 64=base64_encode ($contents);
echo "Data: $mime; base64, $base 64";
}
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
Copy CodeThe code is as follows: function Make_seo_name ($title) {
Return preg_replace ('/[^a-z0-9_-]/i ', ' ', Strtolower (Str_replace (', '-', trim ($title)));
}
18. Ultimate Encryption function
Copy CodeThe 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 many 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.
Copy CodeThe 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--is used to create files in the theme, such as: example.php
Copy CodeThe code is as follows:
Loadtimeline ("Phpsnips")->gettweets ();
foreach ($feed as $time = = $message) {
echo "". $twitter->formattweet ($message). "
At: ". $time.";
}

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