Home >Backend Development >PHP Tutorial >Summary of common problems in php_PHP tutorial

Summary of common problems in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:56:011157browse

This article collects some doubts or small problems that are often encountered in PHP development. You can refer to them.

The difference between some of the above functions,

1. The difference between isset() and empty()
Both are used for testing variables. But isset() tests whether a variable has been assigned a value, and empty() tests whether a variable that has been assigned a value is empty. If a variable is referenced in PHP without being assigned a value, it is allowed, but there will be a notice. If a variable is assigned a null value, $foo="" or $foo=0 or $foo=false, then empty($foo) returns true and isset($foo) also returns true, which means assigning a null value will not log out. a variable. To unregister a variable, use unset($foo) or $foo=NULL.
2. How to display error messages
When display_errors = On and error_reporting = E_ALL in php.ini, all errors and prompts will be displayed. It is best to turn it on during debugging for error correction. If you use the previous PHP writing method, most of the error messages are about undefined variables. . There will be a prompt when a variable is called before it is assigned a value. The solution is to detect or shield
3. What is the difference between single quotes and double quotes? When to use it
In single quotes, any variables ($var) and special escape characters (such as "t r n", etc.) will not be parsed, so PHP's parsing speed is faster. The escape characters only support "'" and "" Escape single quotes and backslashes themselves; in double quotes, the variable ($var) value will be substituted into the string, special escape characters will also be parsed into specific single characters, and some are specifically for the above two items Special functional escaping of attributes, such as "$" and ". Although programming is more convenient, PHP's parsing is also very slow; in an array, if the subscript is not an integer but a string type, be sure to use Single quotes enclose the subscript. The correct writing is $array['key'], not $array[key], because incorrect writing will cause the PHP parser to think that key is a constant, and then first determine whether the constant exists. , only use "key" as a subscript into the expression, and an error event will be triggered to generate a Notice-level error. Therefore, do not use double quotes in most situations where single quotes can be used.
4.What is the difference between print, echo and print_r? When should they be used?
Both echo and print can do output. The difference is that echo is not a function and has no return value, while print is a function with a return value, so relatively speaking it will be faster if it just outputs echo, and print_r is usually used for printing. Information about variables, usually used in debugging

