首页 后端开发 php教程 直接拿来用 10个PHP代码片段_PHP

直接拿来用 10个PHP代码片段_PHP

Jun 01, 2016 pm 12:04 PM
php 代码片段

  PHP是一种HTML内嵌式的语言,是一种在服务器端执行的嵌入HTML文档的脚本语言。PHP拥有数以百计的基本功能,支持上千种扩展。这些功能都被很好的加载在PHP站点上,但内置的库有各种各样的命名。在PHP代码库中包含了无数个有用的PHP代码片段,每位开发者都需要不断完善自己的“工具箱”。有了这些代码片段可以为你节省大量的时间,一起来看下。

直接拿来用 10个PHP代码片段_PHP

  1.查找Longitudes与Latitudes之间的距离

function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
    $theta = $longitude1 - $longitude2;
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * 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'); 
}

$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:

miles: 2.6025
feet: 13,741.4350
yards: 4,580.4783
kilometers: 4.1884
meters: 4,188.3894
登录后复制

  源码

  2.完善cURL功能

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;
	}
}
登录后复制

  源码

  3.清理用户输入

]*?>.*?@si',   // Strip out javascript
    &#39;@<[\/\!]*?[^<>]*?>@si&#39;,            // Strip out HTML tags
    &#39;@]*?>.*?@siU&#39;,    // Strip style tags properly
    &#39;@@&#39;         // Strip multi-line comments
  );

    $output = preg_replace($search, &#39;&#39;, $input);
    return $output;
  }
?>
$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;
}
?>
登录后复制

  源码

  4.通过IP(城市、国家)检测地理位置

function detect_city($ip) {

        $default = &#39;Hollywood, CA&#39;;

        if (!is_string($ip) || strlen($ip) < 1 || $ip == &#39;127.0.0.1&#39; || $ip == &#39;localhost&#39;)             $ip = &#39;8.8.8.8&#39;;           $curlopt_useragent = &#39;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)&#39;;           $url = &#39;http://ipinfodb.com/ip_locator.php?ip=&#39; . 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         => &#39;http://&#39; . $_SERVER[&#39;HTTP_HOST&#39;],
        );

        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(&#39;{

	
City : ([^<]*)
}i&#39;, $content, $regs) ) { $city = $regs[1]; } if ( preg_match(&#39;{
	
State/Province : ([^<]*)

}i&#39;, $content, $regs) ) { $state = $regs[1]; } if( $city!=&#39;&#39; && $state!=&#39;&#39; ){ $location = $city . &#39;, &#39; . $state; return $location; }else{ return $default; } }
登录后复制

  源码

  5.设置密码强度

 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"));
登录后复制

  源码

  6.检测浏览器语言,只提供可用的$availableLanguages作为数组(‘en’, ‘de’, ‘es’)

function get_client_language($availableLanguages, $default=&#39;en&#39;){
	
	if (isset($_SERVER[&#39;HTTP_ACCEPT_LANGUAGE&#39;])) {
			
		$langs=explode(&#39;,&#39;,$_SERVER[&#39;HTTP_ACCEPT_LANGUAGE&#39;]);

		//start going through each one
		foreach ($langs as $value){
	
			$choice=substr($value,0,2);
			if(in_array($choice, $availableLanguages)){
				return $choice;
				
			}
			
		}
	} 
	return $default;
}
登录后复制

  源码

  7.创建数据URL

function data_uri($file, $mime) {
  $contents=file_get_contents($file);
  $base64=base64_encode($contents);
  echo "data:$mime;base64,$base64";
}
登录后复制

  源码

  8.创建更加友好的页面标题SEO URL

输入示例:$title = “This foo’s bar is rockin’ cool!”; echo makeseoname($title); //RETURNS: //this-foos-bar-is-rockin-cool

function make_seo_name($title) {
	return preg_replace(&#39;/[^a-z0-9_-]/i&#39;, &#39;&#39;, strtolower(str_replace(&#39; &#39;, &#39;-&#39;, trim($title))));
}
登录后复制

  源码

  9.终极加密功能

// 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;
}
登录后复制

  源码

  10a.Tweeter Feed Runner——使用任意twitter名,可在任意页面上加载用户资源。

pversion; 
    } 
    public function loadTimeline($user, $max = 20){ 
        $this->twitURL .= &#39;statuses/user_timeline.xml?screen_name=&#39;.$user.&#39;&count=&#39;.$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; 
    } 
}
登录后复制

  10b. Tweeter Feed Runner——用于在主题中创建文件,比如:example.php

loadTimeline("phpsnips")->getTweets(); 
foreach($feed as $time => $message){ 
    echo "<div class=&#39;tweet&#39;>".$twitter->formatTweet($message)."<br />At: ".$time."</div>"; 
}
登录后复制

  源码

  英文出自:Codegeekz

  

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1665
14
CakePHP 教程
1423
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
PHP和Python:比较两种流行的编程语言 PHP和Python:比较两种流行的编程语言 Apr 14, 2025 am 12:13 AM

PHP和Python各有优势,选择依据项目需求。1.PHP适合web开发,尤其快速开发和维护网站。2.Python适用于数据科学、机器学习和人工智能,语法简洁,适合初学者。

PHP行动:现实世界中的示例和应用程序 PHP行动:现实世界中的示例和应用程序 Apr 14, 2025 am 12:19 AM

PHP在电子商务、内容管理系统和API开发中广泛应用。1)电子商务:用于购物车功能和支付处理。2)内容管理系统:用于动态内容生成和用户管理。3)API开发:用于RESTfulAPI开发和API安全性。通过性能优化和最佳实践,PHP应用的效率和可维护性得以提升。

PHP:网络开发的关键语言 PHP:网络开发的关键语言 Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP的持久相关性:它还活着吗? PHP的持久相关性:它还活着吗? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在现代编程领域中依然占据重要地位。1)PHP的简单易学和强大社区支持使其在Web开发中广泛应用;2)其灵活性和稳定性使其在处理Web表单、数据库操作和文件处理等方面表现出色;3)PHP不断进化和优化,适用于初学者和经验丰富的开发者。

PHP与Python:了解差异 PHP与Python:了解差异 Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

PHP和Python:代码示例和比较 PHP和Python:代码示例和比较 Apr 15, 2025 am 12:07 AM

PHP和Python各有优劣,选择取决于项目需求和个人偏好。1.PHP适合快速开发和维护大型Web应用。2.Python在数据科学和机器学习领域占据主导地位。

PHP与其他语言:比较 PHP与其他语言:比较 Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP和Python:解释了不同的范例 PHP和Python:解释了不同的范例 Apr 18, 2025 am 12:26 AM

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

See all articles