1、检测用户位置
使用下面的函数,可以检测用户是在哪个城市访问你的网站
function detect_city($ip) {
$default = 'UNKNOWN';
$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('{<li>City : ([^<]*)</li>}i', $content, $regs) ) {
$city = $regs[1];
}
if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) ) {
$state = $regs[1];
}
if( $city!='' && $state!='' ){
$location = $city . ', ' . $state;
return $location;
}else{
return $default;
}
}
调用:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$city = detect_city($ip);
echo $city;
?>
2、验证邮箱地址
有时候,当在网站填写表单,用户可能会输入错误的邮箱地址,这个函数可以验证邮箱地址是否有效。
function is_validemail($email)
{
$check = 0;
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
$check = 1;
}
return $check;
}
语法:
<?php
$email = "blog@koonk.com";
$check = is_validemail($email);
echo $check;
// If the output is 1, then email is valid.
?>
3、获取用户的真实 IP
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_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;
}
语法:
<?
php $ip = getRealIpAddr();
echo $ip;
?>
4、阻止多个 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;
}
5、强制性文件下载
如果你需要下载特定的文件而不用另开新窗口,下面的代码片段可以帮助你。
function force_download($file)
{
$dir = "../log/exports/";
if ((isset($file))&&(file_exists($dir.$file))) {
header("Content-type: application/force-download");
header('Content-Disposition: inline; filename="' . $dir.$file . '"');
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($dir.$file));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
readfile("$dir$file");
} else {
echo "No file selected";
}
}
语法:
<php
force_download("image.jpg");
?>
6、压缩 zip 文件
使用下面的 PHP 片段可以即时压缩 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);
?>
7、 解压文件
function unzip($location,$newLocation)
{
if(exec("unzip $location",$arr)){
mkdir($newLocation);
for($i = 1;$i< count($arr);$i++){
$file = trim(preg_replace("~inflating: ~","",$arr[$i]));
copy($location.'/'.$file,$newLocation.'/'.$file);
unlink($location.'/'.$file);
}
return TRUE;
}else{
return FALSE;
}
}
语法:
<?php
unzip('test.zip','unziped/test'); //File would be unzipped in unziped/test folder
?>
8、缩放图片
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;
}
9、目录清单
使用下面的 PHP 代码片段可以在一个目录中列出所有文件和文件夹
function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
{
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a>'."\n";
}
}
closedir($handle);
}
}
}
语法:
<?php
list_files("images/"); //This will list all files of images folder
?>
10、 获取当前页面 URL
这个 PHP 片段可以帮助你让用户登录后直接跳转到之前浏览的页面
function current_url()
{
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$validURL = str_replace("&", "&", $url);
return validURL;
}
语法:
<?php
echo "Currently you are on: ".current_url();
?>
11、检测 URL 是否有效
function isvalidURL($url)
{
$check = 0;
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
$check = 1;
}
return $check;
}
语法:
<?php
$url = "http://koonk.com";
$check = checkvalidURL($url);
echo $check; //if returns 1 then URL is valid.
?>
12、生成二维码
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");
?>
13、计算两个地图坐标之间的距离
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).'';
}
?>
14、限制文件下载的速度
<?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!');
}
?>
16、检查网站是否宕机
function Visit($url){
$agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";$ch=curl_init();
curl_setopt ($ch, CURLOPT_URL,$url );
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch,CURLOPT_VERBOSE,false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_SSLVERSION,3);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
$page=curl_exec($ch);
//echo curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300) return="" true;="" else="" false;="" }="" if="" (visit("http:="" www.google.com"))="" echo="" "website="" ok"."n";="" down";<="" pre="">
15、裁剪图片
$filename= "test.jpg";
list($w, $h, $type, $attr) = getimagesize($filename);
$src_im = imagecreatefromjpeg($filename);
$src_x = '0'; // begin x
$src_y = '0'; // begin y
$src_w = '100'; // width
$src_h = '100'; // height
$dst_x = '0'; // destination x
$dst_y = '0'; // destination y
$dst_im = imagecreatetruecolor($src_w, $src_h);
$white = imagecolorallocate($dst_im, 255, 255, 255);
imagefill($dst_im, 0, 0, $white);
imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
header("Content-type: image/png");
imagepng($dst_im);
imagedestroy($dst_im);