5. Sometimes you need to open remote files in PHP
The functions to open remote files are: fopen(http://XXX.com/a.php), fsockopen(http://XXX.com/a.php), file_get_contents(http://XXX.com/a .php) etc.)
In php5 and apache2.2.X environments, you will be prompted that the file stream cannot be opened and the http request failed (failed to open stream: HTTP request failed!)
In php.ini, there are two options:
allow_url_fopen =on (indicates that remote files can be opened through url),
user_agent=”PHP”(Indicates which script is used to access the network. By default, there is a “;” in front of it. Just remove it.)
Just restart the Apache service.

6. How to get the value of auto_increment in advance?
mysql_connect('localhost','root','root') or die('Cannot connect to the server');
mysql_select_db (’test '); // Connect the database
$sql = “show create table id_user”; //id_userd is the table name
$query = mysql_query($sql);
$arr = mysql_fetch_array($query);
$b = strstr($arr[1],’AUTO_INCREMENT=’); //Get the substring, including AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 )
$result = intval(substr($b,15)); //substr() gets the string from the 16th position of the string, and then converts the obtained string to int type
response
7. Use to obtain client information
getenv(”REMOTE_ADDR”) can get the viewer’s IP
getenv("HTTP_USER_AGENT") can get the browser's operating system type and browser type
getenv can get everything in the $_ENV global variable
print_r($_ENV) can see a lot of things
For example
echo getenv(ALLUSERSPROFILE); You can see the value of ALLUSERSPROFILE
echo getenv(PATHEXT); You can see the value of PATHEXT

8. The difference between mysql_fetch_row() and mysql_fetch_array()
mysql_fetch_array() is an extended version of mysql_fetch_row(). In addition to storing data in an array as a numerical index, you can also store data as an associative index, using the field name as the key. Using mysql_fetch_array() is not significantly slower than using mysql_fetch_row(), and it also provides significantly more values.
The optional second parameter result_type in mysql_fetch_array() is a constant that can accept the following values: MYSQL_ASSOC, MYSQL_NUM and MYSQL_BOTH. This feature is new since PHP 3.0.7. The default value of this parameter is MYSQL_BOTH.
9. Usage and efficacy of EOD
is better than single quotes and double quotes and can contain newlines. EOD can be changed to other characters.
10. How to convert a long string of numbers into normal time using gdate()?
gmdate returns GMT time, except that it is exactly the same as the date() function. If you need local time, use date() to format the timestamp.
11. What is the difference between ()//in regular expressions?
/ / is the pattern delimiter, which means there is a regular rule inside.
( ) represents a sub-pattern. There can be many ( ) components in a //. You can use 1 2 or $1 $2 to match the value of the previous sub-pattern.
12.What is the difference between require and require_once?
Repeated calls to require will load the files you drink multiple times; require_once only loads once, regardless of how many times you actually call it, and is mainly used for complex file inclusion relationships
For example, b contains a, c contains a, but at the same time, c also contains b. If you use require, a may be loaded twice
13. What are the differences in obtaining the three IP addresses?
$_SERVER['REMOTE_ADDR'];
$_SERVER['HTTP_CLIENT_IP'];
$_SERVER['HTTP_X_FORWARDED_FOR'];
$_SERVER['REMOTE_ADDR'];                                                                //Accessor (may be the user, may be the proxy) IP
$_SERVER['HTTP_CLIENT_IP']; //Agent-side (may exist, can be forged)
$_SERVER['HTTP_X_FORWARDED_FOR']; //Which IP does the user use as a proxy (may exist or can be forged)
14. What is the difference between $_GET and $_POST?
1: The get method limits the size of the passed value, which cannot exceed 2K. The post does not limit the size of the passed value.
2: Get is used to obtain data from the server, while Post is used to transfer data to the server.
Three: Get adds the data in the form to the URL pointed to by the action in the form of variable=value, and the two are connected using "?", and each variable is connected using "&"; Post is to add the data in the form to the URL pointed to by the action. The data is placed in the data body of the form and passed to the URL pointed to by the action according to the corresponding variables and values.
Four: Get is unsafe because during the transmission process, the data is placed in the requested URL, and many existing servers, proxy servers or user agents will record the requested URL in a log file and then place it somewhere. place, so that some private information may be seen by third parties. In addition, users can also see the submitted data directly on the browser, and some internal system messages will be displayed in front of the user. All Post operations are invisible to users.
15. You can add public and private in front of functions in a class, but you can’t add them in front of functions in a function library?
You can customize the function as you wish. Public is a class attribute object that is used publicly, and private is a class attribute object that is used independently;
Public or private in a class refers to whether the method (note that it is called "method") is public or private to the class. The function library you are referring to is a library of "functions" and does not belong to methods in the class, so it does not need to be There can be no pre-modification.
16. How is the page execution time calculated?

The code is as follows Copy code
$mtime = explode(' ', microtime( ));
 代码如下 复制代码
$mtime = explode(’ ‘, microtime());
$starttime = $mtime[1] + $mtime[0];
……
……
……
$mtime = explode(’ ‘, microtime());
$endtime = $mtime[1] + $mtime[0];
$usedtime = $endtime - $starttime;
printf(”
%0.4f s”, $usedtime);
$starttime = $mtime[1] + $mtime[0]; … … … $mtime = explode(’ ‘, microtime()); $endtime = $mtime[1] + $mtime[0]; $usedtime = $endtime - $starttime; printf("
%0.4f s", $usedtime);

17. UTF8 encoding script session_start(), header(), settcookie() and other functions have errors, prompting "headers already sent".
UTF8 encoding scripts. Usually editors will add a three-byte BOM encoding to the file header to identify the UTF8 encoding format. These three bytes are invisible to ordinary file editors, and they are output as HTML first. Output. The above error will be prompted when executing the above function. Solution: Use an editor such as editplus that can clear the BOM, clear the BOM (set to utf8 to clear the BOM) and save it.
18. The difference between single quotes, double quotes and backticks in PHP
PHP single quotes (’), double quotes ("") and backticks (`) can quote strings. Variables in single quotes are not escaped, variables in double quotes are escaped, and variables in backticks are escaped and executed as shell commands.

Xia Cheng introduced some common development problems

Let’s start with the minor issues and then go up to some fatal mistakes. It is divided into three parts.
Part 1, minor errors
1. Printf(),
This function is mainly used to format and display data. Use it only when you want to change the display format of certain data.
For example, display the value of PI (3.1415926) with different precisions.

The code is as follows Copy code
代码如下 复制代码
 
 printf ("Pi is: %.2fn
n", M_PI);
   printf ("Pi is also: %.3fn
n", M_PI);
   printf ("Pi is also: %.4fn
n", M_PI);
  ?>

​printf ("Pi is: %.2fn
n", M_PI);
​printf ("Pi is also: %.3fn
n", M_PI); ​printf ("Pi is also: %.4fn
n", M_PI);
?>

But many programmers only use this function to display some variable values ​​and function return values. Because Printf() must format the data before displaying the data, the speed is slow. Therefore, print and echo are only used when displaying the data to increase the speed.

2. Semantic check


PHP is a weakly typed language, which means that you don’t need to define a variable before using it. This brings great convenience and flexibility to programming, but you must know what type the variable should be, because This variable still actually corresponds to a certain type at runtime (various types

can be freely converted to each other), variables without types do not exist. It is possible that PHP cannot detect your semantic errors, but due to changes in variable types, some potential problems may occur. Another issue worth noting is the scope of variables, which may also cause
Some potential problems occur.
There are the following basic variables in PHP:
Boolean, resource, integer, double, string, array and object.

3. Use of temporary variables

 代码如下 复制代码

 $tmp = date ("F d, h:i a");
 print $tmp;
?>
  就应该改成:
   print date ("F d, h:i a");
?>
  
  又如:

 
// string reverse_characters(string str)
// Reverse all of the characters in a string.
function reverse_characters ($str)
{
 return implode ("", array_reverse (preg_split("//", $str)));
}

?>

The abuse of temporary variables will lead to a reduction in program operating efficiency. When to use temporary variables can be based on the following two considerations: 1. Whether the variable is used at least twice. 2. Whether the use of this variable will significantly improve the readability of the program. If none of these are satisfied, the use of this variable is omitted. For example:
The code is as follows Copy code
​ $tmp = date ("F d, h:i a"); <🎜> ​print $tmp; <🎜> ?> should be changed to: ​print date ("F d, h:i a"); <🎜> ?> Another example: <🎜> // string reverse_characters(string str) <🎜> // Reverse all of the characters in a string. <🎜> function reverse_characters ($str) <🎜> { <🎜> ​return implode ("", array_reverse (preg_split("//", $str))); <🎜> } <🎜> <🎜> ?>

  的可读性不强,可改成: 
 

 代码如下 复制代码
代码如下 复制代码

// string reverse_characters(string str)
// Reverse all of the characters in a string.
function reverse_characters ($str)
{
 $characters = preg_split ("//", $str);
 $characters = array_reverse ($characters);

 return implode ("", $characters);
}

?>
  
     // string reverse_characters(string str)   // Reverse all of the characters in a string.   function reverse_characters ($str)   {    $characters = preg_split ("//", $str);    $characters = array_reverse ($characters);       return implode ("", $characters);   }      ?>   

Some problems found on the Internet


Collection of frequently asked questions in php 2009-09-10 11:07 [1] Variables cannot be passed between pages
The automatic global variables of get, post, and session are turned off in the latest PHP version, so to get the submitted variables from the previous page, use $_GET['foo'], $_POST['foo'], $_SESSION[ 'foo'] to get
Of course, you can also modify the automatic global variables to be on (php.ini is changed to register_globals = On); considering compatibility, it is better to force yourself to become familiar with the new writing method.

【2】An error occurs when passing Chinese parameters using the get method in apache2 under Win32
test.php?a=Hello&b=Hello too
Passing parameters will cause an internal error
Solution: "test.php?a=".urlencode(Hello)."&b=".urlencode(Hello)

【3】session under win32 does not work properly
php.ini default session.save_path = /tmp
This is obviously a configuration under Linux. PHP under win32 cannot read and write session files, causing the session to be unusable
Just change it to an absolute path, for example session.save_path = c:windowstemp

【4】Display error message
When display_errors = On and error_reporting = E_ALL in php.ini, all errors and prompts will be displayed. It is best to turn them on during debugging for error correction. If you use the previous PHP writing method, most of the error messages will be about undefined variables. There will be a prompt when a variable is called before it is assigned a value. The solution is to detect or shield
For example, to display $foo, you can if(isset($foo)) echo $foo or echo @$foo

【5】mail() cannot send emails under Win32
Sendmail configured under linux can be sent, but under win32 you need to call the smtp server to send emails
Modify SMTP of php.ini = ip //ip is an smtp server without verification function (hard to find online)
The best solution for sending emails in php is to use socket to send directly to the other party's email server without forwarding the server
There is a very good class, but it needs to be modified to make sending messages faster. The modified version will be launched in the near future

【6】The header already sent error usually occurs when you use HEADER. It may be due to several reasons:
1. You PRING or ECHO before using HEADER
2. There is a blank line
in front of your current file. 3. You may have INCLUDEd a file and there is a blank line at the end of the file or this error will appear in the output. !
Also use session_register()

【7】If you do not set a password for the initial installation of mysql, you should use
update mysql.user set password=password("yourpassword") where user="root"

【8】No change after changing php.ini
Restart the web server, such as IIS, Apache, etc., and then the latest settings will be applied

[9] PHP installation on 2003 (ISAPI installation method)
The php4isapi.dll of PHP4 seems to conflict with 2003 and can only be installed in CGI mode

Step 1, first go to an installation program. I installed it: php-4.2.3-installer.exe. You can also find the latest version before installing php-4.2.3-installer.exe. Make sure your IIS6.0 is started and accessible. After installation, go to the default website-->Application Configuration
Step 2: Click web service extension -->New web service extension.
Step 3: Extension-->php, then add
Step 4: Find the path to php.exe and add it.
Step Five: Confirm and that’s it!
Step 6: Select the PHP service extension and click Allow.

【10】Sometimes the sql statement does not work and the database operation fails
The easiest way to debug is to echo the SQL statement and see if the value of the variable can be obtained

【11】

The code is as follows Copy code
 代码如下 复制代码

// 自 PHP 3 起可用
print $HTTP_POST_VARS['username'];

// 自 PHP 4.1.0 起可用
print $_POST['username'];
print $_REQUEST['username'];

import_request_variables('p', 'p_');
print $p_username;


// 如果PHP指令 register_globals = on 时可用。不过自PHP 4.2.0 起默认值为 register_globals = off不提倡使用此种方法。
print $username;
?>

<🎜>// Available since PHP 3 <🎜> print $HTTP_POST_VARS['username'];<🎜> <🎜>// Available since PHP 4.1.0 <🎜> print $_POST['username']; <🎜> print $_REQUEST['username'];<🎜> <🎜>import_request_variables('p', 'p_'); <🎜> print $p_username;<🎜> <🎜><🎜> // Available if PHP directive register_globals = on. However, since PHP 4.2.0, the default value is register_globals = off and this method is not recommended. <🎜> print $username; <🎜> ?>

Using the GET form is similar, but you need to use the appropriate GET predefined variables. GET also works with QUERY_STRING (the information after the "?" in the URL). So, for example, http://www.example.com/test.php?id=3 contains GET data accessible with $_GET['id']. See $_REQUEST and import_request_variables().
Before PHP 4.2.0 the default value of register_globals was on. In PHP 3 its value is always on. You are encouraged not to rely on this directive, and it is recommended to code assuming it is off.

[12] Temporarily save your variables to a temporary file:

The code is as follows Copy code
 代码如下 复制代码

if(file_exists('temp.php'))
{
$x=r('temp.php');
@eval("$a = $x;");
}
if(!is_array($a)){
#重新构造数组A
$a=array(array("af"=>"fsdf"),"f"=>"df");
}
w('temp.php',var_export($a,true));

var_dump($a);
读取,写入文档数据
function r($file_name)
{
$filenum=@fopen($file_name,"r");
@flock($filenum,LOCK_SH);
$file_data=@fread($filenum,filesize($file_name));
@fclose($filenum);
return $file_data;
}
function w($file_name,$data,$method="w")
{
$filenum=@fopen($file_name,$method);
flock($filenum,LOCK_EX);
$file_data=fwrite($filenum,$data);
fclose($filenum);
return $file_data;
}

if(file_exists('temp.php')) { $x=r('temp.php'); @eval("$a = $x;"); } if(!is_array($a)){ #Reconstruct array A $a=array(array("af"=>"fsdf"),"f"=>"df"); } w('temp.php',var_export($a,true)); var_dump($a); Read and write document data function r($file_name) { $filenum=@fopen($file_name,"r"); @flock($filenum,LOCK_SH); $file_data=@fread($filenum,filesize($file_name)); @fclose($filenum); return $file_data; } function w($file_name,$data,$method="w") { $filenum=@fopen($file_name,$method); flock($filenum,LOCK_EX); $file_data=fwrite($filenum,$data); fclose($filenum); return $file_data; }

【13】The difference between include and require
There is not much difference between the two. If the file to be included does not exist, include prompts notice, and then continues to execute the following statement. require prompts a fatal error and exits; according to my testing, under the win32 platform, they are included first and then executed, so It is best not to have include or require statements in the included files, as this will cause directory confusion. Maybe the situation is different in Linux, and I haven’t tested it yet; if you don’t want a file to be included multiple times, you can use include_once or require_once

【14】Application of session in functions and methods: The variables you plan to register into the session must be global.

The reason is this:
PHP's session_register function only remembers the name of the variable, but not the value of the variable.
The real need to remember the value of this variable on the server side is after the entire script is finished running. That is to say, the value of the variable will be read and saved into the temporary directory on the server side when the script is finished running. In this way, in all functions Only variables outside the method or defined as global variables within the function or method will be successfully registered, while others will be unset at the end of the script.

[15] Since the session in PHP is based on cookies, it will not disappear immediately after all session windows are closed. This is different from other scripting languages, and it also makes me feel depressed.

Answer: No, no, no, the friend above has not thoroughly studied the session of PHP. If we must say that the session of PHP is related to cookies, it means that a session_id is recorded on the client
In the temporary directory on the server side, a file with roughly the same name as the session_id will be generated. This file is the real record of the variables you have successfully registered and their values. Similarly, if the client prohibits the use of cookies, PHP will automatically pass the value of session_id in the get method so that it will not be lost. Therefore, the relationship between cookies and sessions is not so inseparable. Moreover, PHP's session cannot be said to be based on cookies.

【16】The difference between isset() and empty()
If a variable is referenced in PHP without being assigned a value, it is allowed, but there will be a notice;
Both are used to test variables, but isset() tests whether a variable has been assigned a value, while empty() tests whether a variable that has been assigned a value is empty
If a variable is assigned a null value, $foo="" or $foo=0 or $foo=false, then empty($foo) returns true and isset($foo) also returns true, which means assigning a null value will not log out. a variable. To unregister a variable, you can use unset($foo) or $foo=NULL

【17】How to upload multiple files at one time via HTTP protocol
There are two ideas, two implementations of the same method.
1. Set multiple file input boxes in the form and name them with arrays, as follows:

The code is as follows Copy code
 代码如下 复制代码






这样,在服务器端做以下测试
echo "
"; <br>
print_r($_FILES); <br>
echo "
";

2,在form中设置多个文件输入框,但名字不同,如下:






在服务器端做同样测试:
echo "
"; <br>
print_r($_FILES); <br>
echo "
";

In this way, do the following tests on the server side echo "
"; 
print_r($_FILES); 
echo "
"; 2. Set multiple file input boxes in the form, but with different names, as follows:
Do the same test on the server side: echo "
"; 
print_r($_FILES); 
echo "
";

【18】You can create a temporary PHP format file and include it where needed, so that the variables defined in the temporary PHP file are available and can replace the session.

【19】As mentioned above, the methods submitted through get and post cannot be used directly. Sometimes it is very troublesome. I wrote a piece of code myself and converted them into global variables for easy use. The session variables can be used in the same way. .
Convert variables submitted through GET or POST into global variables:

The code is as follows
 代码如下 复制代码
foreach($_GET as $key=>$value){
$$key=$value;
}
foreach($_POST as $key=>$value){
$$key=$value;
}
Copy code
foreach($_GET as $key=> $value){
$$key=$value; }

foreach($_POST as $key=>$value){

$$key=$value; http://www.bkjia.com/PHPjc/632206.html
www.bkjia.com
true
http: //www.bkjia.com/PHPjc/632206.htmlTechArticleThis article collects some doubts or small problems that are often encountered in PHP development. You can refer to them. The difference between some of the above functions, 1. The difference between isset() and empty() Both are...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn