找回密码
 注册
[Jglt.net主论坛]
[镜像论坛]--[金光网]--[XLCS]
糖果主机-SugarHosts 提供价格超值的绝佳产品和服务Jtti,新加坡服务器,美国服务器,香港服务器,海外云服务器LightNode - 覆盖超过30个海外节点NVMe VPS主机
查看: 164|回复: 2

几个有用的PHP代码片段和功能

[复制链接]
发表于 2013 年 9 月 20 日 22:49:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?注册

×
下面收集的几个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[1];
        }
        if ( preg_match('{
State/Province : ([^<]*)

}i', $content, $regs) )  {
            $state = $regs[1];
        }

        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);
Jgwy.Com - Free Web Hosting Guide & Directory In China since 2001! Jgwy.Net-Jglt.Net
发表于 2013 年 10 月 11 日 08:51:51 | 显示全部楼层
好代码支持下
Jgwy.Com - Free Web Hosting Guide & Directory In China since 2001! Jgwy.Net-Jglt.Net
回复

使用道具 举报

发表于 2013 年 10 月 12 日 14:08:48 | 显示全部楼层
需要放到哪里呢?
Jgwy.Com - Free Web Hosting Guide & Directory In China since 2001! Jgwy.Net-Jglt.Net
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|金光论坛

GMT+8, 2024 年 6 月 10 日 13:05 , Processed in 0.098396 second(s), 23 queries .

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表