1. 过滤数据库输入
当执行数据库更新操作时,你必须非常小心,以防范 SQL 注入和其他试图插入恶意数据的行为。下面的函数可能是最完整和有效的方法,在执行数据库更新操作前过滤字符串。
function cleanInput($input) { $search = array( '@<script[^>]*?>.*?</script>@si', // Strip out javascript '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly '@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments ); $output = preg_replace($search, '', $input); return $output; } ?> <?php 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; }
使用案例:
<?php $bad_string = "Hi! <script src='http://mangguo.org/bad_script.js'></script> It's a good day!"; $good_string = sanitize($bad_string); // $good_string returns "Hi! It\'s a good day!" // Also use for getting POST/GET variables $_POST = sanitize($_POST); $_GET = sanitize($_GET); ?>
来自:http://css-tricks.com/snippets/php/sanitize-database-inputs/
2. 计算两个坐标点之间的距离
希望能够计算两个坐标点之间的距离?下面的函数使用了两个地点的经度和纬度,并计算它们之间的距离,使用英里或米为单位。
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).'<br />'; }
来自:http://www.inkplant.com/code/calculate-the-distance-between-two-points.php
3. 根据指定标签获取 twitter 数据
这是一个快速又简单的方法,使用 cURL 库根据指定标签获取 twitter 数据。下面的例子将检索所有 tweets 的 #cats
标签。
function getTweets($hash_tag) { $url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ; echo "<p>Connecting to <strong>$url</strong> ...</p>"; $ch = curl_init($url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE); $xml = curl_exec ($ch); curl_close ($ch); //If you want to see the response from Twitter, uncomment this next part out: //echo "<p>Response:</p>"; //echo "<pre>".htmlspecialchars($xml)."</pre>"; $affected = 0; $twelement = new SimpleXMLElement($xml); foreach ($twelement->entry as $entry) { $text = trim($entry->title); $author = trim($entry->author->name); $time = strtotime($entry->published); $id = $entry->id; echo "<p>Tweet from ".$author.": <strong>".$text."</strong> <em>Posted ".date('n/j/y g:i a',$time)."</em></p>"; } return true ; } getTweets('#cats');
来自:http://www.inkplant.com/code/get-twitter-posts-by-hashtag.php
4. 添加 CSS 奇偶类
当使用 PHP 生成列表或表格,为每一数据行添加奇偶类将大大简化 CSS 代码的书写。
在一个循环体中,CSS 类名将会被命名为 .example-class0
和 .example-class1
两种。
来自:http://css-tricks.com/snippets/php/applying-evenodd-classes/
5. 给自己发送错误报告邮件
为了跟踪某些网站的异常状况,使用电子邮件记录错误日志,往往比直接在页面中抛错更为合适。这里是实现邮件报告的代码片段。
<?php // Our custom error handler function nettuts_error_handler($number, $message, $file, $line, $vars){ $email = " <p>An error ($number) occurred on line <strong>$line</strong> and in the <strong>file: $file.</strong> <p> $message </p>"; $email .= "<pre>" . print_r($vars, 1) . "</pre>"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Email the error to someone... error_log($email, 1, 'you@youremail.com', $headers); // Make sure that you decide how to respond to errors (on the user's side) // Either echo an error message, or kill the entire project. Up to you... // The code below ensures that we only "die" if the error was more than // just a NOTICE. if ( ($number !== E_NOTICE) && ($number < 2048) ) { die("There was an error. Please try again later."); } } // We should use our custom function to handle errors. set_error_handler('nettuts_error_handler'); // Trigger an error... (var doesn't exist) echo $somevarthatdoesnotexist;
来自:http://net.tutsplus.com/tutorials/php/quick-tip-email-error-logs-to-yourself-with-php/
6. 自动创建和合并 POST 数组键名
这个片段对于 POST 提交的处理非常有用。你需要准备一个和预期的 POST 数组键名一致的清单数组,这段代码会自动创建和合并 POST 数组的键名。如果没有找到相应键名,则在 POST 数组中将其置为 NULL。基本上你不需要再像下面这样编写代码了:
$username=$_POST["username"]; $age=$_POST["age"];
这段代码对于 $_POST 数组的处理显得不够灵活,而你更关注于数据校验,而不是反复地在判断 $_POST 键值,存取数据,因为那是更重要的。
<?php $expected=array('username','age','city','street'); foreach($expected as $key){ if(!empty($_POST[$key])){ ${key}=$_POST[$key]; } else{ ${key}=NULL; } } ?>
来自:http://www.catswhocode.com/blog/snippets/automatically-creates-variables…
7. 使用 PHP 下载并存储远程图片
下面是一个超级简单而又奏效的方式,用来在服务器端下载并存储远程图片:
$image = file_get_contents('http://www.url.com/image.jpg'); file_put_contents('/images/image.jpg', $image); //save the image on your server
来自:http://www.catswhocode.com/blog/snippets/download-save-a-remote-image…
8. 创建 dataURI 式的图片数据
在 HTML/CSS/JS 中嵌入使用 dataURI 格式的图片,以牺牲可维护性,达到大大减少 HTTP 请求数量的目的。你可以选择使用在线的转换工具,也可以使用以下 PHP 代码:
function data_uri($file, $mime) { $contents=file_get_contents($file); $base64=base64_encode($contents); echo "data:$mime;base64,$base64"; }
来自:http://css-tricks.com/snippets/php/create-data-uris/
9. 检测浏览器语言
在开发一个多语言网站的时候,需要探测浏览器语言以决定使用该语言作为网站的默认语言。下面介绍如何使用 PHP 探测用户的浏览器类型:
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; }
来自:http://snipplr.com/view/12631/detect-browser-language/php-detect-browser-language
10. 添加英文数字顺序后缀(th、st、nd、rd、th)
下面的代码用来给数字加上英文顺序后缀,中文一般用不到:
function ordinal($cdnl){ $test_c = abs($cdnl) % 10; $ext = ((abs($cdnl) %100 < 21 && abs($cdnl) %100 > 4) ? 'th' : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th')); return $cdnl.$ext; } for($i=1;$i<100;$i++){ echo ordinal($i).'<br>'; }
来自:http://phpsnips.com/snip-37
英文原稿:10 awesome PHP functions and snippets | CatsWhoCode
翻译整理:10+ 超牛的 PHP 函数和代码片段 | 芒果小站
转载自 <a href="https://mangguo.org/10-awesome-php-functions-and-snippets/" title="10+ 超牛的 PHP 函数和代码片段" rel="bookmark">10+ 超牛的 PHP 函数和代码片段 | 芒果小站</a>
/2013-05-30 13:58只能在这帮顶了,有用到时再来找。
/2013-05-31 14:37[…] 10+ 超牛的 PHP 函数和代码片段 […]
/2013-06-03 09:24收藏
/2013-06-04 23:03特别第一个。很多人忽略sql注入;
/2013-06-15 10:51是的,这个很重要。
/2013-06-16 10:43对PHP不懂,模板神马的直接拿来用、
/2013-06-16 10:58写的不错,来支持下,用的你的模版,感觉很好
/2013-06-16 11:16技术性比较强~~ 好多都看不懂呢
/2013-06-18 15:11看来这些代码好像都很有用。值得收藏一下。以后估计有机会能用到。
/2013-07-10 16:55收藏下
/2013-07-28 18:09第一个好像实用性不高。。
想要过滤style标签
要是有人用
<sty<style>…</style>le>
这样过滤后正好有一个<style>
/2015-03-04 15:19很不错收藏一下