10 个实用的PHP代码片段

1. Perfect cURL Function

 
01 <SPAN style="COLOR: #008080">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) {
02     $ch = curl_init();
03     curl_setopt($ch, CURLOPT_AUTOREFERER, true);
04     if(!empty($ref)) {
05         curl_setopt($ch, CURLOPT_REFERER, $ref);
06     }
07     curl_setopt($ch, CURLOPT_URL, $url);
08     curl_setopt($ch, CURLOPT_HEADER, 0);
09     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
10     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
11     if(!empty($ua)) {
12         curl_setopt($ch, CURLOPT_USERAGENT, $ua);
13     }
14     if(count($post) > 0){
15         curl_setopt($ch, CURLOPT_POST, 1);
16         curl_setopt($ch, CURLOPT_POSTFIELDS, $post);    
17     }
18     $output = curl_exec($ch);
19     curl_close($ch);
20     if($print) {
21         print($output);
22     } else {
23         return $output;
24     }
25 }</SPAN>

2. Find Distance Between Two Longitudes, Latitudes

 
01 <SPAN style="COLOR: #008080">function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
02     $theta = $longitude1 - $longitude2;
03     $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
04     $miles = acos($miles);
05     $miles = rad2deg($miles);
06     $miles = $miles * 60 * 1.1515;
07     $feet = $miles * 5280;
08     $yards = $feet / 3;
09     $kilometers = $miles * 1.609344;
10     $meters = $kilometers * 1000;
11     return compact('miles','feet','yards','kilometers','meters'); 
12 }
13   
14 $point1 = array('lat' => 40.770623, 'long' => -73.964367);
15 $point2 = array('lat' => 40.758224, 'long' => -73.917404);
16 $distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
17 foreach ($distance as $unit => $value) {
18     echo $unit.': '.number_format($value,4).'
19 ';
20 }
21   
22 The example returns the following:
23   
24 miles: 2.6025
25 feet: 13,741.4350
26 yards: 4,580.4783
27 kilometers: 4.1884
28 meters: 4,188.3894</SPAN>

  3. Detect Location by IP (City, State)

 
01 <SPAN style="COLOR: #008080">function detect_city($ip) {
02   
03         $default = 'Hollywood, CA';
04   
05         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,
06             CURLOPT_HEADER      => 0,
07             CURLOPT_RETURNTRANSFER  => 1,
08             CURLOPT_USERAGENT   => $curlopt_useragent,
09             CURLOPT_URL       => $url,
10             CURLOPT_TIMEOUT         => 1,
11             CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
12         );
13   
14         curl_setopt_array($ch, $curl_opt);
15   
16         $content = curl_exec($ch);
17   
18         if (!is_null($curl_info)) {
19             $curl_info = curl_getinfo($ch);
20         }
21   
22         curl_close($ch);
23   
24         if ( preg_match('{</SPAN>
  • City : ([^<]*)
 
1 <SPAN style="COLOR: #008080">}i', $content, $regs) ) { $city = $regs[1]; } if ( preg_match('{</SPAN>
  • State/Province : ([^<]*)
 
1 <SPAN style="COLOR: #008080"
2   
3 }i', $content, $regs) ) { $state = $regs[1]; } if( $city!='' && $state!='' ){ $location = $city . ', ' . $state; return $location; }else{ return $default; } }</SPAN>

  4. PHP Functions to Clean User Input

 
01 <SPAN style="COLOR: #008080">]*?>.*?@si',   // Strip out javascript
02     '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
03     '@<style[^>]*?>.*?@siU',    // Strip style tags properly
04     '@@'         // Strip multi-line comments
05   );
06   
07     $output = preg_replace($search, '', $input);
08     return $output;
09   }
10 ?>
11 $val) {
12             $output[$var] = sanitize($val);
13         }
14     }
15     else {
16         if (get_magic_quotes_gpc()) {
17             $input = stripslashes($input);
18         }
19         $input  = cleanInput($input);
20         $output = mysql_real_escape_string($input);
21     }
22     return $output;
23 }
24 ?></SPAN>

  5. Detect Browser Language

 
