Php tips [recommended] and php tips

Source: Internet
Author: User

Php tips [recommended] and php tips

1. How to define common file separator numbers for linux and Windows

DIRECTORY_SEPARATOR:

Directory separator, which is a built-in constant that defines php. On the debugging machine, we habitually use "\" as the file Separator in windows, but the system does not know this identifier on linux, so we need to introduce this php built-in constant: DIRECTORY_SEPARATOR

In this way, you do not need to judge whether it is in linux or windows.

2 PHP compression and decompression class

PclZip is a powerful PHP class for compressing and decompressing zip files. The PclZip library can compress and decompress Zip files (WinZip and PKZIP ); this type of files can be processed, including generating compressed files, listing compressed files, and extracting files. You can also add or delete an existing ZIP package.

Recently it has been used for compressing files.

Generate a zip file

Usage 1:

<?php include_once('pclzip.lib.php'); $archive = new PclZip('archive.zip'); $v_list = $archive->create('file.txt,data/text.txt,folder'); if ($v_list == 0) {  die("Error : ".$archive->errorInfo(true)); }?>

Usage 2:

<?php include_once('pclzip.lib.php'); $archive = new PclZip('archive.zip'); $v_list = $archive->create('data/file.txt,data/text.txt',PCLZIP_OPT_REMOVE_PATH, 'data',PCLZIP_OPT_ADD_PATH, 'install'); if ($v_list == 0) {  die("Error : ".$archive->errorInfo(true)); }?>

Http://www.phpconcept.net/pclzip/

3. For a short section of "poor" PHP code optimization process, Please carefully understand the optimization process

The following section of the "poor" PHP code is a simplified test question. This is like a question: how do you optimize this code?

<?echo("<p>Search results for query: " .$_GET['query'] . ".</p>");?>

The main problem with this Code is that it directly displays the data submitted by the user on the webpage, resulting in an XSS vulnerability. There are actually many ways to fill this vulnerability. So what code is what we want?

<?echo("<p>Search results for query: " .htmlspecialchars($_GET['query']) . ".</p>");?>

This is the minimum requirement. The XSS vulnerability is filled by the htmlspecialchars function, thus blocking invalid characters.

<?php if (isset($_GET['query'])) {  echo '<p>Search results for query: ',  htmlspecialchars($_GET['query'], ENT_QUOTES), '.</p>'; } ?>

Optimization:

<?php if (isset($_GET['query'])) {  echo '<p>Search results for query: ',  htmlspecialchars($_GET['query'], ENT_QUOTES), '.</p>'; } ?>
  • <? Replaced with <? Php, which is more in line with XML specifications.
  • Determine whether the value of $ _ GET ['query'] is null before outputting it.
  • The extra parentheses in the echo command are removed.
  • The string is limited by single quotes, saving PHP time to search for replaceable variables from the string.
  • Use commas instead of periods to save the echo time.
  • Pass the ENT_QUOTES identifier to the htmlspecialchars function to ensure that the single quotation marks are also escaped. Although this is the most important thing, it is also a good habit.

4. You do not need to use a third-party class library to export MySQL Data to Excel.

If you export data frequently, you may encounter a third-party class library export ceiling, which is a very helpless thing. When there are more than 20 thousand data records, the export often fails. It is easy to reach the PHP memory usage limit

// Output the excelfile header. You can replace user.csv with the file name header ('content-Type: application/vnd. ms-excel '); header ('content-Disposition: attachment; filename = "user.csv"'); header ('cache-Control: max-age = 0 '); // obtain data from the database. To save memory, do not read data to the memory at one time. Read the data from one row in the handle. $ SQL = 'select * from tbl where ...... '; $ Stmt = $ db-> query ($ SQL); // open the php file handle. php: // output indicates that the file is directly output to the browser $ fp = fopen ('php: // output ', 'A'); // output Excel column Name Information $ head = array ('name', 'Gender', 'age', 'email ', 'telephony ','...... '); Foreach ($ head as $ I => $ v) {// CSV Excel supports GBK encoding and must be converted, otherwise, garbled code $ head [$ I] = iconv ('utf-8', 'gbk', $ v);} // writes data to the file handle fputcsv through fputcsv ($ fp, $ head); // counter $ cnt = 0; // refresh the output buffer every $ limit row. Do not set it to too large or too small $ limit = 100000; // extract data row by row without wasting memory while ($ row = $ stmt-> fetch (Zend_Db: FETCH_NUM) {$ cnt ++; if ($ limit = $ cnt) {// refresh the output buffer to prevent problems caused by excessive data. ob_flush (); flush (); $ cnt = 0 ;} foreach ($ row as $ I =>$ v) {$ row [$ I] = iconv ('utf-8', 'gbk', $ v );} fputcsv ($ fp, $ row );}

The method here is to use fputcsv to write a CSV file and directly output an Excel file to the browser.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.