1. 郵箱或者ip地址的驗證 是對 <i>filter_var</i> 的運用
filter_var() 函數通過指定的過濾器過濾變量。
如果成功,則返回已過濾的數據,如果失敗,則返回 false。
語法
filter_var(variable, filter, options)variable:必需。規定要過濾的變量。
filter:可選。規定要使用的過濾器的 ID。 (參見下面的FiltersID列表)
options:規定包含標志/選項的數組。檢查每個過濾器可能的標志和選項。
示例代碼:
function is_validemail($email) { $check = 0; if(filter_var($email,FILTER_VALIDATE_EMAIL)) { $check = 1; } return $check; }
FiltersID名稱:描述
FILTER_CALLBACK:調用用戶自定義函數來過濾數據。
FILTER_SANITIZE_STRING:去除標簽,去除或編碼特殊字符。
FILTER_SANITIZE_STRIPPED:"string" 過濾器的別名。
FILTER_SANITIZE_ENCODED:URL-encode 字符串,去除或編碼特殊字符。
FILTER_SANITIZE_SPECIAL_CHARS:HTML 轉義字符 '"<>& 以及 ASCII 值小于 32 的字符。
FILTER_SANITIZE_EMAIL:刪除所有字符,除了字母、數字以及 !#$%&'*+-/=?^_{|}~@.[] FILTER_SANITIZE_URL:刪除所有字符,除了字母、數字以及 $-_.+!*'(),{}|\\^~[]
<>#%";/?:@&=
FILTER_SANITIZE_NUMBER_INT:刪除所有字符,除了數字和 +-
FILTER_SANITIZE_NUMBER_FLOAT:刪除所有字符,除了數字、+- 以及 .,eE。
FILTER_SANITIZE_MAGIC_QUOTES:應用 addslashes()。
FILTER_UNSAFE_RAW:不進行任何過濾,去除或編碼特殊字符。
FILTER_VALIDATE_INT:在指定的范圍以整數驗證值。
FILTER_VALIDATE_BOOLEAN:如果是 "1", "true", "on" 以及 "yes",則返回 true,如果是 "0", "false", "off", "no" 以及 "",則返回 false。否則返回 NULL。
FILTER_VALIDATE_FLOAT:以浮點數驗證值。
FILTER_VALIDATE_REGEXP:根據 regexp,兼容 Perl 的正則表達式來驗證值。
FILTER_VALIDATE_URL:把值作為 URL 來驗證。
FILTER_VALIDATE_EMAIL:把值作為 e-mail 來驗證。
FILTER_VALIDATE_IP:把值作為 IP 地址來驗證。
2.對獲取用戶的真實 IP 對$_SERVER[]的運用
實例代碼:
function getRealIpAddr() { if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; }
我們進一步開發,來阻止多個 IP 訪問你的網站
if ( !file_exists('blocked_ips.txt') ) {
$deny_ips = array(
'127.0.0.1',
'192.168.1.1',
'83.76.27.9',
'192.168.1.163'
);
} else {
$deny_ips = file('blocked_ips.txt');
}
// read user ip adress:
$ip = isset($_SERVER['REMOTE_ADDR']) ? trim($_SERVER['REMOTE_ADDR']) : '';
// search current IP in $deny_ips array
if ( (array_search($ip, $deny_ips))!== FALSE ) {
// address is blocked:
echo 'Your IP adress ('.$ip.') was blocked!';
exit;
}
3.壓縮成 zip 文件
實例代碼:
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
語法:
<?php $files=array('file1.jpg', 'file2.jpg', 'file3.gif'); create_zip($files, 'myzipfile.zip', true); ?>
4.縮放圖片
function resize_image($filename, $tmpname, $xmax, $ymax)
{
$ext = explode(".", $filename);
$ext = $ext[count($ext)-1];
if($ext == "jpg" || $ext == "jpeg")
$im = imagecreatefromjpeg($tmpname);
elseif($ext == "png")
$im = imagecreatefrompng($tmpname);
elseif($ext == "gif")
$im = imagecreatefromgif($tmpname);
$x = imagesx($im);
$y = imagesy($im);
if($x <= $xmax && $y <= $ymax)
return $im;
if($x >= $y) {
$newx = $xmax;
$newy = $newx * $y / $x;
}
else {
$newy = $ymax;
$newx = $x / $y * $newy;
}
$im2 = imagecreatetruecolor($newx, $newy);
imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
return $im2;
}
5.把秒轉換成天數或小時數
function secsToStr($secs) {
if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}
if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}
if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}
$r.=$secs.' second';if($secs<>1){$r.='s';}
return $r;
}
6.根據url下載圖片
function imagefromURL($image,$rename)
{
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec ($ch);
curl_close ($ch);
$fp = fopen("$rename",'w');
fwrite($fp, $rawdata);
fclose($fp);
}
語法:
<?php $url = "http://koonk.com/images/logo.png"; $rename = "koonk.png"; imagefromURL($url,$rename); ?>
7.生成二維碼
function qr_code($data, $type = "TXT", $size ='150', $ec='L', $margin='0')
{
$types = array("URL" =--> "http://", "TEL" => "TEL:", "TXT"=>"", "EMAIL" => "MAILTO:");
if(!in_array($type,array("URL", "TEL", "TXT", "EMAIL")))
{
$type = "TXT";
}
if (!preg_match('/^'.$types[$type].'/', $data))
{
$data = str_replace("\\", "", $types[$type]).$data;
}
$ch = curl_init();
$data = urlencode($data);
curl_setopt($ch, CURLOPT_URL, 'http://chart.apis.google.com/chart');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'chs='.$size.'x'.$size.'&cht=qr&chld='.$ec.'|'.$margin.'&chl='.$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
語法:
<?php header("Content-type: image/png"); echo qr_code("http://koonk.com", "URL"); ?>
8.計算兩個地圖坐標之間的距離
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');
}
語法:
<?php $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 />'; } ?>
9.限制文件下載的速度
<?php
// local file that should be send to the client
$local_file = 'test-file.zip';
// filename that the user gets as default
$download_file = 'your-download-name.zip';
// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file)) {
// send headers
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);
// flush content
flush();
// open file stream
$file = fopen($local_file, "r");
while(!feof($file)) {
// send the current file part to the browser
print fread($file, round($download_rate * 1024));
// flush the content to the browser
flush();
// sleep one second
sleep(1);
}
// close file stream
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}
?>