A summary of some common PHP problems (favorites)

Source: Internet
Author: User

This article brings the content is about PHP common some of the problems summary (collection), there is a certain reference value, the need for friends can refer to, I hope to help you.

1. What is the difference between single and double quotes when defining a string?

Single quote loading speed faster than double quotation marks

What is the difference between 2.echo (), print (), Print_r ()?

(1) Echo is syntax, Output one or more strings, no return value;
(2) Print is a function that cannot output arrays and objects, Outputastring,print
has a return value;
(3) Print_r is a function that can output an array. Print_r is a more interesting function, you can output stirng, int, float, array, object, and so on, the output array will be represented by the structure, Print_r output is true when successful, and Print_r can be Print_r ($ Str,true), so that the print_r does not output and returns the value after Print_r processing. In addition, for Echo and print, the basic use of ECHO is mostly, because its efficiency is higher than print.

3. What are the string handling functions according to functional classification? What is the function of these functions?

A. String output function
(1) Echo $a, $b, $c ...; is a language structure, not a real
(2) print ($a) The output string of this function. Returns 1 if successful, failure returns 0
(3) Print_r ($a)
(4) Var_dump ($a); Can output type, length, value
B. Functions that remove the string leading and trailing spaces: trim LTrim RTrim (alias: chop) Use the second argument, and you can also remove the specified character.
C. Escape string function: Addslashes ()
D. function to get string length: strlen ()
E. Functions for intercepting string Lengths: substr ()
F. Retrieving String functions: Strstr (), Strpos ()
G. Substitution string function: Str_replace ()

4. Do you have the correct answers to the following questions?

1). $arr = Array (' James ', ' Tom ', ' Symfony '); Use the value of the $arr array ', ' to split and merge into a string output?

echo implode (', ', $arr);

2). $str = ' jack,james,tom,symfony '; Please split the $str with ', ' and put the split value in the $arr array?

$arr = Explode (', ', $str);

3). $arr =array (3,7,2,1, ' d ', ' abc '); Please sort the $arr in order from large to small, and keep its key value unchanged?

Arsort ($arr);p rint_r ($arr);

4). $mail = "gaofei@163.com"; Please remove the domain (163.com) of this mailbox and print it to see how many methods can be written?

Echostrstr ($mail, ' 163 '); Echosubstr ($mail, 7); $arr =explode ("@", $mail); echo$arr[1];

5. Page characters appear garbled, how to solve?

1. First consider whether the current file is set by character sets. See if the META tag is written in CharSet, if it is a PHP page you can also see if it is
The charset is specified in the header () function;
For example:

<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>header ("content-type:text/html;charset= Utf-8 ");

2. If the character set (that is, CharSet), then the current file is determined
Whether the saved encoding format is consistent with the character set of the page,
The two must remain unified;
3. If you are involved in extracting data from a database, then when you judge the database query
Whether the character set is consistent with the character set of the current page, the two must be uniform,
For example:

mysql_query ("Set names UTF8").

6. What is a regular expression? What are the usual regular-related functions in PHP? Please write a regular expression for email, Chinese mobile phone number and landline number.


