Summary of common problems in php

Source: Internet
Author: User
Tags flock php session

This article adds to my favorites some of the questions or small issues that php developers often encounter. For more information, see.

The differences between the above functions,

1. Differences between isset () and empty ()
Both are used to test variables. However, isset () is used to test whether a variable is assigned a value, while empty () is used to test whether a variable that has been assigned a value is null. If a variable is not assigned a value, it is allowed to reference it in php, but there will be a notice prompt. If a variable is assigned a null value, $ foo = "" or $ foo = 0 or $ foo = false, empty ($ foo) returns true, isset ($ foo) returns the true value, that is, the null value will not cancel a variable. To cancel a variable, you can use unset ($ foo) or $ foo = NULL.
2. How to Display error messages
When php. when display_errors = On and error_reporting = E_ALL of ini, all errors and prompts are displayed. It is best to enable this function during debugging for error correction, if you use php to write errors, most of them are about undefined variables. A prompt is displayed before the variable value is assigned. The solution is to detect or block the variable.
3. What is the difference between single quotes and double quotes? When to use
In single quotes, any variable ($ var) or special escape characters (such as "t r n") will not be parsed, so PHP is faster to parse, escape characters only support the escape of single quotes and backslash. In double quotes, the variable ($ var) value is substituted into the string, special escape characters will also be parsed into a specific single character, and some special functional escape for the above two features, such as "$" and ". In this way, although programming is more convenient, PHP Parsing is also slow. In the array, if the subscript is not an integer but a string type, you must enclose the subscript in single quotes, the correct syntax is $ array ['key'] instead of $ array [key], because incorrect syntax makes the PHP parser think that key is a constant, then, the system first checks whether a constant exists and uses the "key" as the subscript to bring it into the expression if it does not exist. At the same time, an error event is triggered, resulting in a Notice-level error. Therefore, do not use double quotation marks when you can use single quotes in most cases.
4. What is the difference between print, echo, and print_r? When are they used?
Echo and print can both be used for output. The difference is that echo is not a function and there is no return value. print is a function that has a return value. Therefore, if only echo is output, it will be faster, print_r is usually used to print information about variables, which is usually used in debugging.
5. You may need to open remote files in PHP.
Open remote file functions are: fopen (http://XXX.com/a.php), fsockopen (http://XXX.com/a.php), file_get_contents (http://XXX.com/a.php), etc)
In the php5, apache2.2.X environment, you will be prompted that you cannot open the file stream, http request failed (failed to open stream: HTTP request failed !)
In php. ini, there are two options:
Allow_url_fopen = on (indicating that remote files can be opened through URLs ),
User_agent = "PHP" (indicates the script used to access the network. By default, there is .)
Restart the Apache service.
6. How to get the auto_increment value in advance?
Mysql_connect ('localhost', 'root', 'root') or die ('cannot connect to Server ');
Mysql_select_db ('test'); // connect to the database
$ SQL = "show create table id_user"; // id_userd indicates the table name.
$ Query = mysql_query ($ SQL );
$ Arr = mysql_fetch_array ($ query );
$ B = strstr ($ arr [1], 'Auto _ INCREMENT = '); // obtain the substring, including AUTO_INCREMENT = 5 DEFAULT CHARSET = utf8)
$ Result = intval (substr ($ B, 15); // substr () obtains the string from the string's 16th locations, and then converts the obtained string to the int type.
Echo 'Auto _ INCREMENT value '. $ result; // output result: the ID value of the next data insertion.
7. Obtain client information
Getenv ("REMOTE_ADDR") to get the IP address of the browser
Getenv ("HTTP_USER_AGENT") can obtain the browser's operating system type.
Getenv can get all the global variables $ _ ENV.
Print_r ($ _ ENV) can see a lot of things
For example
Echo getenv (ALLUSERSPROFILE); the value of ALLUSERSPROFILE is displayed.
Echo getenv (PATHEXT); you can see the value of PATHEXT
8. Differences between mysql_fetch_row () and mysql_fetch_array ()
Mysql_fetch_array () is an extension of mysql_fetch_row. In addition to storing data in an array as a digital index, you can also store data as an associated index and use the field name as the key name. Mysql_fetch_array () is not significantly slower than mysql_fetch_row (), and more values are provided.
The second optional parameter result_type in mysql_fetch_array () is a constant and can accept the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH. This feature is newly added in PHP 3.0.7. The default value of this parameter is MYSQL_BOTH.
9. Usage and efficacy of EOD
It is better than single quotes and double quotes, and can contain line breaks. You can change the EOD to another character.
10. How can I use gdate () to obtain a long string of numbers and convert it to a normal time?
Gmdate returns the GMT time, which is exactly the same as date. If you need local time, use date () to format the timestamp.
11. What is the difference between () // in the regular expression?
// It is a pattern delimiter, which indicates a regular rule.
() Indicates the sub-mode. A/can contain many () components. You can use 1 2 or $1 $2 to match the values of the previous sub-mode.
12. What is the difference between require and require_once?
Repeated require calls load the files you drink multiple times. require_once is loaded only once, no matter how many times you actually call it, it is mainly used for complex file inclusion relationships.
For example, if B contains a, c contains a, but c also contains B, then if require is used, it may cause two loads of
13. What are the differences between the three IP addresses?
$ _ SERVER ['remote _ ADDR '];
$ _ SERVER ['HTTP _ CLIENT_IP '];
$ _ SERVER ['HTTP _ X_FORWARDED_FOR '];
$ _ SERVER ['remote _ ADDR ']; // IP address of the access end (which may be a user or a proxy)
$ _ SERVER ['HTTP _ CLIENT_IP ']; // proxy end (it may exist and can be forged)
$ _ SERVER ['HTTP _ X_FORWARDED_FOR ']; // the proxy of the user's IP address (which may exist or can be forged)
14. What is the difference between $ _ GET and $ _ POST?
1. The get method limits the size of the value to be passed. The post method does not limit the size of the value to be passed.
2. Get is used to obtain data from the server, while Post is used to transmit data to the server.
3. Get adds the data in the form to the URL pointed to by action in the form of variable = value, and uses "?" Connect, and use "&" to connect various variables. Post is to place the data in the form data body, and pass the data to the URL pointed to by the action according to the corresponding variables and values.
4. Get is insecure because data is stored in the request URL during transmission, nowadays, many existing servers, proxy servers, or user proxies record the request URL to a log file and place it in a certain place, so that some private information may be seen by a third party. In addition, you can directly view the submitted data in the browser. Some internal messages are displayed in front of the user. All Post operations are invisible to users.
15. public and private can be added before the functions in the class, but cannot be added before the functions in the function library?
You can customize functions as needed. public is a publicly used class property object, and privat is an independently used class property object;
In a class, public or private indicates whether this method (which must be called "method") is made public to the public or belongs to the class private and you are referring to the function library. It is a "function" library, it does not belong to methods in the class, so there is no need or pre-modification.
16. How is the page execution time calculated?

The Code is as follows: Copy code
$ Mtime = explode ('', microtime ());
$ Starttime = $ mtime [1] + $ mtime [0];
......
......
......
$ Mtime = explode ('', microtime ());
$ Endtime = $ mtime [1] + $ mtime [0];
$ Usedtime = $ endtime-$ starttime;
Printf ("<br/> % 0.4f s", $ usedtime );

17. The UTF8 encoding script session_start (), header (), settcookie () and other functions have an error and the system prompts "headers already sent".
Generally, the editor of The UTF8 encoding script adds a three-byte BOM code to the file header to identify the UTF8 encoding format. These three bytes are invisible to the normal file editor, the output is output in HTML first. The above error is prompted when you execute the above function. Solution: Use editplus to clear the BOM editor and clear the BOM (set to utf8 to clear the BOM.
18. Differences between single quotation marks, double quotation marks, and reverse quotation marks in PHP
PHP single quotes ('), double quotes (""), and backquotes (') can reference strings. Variables in single quotes are not escaped. Variables in double quotes are escaped. Variable escaping in backquotes is executed as shell commands.

The following describes some common problems in development.

Next we will discuss from a minor issue to some fatal errors. It is divided into three parts.
Part 1 minor errors
I. Printf (),
This function is mainly used to format and display data. It is used only when you want to change the display format of a data.
For example, the PI (3.1415926) value is displayed with different precision.

The Code is as follows: Copy code
<? Php

Printf ("Pi is: %. 2fn <br> n", M_PI );
Printf ("Pi is also: %. 3fn <br> n", M_PI );
Printf ("Pi is also: %. 4fn <br> n", M_PI );
?>

However, many programmers only use this function to display some variable values and function return values. Because Printf () needs to format the data at a low speed before displaying the data, it only applies print and echo to display the data to increase the speed.
Ii. semantic check
PHP is a weak type language, that is, it does not need to be defined before using a variable, which brings great convenience and flexibility to programming, however, you must know the type of the variable, because the variable still corresponds to a certain type (various types

Can be freely converted between), no type of variable does not exist. It is possible that PHP does not check your semantic errors, but changes in the variable type may cause some potential problems. Another noteworthy problem is the scope of the variable, which may also lead

Some potential problems occur.
PHP has the following basic variables:
Boolean, resource, integer, double, string, array and object.
Iii. Use of temporary variables
Misuse of temporary variables can reduce the program running efficiency. When to use temporary variables can be based on the following two considerations:
1. Whether the variable is used at least twice.
2. Will the use of this variable significantly improve the readability of the program.
If either of them is true, the use of the variable is omitted. For example:

The Code is as follows: Copy code

<? Php
$ Tmp = date ("F d, h: I ");
Print $ tmp;
?>
It should be changed:
<? Php
Print date ("F d, h: I ");
?>

Another example:

<? Php

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

?>

Can be changed:
 

The Code is as follows: Copy code
<? Php

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

?>

Network Problems Found


FAQ highlights in php [1] variables cannot be transferred between pages
The get, post, and session automatic global variables are disabled in the latest php version. Therefore, to obtain and submit the variables from the previous page, use $ _ GET ['foo']. $ _ POST ['foo'], $ _ SESSION ['foo'] to obtain
Of course, you can also change the automatic global variable to On (php. ini is changed to register_globals = On). Considering compatibility, it is better to force yourself to get familiar with the new writing method.

[2] an error occurs when apache2 uses the get method to pass Chinese parameters under Win32.
Test. php? A = Hello & B = You
Passing parameters will cause an internal error.
Solution: "test. php? A = ". urlencode (Hello)." & B = ". urlencode (you can also)

[3] The session under win32 does not work normally
Php. ini default session. save_path =/tmp
This is obviously a configuration in linux. in win32, php cannot read or write session files, and thus the session cannot be used.
Change it to an absolute path, for example, session. save_path = c: windowstemp.

[4] displaying error messages
When php. when display_errors = On and error_reporting = E_ALL of ini, all errors and prompts are displayed. It is best to enable this function during debugging for error correction, if you use php to write errors, most of them are about undefined variables. A prompt is displayed before the variable value is assigned. The solution is to detect or block the variable.
For example, if $ foo is displayed, you can use if (isset ($ foo) echo $ foo or echo @ $ foo.

[5] Win32 mail () cannot send email
Sendmail configured in linux can be sent. in win32, you need to call the smtp server to send emails.
Modify SMTP = ip address of php. ini // ip address is an smtp server without verification function (it is hard to find it online)
The best solution for sending emails in php is to directly send emails to the recipient's email server using socket instead of forwarding the server.
There is a good class, but it will be fast to change the mail. The modified version will be available soon.

[6] the header already sent error usually occurs when you use the HEADER. It may be caused by the following reasons:
1. You PRING or ECHO before using the HEADER
2. You have a blank line before the current file.
3. You may INCLUDE a file. This error may also occur if there are blank lines at the end of the file or the output file .!
Also use session_register ()

[7] if the password is not set for the newly installed mysql, use
Update mysql. user set password = password ("yourpassword") where user = "root"

[8] php. ini has not changed.
Restart the web server, such as IIS and Apache, and then apply the latest settings.

[9] php installation on 2003 (ISAPI installation method)
Php4isapi. dll of PHP4 seems to be in conflict with 2003. It can only be installed in CGI Mode.

Step 1, first go to an installer, I am installing: php-4.2.3-installer.exe, you can also go to find the latest version, ensure your IIS6.0 started before installing the php-4.2.3-installer.exe, and can be accessed. After installation, go to the default website --> application configuration
Step 2: click web Service Extension> Create web service extension.
Step 3: add the extension --> php
Step 4: Find the php.exe path and add it.
Step 5: OK!
Step 6: select the php service extension and click Allow.

[10] Sometimes SQL statements do not work and database operations fail.
The simplest debugging method is echo the SQL statement to see if the variable value can be obtained.

[11]

The Code is as follows: Copy code

<? Php

// Available from PHP 3
Print $ HTTP_POST_VARS ['username'];

// Available from PHP 4.1.0
Print $ _ POST ['username'];
Print $ _ REQUEST ['username'];

Import_request_variables ('P', 'P _');
Print $ p_username;


// If the PHP Command register_globals = on is available. However, this method is not recommended since PHP 4.2.0 and the default value is register_globals = off.
Print $ username;
?>

The same applies to GET forms, except that appropriate GET predefined variables are used. GET also applies to QUERY_STRING (in the URL, "?" ). So, for example, http://www.example.com/test.php? Id = 3 contains GET data that can be accessed by $ _ GET ['id. See $ _ REQUEST and import_request_variables ().
The default value of register_globals before PHP 4.2.0 is on. In PHP 3, its value is always on. We encourage you not to rely on this command. We recommend that you consider it as off during encoding.

 

[12] 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 ($ )){
# Reconstructs array
$ A = array ("af" => "fsdf"), "f" => "df ");
}
W ('temp. php', var_export ($ a, true ));

Var_dump ($ );
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] differences between include and require
There is no big difference between the two. If the file to be included does not exist, include prompts notice and continues executing the following statement. require prompts a fatal error and exits. According to my test, on the win32 platform, they are all included first and then executed. Therefore, it is best not to have include or require statements in the contained files, which will cause directory confusion. It may be different in linux and has not been tested yet. If a file does not want to be contained for multiple times, you can use include_once or require_once.

[14] Application of session in functions and methods: all variables you intend to register into the session must be global.

The reason is as follows:
The session_register function of php only remembers the name of a variable rather than the value of the variable.
The value of this variable must be remembered on the server end after the entire script is running, that is to say, the variable value will be read and saved to the temporary directory on the server only when the script stops running. In this way, register is successful only for all variables outside the function or method or defined as global variables in the function or method, while others will be unset at the end of the script.

[15] The session in PHP is implemented based on cookies, so it will not disappear immediately after all session windows are closed. This is different from other scripting languages and also depressing me.

A: No, no. My friends upstairs did not thoroughly study the php session. If you have to say that the php session is related to the cookie, that is, a session_id is recorded on the client.
In the temporary directory on the server side, a file with the approximate name of session_id will be generated. This file is the variable that truly records your successful register and their values. Similarly, if the client prohibits the use of cookies, php will automatically pass the session_id value in the get method so that it will not be lost. Therefore, the relationship between cookies and sessions is not so inseparable. Moreover, php sessions cannot be implemented based on cookies.

[16] differences between isset () and empty ()
If a variable is not assigned a value, it is allowed to reference it in php, but there will be a notice prompt;
Both are used to test the variables, but isset () is used to test whether the variables are assigned values, and empty () is used to test whether a variable that has been assigned values is null.
If a variable is assigned a null value, $ foo = "" or $ foo = 0 or $ foo = false, empty ($ foo) returns true, isset ($ foo) returns the true value, that is, the null value will not cancel a variable. To cancel a variable, you can use unset ($ foo) or $ foo = NULL.

[17] how to upload multiple files at a time through the HTTP protocol
There are two ways to implement the same method.
1. Set multiple file input boxes in form and name them using arrays, as shown below:

The Code is as follows: Copy code

<Form action = "" method = post enctype = "multipart/form-data">
<Input type = file name = usefile []>
<Input type = file name = usefile []>
<Input type = file name = usefile []>
</Form>
In this way, perform the following tests on the server side:
Echo "<pre> ";
Print_r ($ _ FILES );
Echo "</pre> ";

2. Set multiple file input boxes in form with different names, as shown below:
<Form action = "" method = post enctype = "multipart/form-data">
<Input type = file name = usefile_a>
<Input type = file name = usefile_ B>
<Input type = file name = usefile_c>
</Form>
Perform the same test on the server:
Echo "<pre> ";
Print_r ($ _ FILES );
Echo "</pre> ";

[18] You can create a temporary PHP file and include it in the desired place. In this way, the variables defined in the temporary PHP file will be available and the session can be replaced.

[19] As mentioned above, the get and post methods cannot be directly submitted. Sometimes it is very troublesome to write code segments and convert them into global variables for ease of use, session variables are also available.
Convert the variables submitted through GET or POST to global variables:

The Code is as follows: Copy code
Foreach ($ _ GET as $ key => $ value ){
$ Key = $ value;
}
Foreach ($ _ POST as $ key => $ value ){
$ Key = $ value;
}

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.