01 <SPAN style="COLOR: #008080">function get_client_language($availableLanguages, $default='en'){
02   
03     if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
04   
05         $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
06   
07         //start going through each one
08         foreach ($langs as $value){
09   
10             $choice=substr($value,0,2);
11             if(in_array($choice, $availableLanguages)){
12                 return $choice;
13   
14             }
15   
16         }
17     
18     return $default;
19 }</SPAN>

  6. Password Strength

 100){ 

 
01 <SPAN style="COLOR: #008080">        $strength = 100
02     
03     return $strength; 
04
05   
06 var_dump(password_strength("Correct Horse Battery Staple")); 
07 echo "
08 "; 
09 var_dump(password_strength("Super Monkey Ball")); 
10 echo "
11 "; 
12 var_dump(password_strength("Tr0ub4dor&3")); 
13 echo "
14 "; 
15 var_dump(password_strength("abc123")); 
16 echo "
17 "; 
18 var_dump(password_strength("sweet"));</SPAN>

  7. Make page titles seo-friendly for URL

 
1 <SPAN style="COLOR: #008080">function make_seo_name($title) {
2     return preg_replace('/[^a-z0-9_-]/i', '', strtolower(str_replace(' ', '-', trim($title))));
3 }</SPAN>

8. Create Data URI’S

 
1 <SPAN style="COLOR: #008080">function data_uri($file, $mime) {
2   $contents=file_get_contents($file);
3   $base64=base64_encode($contents);
4   echo "data:$mime;base64,$base64";
5 }</SPAN>

  9. Ultimate Encryption Function

 
01 <SPAN style="COLOR: #008080">// u(ncrackable) e(ncryption) function by BlackHatDBL (www.netforme.net)
02 function fue($hash,$times) {
03     // Execute the encryption(s) as many times as the user wants
04     for($i=$times;$i>0;$i--) {
05         // Encode with base64...
06         $hash=base64_encode($hash);
07         // and md5...
08         $hash=md5($hash);
09         // sha1...
10         $hash=sha1($hash);
11         // sha256... (one more)
12         $hash=hash("sha256", $hash);
13         // sha512
14         $hash=hash("sha512", $hash);
15   
16     }
17     // Finaly, when done, return the value
18     return $hash;
19 }</SPAN>

  10. Tweeter Feed Runner

 
01 <SPAN style="COLOR: #008080">pversion; 
02     
03     public function loadTimeline($user, $max = 20){ 
04         $this->twitURL .= 'statuses/user_timeline.xml?screen_name='.$user.'&count='.$max; 
05         $ch        = curl_init(); 
06         curl_setopt($ch, CURLOPT_URL, $this->twitURL); 
07         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
08         $this->xml = curl_exec($ch); 
09         return $this
10     
11     public function getTweets(){ 
12         $this->twitterArr = $this->getTimelineArray(); 
13         $tweets = array(); 
14         foreach($this->twitterArr->status as $status){ 
15             $tweets[$status->created_at->__toString()] = $status->text->__toString(); 
16         
17         return $tweets; 
18     
19     public function getTimelineArray(){ 
20         return simplexml_load_string($this->xml); 
21     
22     public function formatTweet($tweet){ 
23         $tweet = preg_replace("/(http(.+?))( |$)/","<A href="http://codegeekz.com/%22 href=" %22? %22$0 codegeekz.com http:><SPAN style="COLOR: #008080">$1</SPAN></A>$3", $tweet); 
24         $tweet = preg_replace("/#(.+?)(\h|\W|$)/", "<A href="http://www.open-open.com/lib/admin/edit/&src=hash%5C%22" &src='hash%5C%22"' kesrc='hash%5C%22"'><SPAN style="COLOR: #008080">#$1</SPAN></A>$2", $tweet); 
25         $tweet = preg_replace("/@(.+?)(\h|\W|$)/", "<A href="%5C%22" %5c%22?=""><SPAN style="COLOR: #008080">@$1</SPAN></A>$2", $tweet); 
26         return $tweet; 
27     
28 }</SPAN>

你可能感兴趣的:(10 个实用的PHP代码片段)