有用的PHP代码片段

使用PHP和Image Magick将.pdf文件转换成图片

下面是一个简单的将.pdf文件转成.jpg图片的实例。如果你要为.pdf文件生成预览图,这将非常地有用。请注意,要使用这段代码你必须在你的服务器端安装 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.<br />".$output;

Credits: http://snipplr.com/view/48513

净化数据库的输入

为使数据库保持安全,我们经常对即将保存的输入慎之又慎。这里是一些超级便利净化输入的函数确保你不会在数据库中插入那些恶毒的代码 。

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;
  }

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! <script src='http://www.evilsite.com/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);

Credits: http://css-tricks.com/snippets/php/sanitize-database-inputs/

用PHP创建图像数据URIs

取代传统的image地址,src属性中的image文件地址基于64位编码生成。IE7下浏览器不兼容。

// 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 '<img src="',$src,'">';

Credits: http://davidwalsh.name/data-uri-php

从PHP数组中生成CSV文件

简短但高效的从PHP数组生成.csv文件的函数。

function generateCsv($data, $delimiter = ',', $enclosure = '"') {
       $handle = fopen('php://temp', 'r+');
       foreach ($data as $line) {
               fputcsv($handle, $line, $delimiter, $enclosure);
       }
       rewind($handle);
       while (!feof($handle)) {
               $contents .= fread($handle, 8192);
       }
       fclose($handle);
       return $contents;
}

Credits: http://snipplr.com/view/66856/generate-csv-file-from-array-using-php/

用PHP解压缩文件

 

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';
}

Credits: http://www.catswhocode.com/blog/snippets/unzip-zip-files

Detect location by IP

Here is an useful code snippet to detect the location of a specific IP. The function below takes one IP as a parameter, and returns the location of the IP. If no location is found, UNKNOWN is returned.

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('{<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;
        }

    }

Credits: http://www.catswhocode.com/blog/snippets/detect-location-by-ip

Email error logs to yourself

Error logs are extremely useful, but you have to read them to know if a problem happened. And let’s be honest: When we think everything is fine, we do not look at logs very often.

This function will email you the log when an error has been raised on your site. Very handy to stay in touch with your website activity.

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;

Credits: http://net.tutsplus.com/tutorials/php/quick-tip-email-error-logs-to-yourself-with-php/

Remove Microsoft Word HTML tags

If you’re working with clients, I guess you already had many problems with people pasting text from Microsoft Word, which results in bad markup and various code problems…

The following function takes some nightmarish Word HTML and return a clean HTML output that you can use safely on the web.

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
}

Credits: http://tim.mackey.ie/CommentView,guid,2ece42de…

Watermark images automatically

If you’re displaying your own images on your websites, chances are that you don’t want to see them everywhere on the web the next day. To prevent image theft and make sure to be credited as the original creator of the image, watermarking them is generally a good idea. The following function allows you to automatically add a watermark on your images.

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/image1.jpg';
$DestinationFile = '/home/user/www/images/image1-watermark.jpg'; 
$WaterMarkText = 'Copyright phpJabbers.com';
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);

Credits: http://www.phpjabbers.com/put-watermark-on-images-using-php…

Automatic mailto links

The following snippet looks for an email address in a string, and replace it by a mailto link. Pretty useful on private applications, but for obvious spamming reason I do not recommend using this on a website, blog or forum.

$stringa = "This should format my email address example@domain.com";

$pattern = "/([a-z0-9][_a-z0-9.-]+@([0-9a-z][_0-9a-z-]+\.)+[a-z]{2,6})/i";
$replace = "\\1";
$text = preg_replace($pattern, $replace, $stringa);
echo htmlspecialchars($text);

Credits: http://css-tricks.com/snippets/php/automatic-mailto-links/

posted @ 2012-10-29 18:02  Partoo  阅读(585)  评论(0编辑  收藏  举报