Regular expression is a syntax rule that describes the pattern of character permutations. Regular expressions are also called pattern expressions. Web site development expressions are most commonly used for client-side validation before form submission information.
For example, verify that the user name is entered correctly, password input is compliant, email, mobile phone number and other information input is legal
in the PHP expression is mainly used for string segmentation, matching, lookup and
Replace operation. The
Preg series functions can be processed. There are several:
Stringpreg_quote (Stringstr[,stringdelimiter])
Escape Regular expression Word regular the special characters of the expression include:. \\+*? [^]$ () {}=!<>|:.
preg_replace--perform search and replace of regular expressions
Mixed preg_replace (mixed pattern, mixed replacement, mixed Subject[,intlimit]
Preg_replace_callback--The search
and replace
Mixed preg_replace_callback (mixed pattern, callback callback, using a callback function to perform regular expressions) Mixedsubject[,intlimit])
preg_split--to split the string with a regular expression
array preg_split (string pattern, string subject [, int limit [, int flags]])
Common regular Expressions:
Mobile:/^? 0?1\d{10}$/
/^[\w-]+[\w-.]? @[\w-]+\. {1} [A-za-z] {2,5}$/
Password (in security level):
/^ (\d+[a-za-z]\w*|[ a-za-z]+\d\w*) $/
Password (high security level):
/^ (\d+[a-za-z~!@#$%^& () {}][\w~!@#$%^& () {}]*|[ a-za-z~! @#$%^& () {}]+\d[\w~!@#$%^& () {}]*) $/

What is the difference between the use of 7.preg_replace () and the Str_ireplace () two functions? How is the Preg_split () and split () functions used?

preg_replace-perform search and replace of regular expressions
Ignore case version str_replace-substring substitution for str_ireplace-str_replace ()
Preg_split-splitting strings with regular expressions
Split-using regular expressions to split a string into an array

8. What are the main functions that get the current timestamp? Use PHP to print out today's time, in the format 2010-12-10 22:21:21? The time format for printing the previous day in PHP is 2010-12-10 22:21:21? How do I turn 2010-12-25 10:30:25 into a unix timestamp?

Echodate ("Y-m-dh:i:s", Strtotime (' -1,days '));d ate (' y-m-dh:i:s ', Time ()), $unix _time = Strtotime ("2009-9-2 10:30:25") ;//become UNIX timestamp echodate ("Y-m-dh:i:s", $unix _time);//format to normal time format

9. When using get value in the URL, if the Chinese garbled, which function should be used to encode Chinese?

In order to prevent script attacks (such as user input <script>alert (111);</script>), when the user submits data on the website form, the PHP side receives the data
, what should be done?
Use UrlEncode () to encode Chinese, using UrlDecode () to decode.
Use Htmlspecialchars ($_post[' title ') to filter the table only son parameter to avoid scripting attacks.

10. What is the difference between mysql_fetch_row () and Mysql_fetch_assoc () and mysql_fetch_array?

The first is to return one row in the result set as an indexed array, and the second is to return
Associative array, and the third can return either an indexed array or an associative array, depending on its second argument Mysql_both mysql_num MYSQL_ASSOC defaults to Mysql_both

$sql = "Select*fromtable1"; $result =mysql_query ($sql); Mysql_fetch_array ($result, mysql_num);

11. Please state the current learning function of return as a resource?

Answer: fopen (open file)
Imagecreatefromjpeg (PNG gif)-from JPEG
File a new image
imagecreatetruecolor-Create a new True color
imagecopymerge-Copy and merge images in a
imagecopyresized-copy part of the image and adjust
Whole size
mysql_connect-open one to MySQL MySQL MySQL
Connection to the server
Mysql_query (); only if this executes the select succeeds, returns the resource, and the failure returns FALSE

12. What details do I need to note about file uploads? How do I save the file to the specified directory? How to avoid uploading files duplicate name problem?

1. First to open the file upload in the php.ini;
2. There is a maximum allowed upload in php.ini, the default is 2MB. Necessary
can be changed;
3. Upload the form must remember to write in the form label enctype= "Multipart/form-data";
4. The method of submission must be post;
5. Set type= "file" form control;
6. Note the size of the uploaded file max_file_size, whether the file type meet the requirements, the upload after the storage path exists. You can get the file suffix by uploading the filename, and then Rename the file using the timestamp + file suffix, which avoids the duplicate name. You can set the file to save the directory, with the file name pieced together to form a file path, using Move_uploaded_file (), you can complete the file saved to the specified directory.

$_files is a few-dimensional array? What are the index subscripts for the first and second dimensions? What do I need to pay attention to when uploading files in bulk?

A two-dimensional array. The first dimension is the name of the upload control, and the two-dimensional subscript is name/type/tmp_name/size/error.

What are the main functions of the 14.header () function? What do you pay attention to during use?


Header () sends HTTP header information-header ("content-type:text/html; Charset=utf-8 ");-------------------//The current page output is HTML, encoded in UTF-8 format-<meta http-equiv=" Content-type "content=" text/ html Charset=utf-8 "/>-header (" content-type:image/png gif jpeg ");----------------------------------// The current page output format is the picture-header ("refresh:5;url=http://www.1004javag.com/five/string.ph P"),--//page 5 seconds to jump to the new URL-header (" Location:http://1004javag.com/five/string.php ");----------//Page redirection

15. If you use the header () function when downloading files?

Answer: Header ("Content-type:application/octet-stream;charset=utf-8"); Here add Utf-8 and
What is the difference between the definitions above? 、??

Header ("Accept-ranges:bytes"), Header ("Accept-length:". FileSize ($filedir. $filename)); Header (" Content-disposition:attachment; Filename= ". $filedir. $filename);

16. What is Ajax? What is the principle of Ajax? What is the core technology of Ajax? What are the pros and cons of Ajax?

Ajax is the abbreviation for asynchronous JavaScript JavaScript JavaScript and XML, and is a combination of JavaScript, XML, CSS, DOM and many other technologies. ' $ ' is an alias for Jquer Jquer jquer jQuery y-y y.
The user's request in the page communicates asynchronously with the server through the Ajax engine, and the server returns the result of the request to the Ajax engine.
Finally, the Ajax engine decides to display the returned data to the specified location on the page. Ajax eventually implements the content that can be loaded on one page at a specified location, and all the output from another page.
This enables a static page to obtain the return data information in the database. So Ajax technology implements a static Web page without refreshing the entire
page, and the server communicates with the
Reduces user latency while reducing network traffic and enhances
The friendliness of the customer experience.
The advantages of Ajax are:
1. Reduce the burden on the server, a part of the previous server-borne work
To client execution, using the client's idle resources for processing;
2. Update the page in the case of only partial refresh, increase the page reaction speed,
Make the user experience more friendly.
The disadvantage of Ajax is not conducive to SEO promotion optimization, because the search engine can not directly access the content of the AJAX request.
The core technology of Ajax is XMLHttpRequest, which is a JavaScript
An object.

What is 17.jquery? What is jquery's approach to simplifying Ajax?

JQuery is a framework for Javascript.
$.get (), $.post (), $.ajax (). $ is an alias for the JQuery object.
The code is as follows:

$.post (the URL address of the asynchronous access, {' parameter name ': Parameter value}, function (msg) {$ ("#result"). HTML (msg);}); $.get (the URL address of the asynchronous access, {' parameter name ': Parameter value}, function (msg) {$ ("#result"). HTML (msg);}); $.ajax ({type: "Post", Url:loadurl,cache:false,data: "Parameter name =" + parameter value, Success:function (msg) {$ ("#result"). HTML (msg);}});

18. What is session control?

simply put, session control is the mechanism for tracking and identifying user information. The idea of Session control is to be able to track a variable in the site, through which the system can identify the corresponding user information, according to the user information can know the user rights, so as to show the user appropriate permissions to the page content. At present, the most important method of conversation tracing is cookie,session.

19. Basic steps for session tracking

1). Accessing the Session object associated with the current request

2) . Find information about a session

3). Storing session information

