几个有用的PHP代码片段和功能
下面收集的几个PHP代码片段和功能非常有趣和有用,供开发者参考参考。1、.PDF文件转换为.JPG文件
一个非常简单的格式转换代码,可以把.PDF文件转换为.JPG文件,代码要起作用,服务器必须要安装Image Magick 扩展。
$pdf_file = './pdf/demo.pdf';
$save_to = './jpg/demo.jpg'; //make sure that apache has permissions to write in this folder! (common problem)
//execute ImageMagick command 'convert' and convert PDF to JPG with applied settings
exec('convert "'.$pdf_file.'" -colorspace RGB -resize 800 "'.$save_to.'"', $output, $return_var);
if($return_var == 0) { //if exec successfuly converted pdf to jpg
print "Conversion OK";
}
else print "Conversion failed.".$output;
2、清除数据库恶意输入
数据库被输入恶意代码,为了保证你的数据库的安全,你必须得小心去清理。有了下面一个超级方便的功能,即可快速清除数据库恶意代码。
function cleanInput($input) {
$search = array(
'@]*?>.*?@si', // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
'@
]*?>.*?
@siU', // Strip style tags properly
'@@' // Strip multi-line comments
);
$output = preg_replace($search, '', $input);
return $output;
}
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;
}
// Usage:
$bad_string = "Hi!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);
3、创建URL图像数组
为了防止暴露图像目录路径,一般不用传统的图像地址,而下面的方法是采用base64-encoded进行加密隐藏。
// A few settings
$image = 'cricci.jpg';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));
// Format the image SRC:data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
// Echo out a sample image
echo '';
4、解压缩文件
function unzip_file($file, $destination){
// create object
$zip = new ZipArchive() ;
// open archive
if ($zip->open($file) !== TRUE) {
die ('Could not open archive');
}
// extract contents to destination directory
$zip->extractTo($destination);
// close archive
$zip->close();
echo 'Archive extracted to directory';
}
5、IP位置检测
一个非常不错,用PHP实现的IP检测代码,明确IP地址则取得位置,发现IP地址地点未知,则返回。
function detect_city($ip) {
$default = 'UNKNOWN';
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,
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('{
City : ([^<]*)
}i', $content, $regs) ){
$city = $regs;
}
if ( preg_match('{
State/Province : ([^<]*)
}i', $content, $regs) ){
$state = $regs;
}
if( $city!='' && $state!='' ){
$location = $city . ', ' . $state;
return $location;
}else{
return $default;
}
}
6、电子邮件通知网站错误记录
错误日志是非常有用的,可以去查询一个问题的发生和原因,但是你很少去留意。以下PHP代码是用邮件的形式提醒你网站运行情况。
function nettuts_error_handler($number, $message, $file, $line, $vars){
$email = "
An error ($number) occurred on line
$line and in the file: $file.
$message
";
$email .= "
" . print_r($vars, 1) . "
";
$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;
7、删除微软HTML标签
返回输入整洁干净的HTML代码,可以使你的网站更加安全。
function cleanHTML($html) {
$html = ereg_replace("<(/)?(font|span|del|ins)[^>]*>","",$html);
$html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);
$html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);
return $html
}
8、图片添加水印
如果你不想你的图片在网络上无名的满天飞,那么给它添加水印是必须的,下面是用PHP实现的给图片添加水印功能。
function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$font = 'arial.ttf';
$font_size = 10;
imagettftext($image_p, $font_size, 0, 10, 20, $black, $font, $WaterMarkText);
if ($DestinationFile<>'') {
imagejpeg ($image_p, $DestinationFile, 100);
} else {
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);
}
imagedestroy($image);
imagedestroy($image_p);
}
/******** usage **********/
$SourceFile = '/home/user/www/images/image.jpg';
$DestinationFile = '/home/user/www/images/image-watermark.jpg';
$WaterMarkText = 'Copyright crazyfrom.com';
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);
好代码支持下 需要放到哪里呢?
页:
[1]