4). Discard session Data

20. What are the precautions for using cookies?

1) Setcookie () can not have any page output before, that is, space, empty line also can not;
2) after Setcookie (), call $_cookie[' CookieName ' on the current page will not have output, you must refresh or go to the next page to see the COOKIE value;
3) different browsers for cookie processing, the client can disable cookies, the browser can also be idle cookie number, a browser can create a maximum of 300 cookies, and each can not exceed 4kb, the total number of cookies that can be set per Web site cannot exceed 20.
4) The cookie is stored on the client and the user has disabled the cookie, then the Setcookie will not work. So you cannot rely too much on cookies.

21. What is the current user to use when using the session, which distinguishes it from other users?

SessionID, the current session_id can be obtained through the session_id () function.

What are the steps to use the session and cookie respectively? What is the life cycle of sesssion and cookies? What is the difference between a session and a cookie?

1. The cookie is stored on the client machine, and the Cookie,cookie value that is not set to expire is saved in the machine's memory, and the cookie disappears automatically as soon as the browser is closed. If a cookie is set to expire, the browser saves the cookie as a text file to the hard disk, and the cookie value remains in effect when the browser is opened again.
2. Session is to save the information that the user needs to store on the server side. The session information for each user is stored on the server side like a key-value pair, where the key is SessionID, and the value is the user needs to store the information. The server is the user who distinguishes the stored session information by SessionID.
The biggest difference between the two is that the session is stored on the server side, and the cookie is on the client. Session security is higher and cookie security is weak.
3. The session has a very important part in web development. It can log the user's correct log-in information to the server's memory, when the user in this role to access the site's management background, no need to log in again to get identity confirmation. Users who do not log in correctly do not allocate session space, and cannot see the page content even if the access address is entered in the admin background. the user's access to the page is determined by the session.

Steps to use the session:

1. Start session: Use the Session_Start () function to start.
2. Register session: Add elements directly to the $_session array.
3. Use session: To determine if the session is empty or if it is already registered, if it already exists, then it can be used as a normal array.
4. Delete session:
1. You can use unset to delete a single session;
2. Use $_session=array () to log off all session changes at once volume;
3. Use the Session_destroy () function to completely destroy the session.

How is a cookie used?

1. Record part of user access information
2. Passing variables between pages
3. Store the Internet page you are viewing in the Cookies Temp folder to improve your browsing speed later.

Create Cookie:setcookie (stringcookiename,stringvalue,int expire);
Read Cookie: Reads the value of the browser-side cookie by using the Super Global array $_cookie.
Delete cookies: There are two ways
1. Manual removal Method:
Right click on the browser properties, you can see the deletion of cookies, the operation can be done to delete all the cookie files.
2.setcookie () Method:
This is the same as setting the cookie, but at this point the value of the cookie is set to NULL, valid for 0 or less than the current timestamp.

23. What do I need to do before I set up or read the session?

Can be opened directly in the php.ini session.auto_start=1 or in the head of the page session_start ();
Open Session,session_start () front cannot have any output, including empty line.

24. In actual development, where is the session used?

Session is used to store user login information and to pass values across pages.
1) commonly used in the user login success, the user login information assigned to the session;
2) used in the verification code image generation, when the random code generated after the assigned value to the session.

25. How many types of logoff session sessions are there?

Unset () $_session=array (); Session_destroy ();
Related Article

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.

Tags Index: