Php FAQs _ PHP Tutorial

Source: Internet
Author: User
Tags parse error
Summary of some common Php problems. Summary of some common Php problems 1: Why can't I get the variable I post the data name to another webpage on one webpage? why can't I get any value when I output $ name? In versions later than PHP4.2, reg Php has some common problems. Conclusion 1: Why can't I get the variable?

Why can't I get any value when I output $ name when I POST data name to another webpage?

In versions later than PHP4.2, the default value of register_global is off.
To get the variables submitted from another page:

Method 1: Find register_global in PHP. ini and set it to on.
Method 2: Put the extract ($ _ POST); extract ($ _ GET) at the beginning of the receiving page. (note that extract ($ _ SESSION) you must have Session_Start ()).
Method 3: Read the variable $ a =$ _ GET ["a"]; $ B =$ _ POST ["B"] one by one. Although this method is troublesome, it is safer.

2: debug your program

You must know the value of a variable at runtime. In this case, create a debug. php file with the following content:

PHP code :--------------------------------------------------------------------------------

Ob_Start ();
Session_Start ();
Echo"
";

Echo "the _ GET variables obtained on this page include :";
Print_R ($ _ GET );

Echo "the _ POST variables obtained on this page include :";
Print_R ($ _ POST );

Echo "the _ COOKIE variables on this page are :";
Print_R ($ _ COOKIE );

Echo "the _ SESSION variables obtained on this page include :";
Print_R ($ _ SESSION );
Echo"
";
?>

--------------------------------------------------------------------------------

In php. ini, set: include_path = "c:/php" and put debug. php in this folder,
In the future, you can include this file in each webpage to view the variable name and value.

3: how to use session

The session_start () function must be called before session-related operations ();

It is very easy to pay for the session, such:


PHP code :--------------------------------------------------------------------------------

Session_start ();
$ Name = "this is a Session example ";
Session_Register ("Name"); // do not write it as Session_Register ("$ Name ");
Echo $ _ SESSION ["Name"];
// After $ _ SESSION ["Name"] is "this is a Session example"
?>

--------------------------------------------------------------------------------



After php4.2, you can directly pay the value for the session:

PHP code :--------------------------------------------------------------------------------

Session_Start ();
$ _ SESSION ["name"] = "value ";
?>

--------------------------------------------------------------------------------

You can cancel the session as follows:

PHP code :--------------------------------------------------------------------------------

Session_start ();
Session_unset ();
Session_destroy ();
?>

--------------------------------------------------------------------------------


There is a BUG in canceling a session variable above php4.2.



Note:

1: no output is allowed before Session_Start () is called. for example, the following is incorrect.
========================================================== =
1 line
2 rows 3 rows Session_Start (); // output already exists in the first row
4 rows .....
5 rows?>
========================================================== =


Tip 1:

If "... headers already sent..." appears, it means to output information to the browser before Session_Start.
It is normal to remove the output (this error will also occur in the COOKIE, the same reason for the error)

Tip 2:

If your Session_Start () is placed in a loop statement and it is difficult to determine where to output information to the browser, you can use the following method:
1 line
... Here is your program ......



2: What is the error?

Warning: session_start (): open (/tmp \ sess_7d1_aa36b4c5ec13a5c1649cc2da23f, O_RDWR) failed :....
Because you have not specified the path for storing session files.

Solution:
(1) create a folder tmp on drive C
(2) open php. ini, find session. save_path, and change it to session. save_path = "c:/tmp"



4: Why do I get only the first half when I send a variable to another web page, and all the variables starting with a space are lost?


PHP code :--------------------------------------------------------------------------------

$ Var = "hello php"; // change it to $ Var = "hello php"; what are the results?
$ Post = "receive. php? Name = ". $ Var;
Header ("location: $ post ");
?>

--------------------------------------------------------------------------------

Content of receive. php:

PHP code :--------------------------------------------------------------------------------

Echo"
";
Echo $_GET["Name"];
Echo "
";
?>

--------------------------------------------------------------------------------


The correct method is:

PHP code :--------------------------------------------------------------------------------

$ Var = "hello php ";
$ Post = "receive. php? Name = ". urlencode ($ Var );
Header ("location: $ post ");
?>

--------------------------------------------------------------------------------


You do not need to use Urldecode () on the receiving page. the variable is automatically encoded.


5: how to intercept a specified length of Chinese characters without "?> "End, the excess part is replaced "..."


In general, the variables to be intercepted come from Mysql. First, make sure that the field length is long enough. generally, it is char (200) and 100 Chinese characters can be kept, including punctuation.

PHP code :--------------------------------------------------------------------------------

$ Str = "this character is long, ^ _ ^ ";
$ Short_Str = showShort ($ str, 4); // extract the first four Chinese characters and the result is: this character...
Echo "$ Short_Str ";
Function csubstr ($ str, $ start, $ len)
{
$ Strlen = strlen ($ str );
$ Clen = 0;
For ($ I = 0; $ I <$ strlen; $ I ++, $ clen ++)
{
If ($ clen >=$ start + $ len)
Break;
If (ord (substr ($ str, $ I, 1)> 0xa0)
{
If ($ clen> = $ start)
$ Tmpstr. = substr ($ str, $ I, 2 );
$ I ++;
}
Else
{
If ($ clen> = $ start)
$ Tmpstr. = substr ($ str, $ I, 1 );
}
}

Return $ tmpstr;
}
Function showShort ($ str, $ len)
{
$ Tempstr = csubstr ($ str, 0, $ len );
If ($ str <> $ tempstr)
$ Tempstr. = "..."; // you can modify the description here.

Return $ tempstr;
}

--------------------------------------------------------------------------------



6: Standardize your SQL statements


In the table, add "'" before the field so that no error occurs due to misuse of keywords,
Of course, I do not recommend you use keywords.

For example
$ SQL = "INSERT INTO 'xltxlm '('author', 'title', 'id', 'content', 'date') VALUES ('xltxlm ', 'use', 1, 'criterion your SQL string', '2017-07-11 00:00:00 ')"

"'" How to input? On the TAB key.


7: how to make Html/PHP strings not interpreted, but displayed as they are


PHP code :--------------------------------------------------------------------------------

$ Str = "PHP ";
Echo "interpreted:". $ str ."
Processed :";
Echo htmlentities (nl2br ($ str ));
?>

--------------------------------------------------------------------------------



8: how to obtain variable values outside the function


PHP code :--------------------------------------------------------------------------------

$ A = "PHP ";
Foo ();
Function foo ()
{
Global $ a; // delete the result.
Echo "$ ";
}
?>

--------------------------------------------------------------------------------



9: How do I know what functions are supported by the system by default?


PHP code :--------------------------------------------------------------------------------

$ Arr = get_defined_functions ();
Function php (){
}
Echo"
";
Echo "this shows all functions supported by the system, and the custom function php \ n ";
Print_r ($ arr );
Echo"
";
?>
--------------------------------------------------------------------------------


10: How to compare the differences between two dates for a few days


PHP code :--------------------------------------------------------------------------------

$ Date_1 = "2003-7-15"; // You can also: $ Date_1 = "2003-6-25 23:29:14 ";
$ Date_2 = "1982-10-1 ";
$ Date_List_1 = explode ("-", $ Date_1 );
$ Date_List_2 = explode ("-", $ Date_2 );
$ D1 = mktime (0, 0, 0, $ Date_List_1 [1], $ Date_List_1 [2], $ Date_List_1 [0]);
$ D2 = mktime (0, 0, $ Date_List_2 [1], $ Date_List_2 [2], $ Date_List_2 [0]);
$ Days = round ($ d1-$ d2)/3600/24 );
Echo "I have struggled for $ Days ^_^ ";
?>

--------------------------------------------------------------------------------


11: Why does the original program show the full screen Notice: Undefined variable after I upgrade PHP:


This is warning because the variable is undefined.
Open php. ini, find the bottom error_reporting, and change it to error_reporting = E_ALL &~ E_NOTICE

For Parse error errors
Error_reporting (0) cannot be closed.
If you want to disable any error prompt, open php. ini, find display_errors, and set it to display_errors = Off. no error will be prompted in the future.

So what is error_reporting?



12: I want to add a file at the beginning and end of each file, but it is very troublesome to add one file at a time.

1: Open the php. ini file.
Set include_path = "c :"

2: write two files
Auto_prepend_file.php and auto_append_file.php are stored on drive C, and they are automatically attached to the header and tail of each php file.

3: in php. ini, find:
Automatically add files before or after any PHP document.
Auto_prepend_file = auto_prepend_file.php; attached to the header
Auto_append_file = auto_append_file.php;

In the future, each php file will be equivalent

PHP code :--------------------------------------------------------------------------------

Include "auto_prepend_file.php ";

... // Here is your program


Include "auto_append_file.php ";
?>

--------------------------------------------------------------------------------




13: how to use PHP to upload files



PHP code :--------------------------------------------------------------------------------


Upload file Form





$ Upload_file = $ _ FILES ['upload _ file'] ['tmp _ name'];
$ Upload_file_name = $ _ FILES ['upload _ file'] ['name'];

If ($ upload_file ){
$ File_size_max = 1000*1000; // 1 MB limit the maximum file upload capacity (bytes)
$ Store_dir = "d:/"; // storage location of the uploaded file
$ Accept_overwrite = 1; // whether to overwrite the same file
// Check the file size
If ($ upload_file_size> $ file_size_max ){
Echo "Sorry, your file capacity exceeds the limit ";
Exit;
}

// Check the read/write file
If (file_exists ($ store_dir. $ upload_file_name )&&! $ Accept_overwrite ){
Echo "files with the same file name exist ";
Exit;
}

// Copy the file to the specified directory
If (! Move_uploaded_file ($ upload_file, $ store_dir. $ upload_file_name )){
Echo "failed to copy the file ";
Exit;
}

}

Echo"

You uploaded the file :";
Echo $ _ FILES ['upload _ file'] ['name'];
Echo"
";
// The original name of the client machine file.

Echo "the MIME type of the file is :";
Echo $ _ FILES ['upload _ file'] ['type'];
// MIME type of the file, which must be supported by the browser, for example, "image/gif ".
Echo"
";

Echo "Upload file size :";
Echo $ _ FILES ['upload _ file'] ['size'];
// Size of the uploaded file, in bytes.
Echo"
";

Echo "the file is temporarily stored after being uploaded :";
Echo $ _ FILES ['upload _ file'] ['tmp _ name'];
// Temporary file name stored on the server after the file is uploaded.
Echo"
";


$ Erroe = $ _ FILES ['upload _ file'] ['error'];
Switch ($ Erroe ){
Case 0:
Echo "uploaded successfully"; break;
Case 1:
Echo "the uploaded file exceeds the limit of the upload_max_filesize option in php. ini."; break;
Case 2:
Echo "the size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form. "; Break;
Case 3:
Echo "only part of the file is uploaded"; break;
Case 4:
Echo "no file is uploaded"; break;
}
?>

--------------------------------------------------------------------------------



14: how to configure the GD Library


The following is my configuration process
1: Use the doscommand (you can also manually copy all dll files in the dlls folder to the system32 directory) copy c: \ php \ dlls \ *. dll c: \ windows \ system32 \
2: Open php. ini
Set extension_dir = "c:/php/extensions /";
3:
Extension = php_gd2.dll; remove the comma before extension. if php_gd2.dll is not available, the same applies to php_gd.dll. ensure that the file c:/php/extensions/php_gd2.dll exists.
4: run the following program for testing.

PHP code :--------------------------------------------------------------------------------

Ob_end_flush ();
// Note: No information can be output to the browser before this time. Be sure to set auto_prepend_file.
Header ("Content-type: image/png ");
$ Im = @ imagecreate (200,100)
Or die ("images cannot be created ");
$ Background_color = imagecolorallocate ($ im, 0, 0 );
$ Text_color = imagecolorallocate ($ im, 230,140,150 );
Imagestring ($ im, 3, 30, 50, "A Simple Text String", $ text_color );
Imagepng ($ im );
?>

--------------------------------------------------------------------------------



Click here to view the results



15: What is UBB code?


UBB code is a variant of HTML. it is a special TAG used by Ultimate Bulletin Board (a BBS program in foreign countries, which is also used in many places in China.
Even if HTML is disabled, you can use UBBCode? . Maybe you want to use UBBCode more? Rather than HTML, even if the forum allows HTML, it is safer to use less code.

There is an example in the UBB of Q3boy. you can run the test directly.


16: I want to modify the MySQL User and password.

First, we need to declare that, in most cases, modifying MySQL requires the root permission in mysql,
Therefore, you cannot change the password unless you request the administrator.

Method 1
Phpmyadmin is the simplest. modify the user table of the mysql database,
But don't forget to use the PASSWORD function.

Method 2
Use mysqladmin, which is a special case stated above.
Mysqladmin-u root-p password mypasswd
After entering this command, you need to enter the original root password, and then the root password will be changed to mypasswd.
Change the root in the command to your username, and you can change your password.
Of course, if your mysqladmin cannot connect to mysql server, or you cannot execute mysqladmin,
This method is invalid.
In addition, mysqladmin cannot clear the password.

The following methods are used at the mysql prompt and must have the root permission of mysql:
Method 3
Mysql> insert into mysql. user (Host, User, Password)
VALUES ('%', 'Jeffrey ', PASSWORD ('biscuit '));
Mysql> FLUSH PRIVILEGES
Specifically, this is adding a user with the username jeffrey and password biscuit.
I wrote this example in mysql Chinese Reference Manual.
Be sure to use the PASSWORD function, and then use flush privileges.

Method 4
Similar to method Sany, but the REPLACE statement is used.
Mysql> replace into mysql. user (Host, User, Password)
VALUES ('%', 'Jeffrey ', PASSWORD ('biscuit '));
Mysql> FLUSH PRIVILEGES

Method 5
Use the set password statement,
Mysql> set password for jeffrey @ "%" = PASSWORD ('biscuit ');
You must also use the PASSWORD () function,
However, you do not need to use flush privileges.

Method 6
Use the GRANT... identified by statement
Mysql> grant usage on *. * TO jeffrey @ "%" identified by 'biscuit ';
Here, the PASSWORD () function is unnecessary and does not need to be flush privileges.

Note: PASSWORD () [not] implements PASSWORD encryption in the same way as Unix PASSWORD encryption.


17: I want to know which website he connected to this page



PHP code :--------------------------------------------------------------------------------

// Output is available only when input through the super connection
Echo $ _ SERVER ['http _ referer'];
?>

--------------------------------------------------------------------------------



18: What do you need to pay attention to when data is put into the database and retrieved?

Warehouse receiving
$ Str = addslashes ($ str );
$ SQL = "insert into 'tab' ('content') values ('$ str ')";
Warehouse picking
$ Str = stripslashes ($ str );
Display time
$ Str = htmlspecialchars (nl2br ($ str ));





19: how to read the current address bar information



PHP code :--------------------------------------------------------------------------------

$ S = "http: // {$ _ SERVER ['http _ host']}: {$ _ SERVER ["SERVER_PORT"]} {$ _ SERVER ['script _ name']} ";
$ Se = '';
Foreach ($ _ GET as $ key => $ value ){
$ Se. = $ key. "=". $ value ."&";
}
$ Se = Preg_Replace ("/(. *) & $/", "$1", $ se );
$ Se? $ Se = "? ". $ Se :"";
Echo $ s ."? $ Se ";
?>
--------------------------------------------------------------------------------




20: I clicked the back button. Why didn't I enter anything?

This is because you have used the session.
Solution:

PHP code :--------------------------------------------------------------------------------

Session_cache_limiter ('private, must-revalidate ');
Session_start ();
...........
..........
?>

--------------------------------------------------------------------------------



21: how to display IP addresses in images


PHP code :--------------------------------------------------------------------------------

Header ("Content-type: image/png ");
$ Img = ImageCreate (180,50 );
$ Ip = $ _ SERVER ['remote _ ADDR '];
ImageColorTransparent ($ img, $ bgcolor );
$ BgColor = ImageColorAllocate ($ img, 0x2c, 0x6D, 0xAF); // background color
$ Shadow = ImageColorAllocate ($ img, 250,0, 0); // shadow color
$ TextColor = ImageColorAllocate ($ img, oxff); // font color
ImageTTFText ($ img, 10, 0, 78, 30, $ shadow, "d:/windows/fonts/Tahoma. ttf", $ ip); // display the background
ImageTTFText ($ img, 10, 0, 25, 28, $ textColor, "d:/windows/fonts/Tahoma. ttf", "your ip is". $ ip); // Display IP
ImagePng ($ img );
Imagecreatefrompng ($ img );
ImageDestroy ($ img );
?>

--------------------------------------------------------------------------------



22: how to obtain the user's real IP address


PHP code :--------------------------------------------------------------------------------

Function iptype1 (){
If (getenv ("HTTP_CLIENT_IP ")){
Return getenv ("HTTP_CLIENT_IP ");
}
Else {
Return "none ";
}
}
Function iptype2 (){
If (getenv ("HTTP_X_FORWARDED_FOR ")){
Return getenv ("HTTP_X_FORWARDED_FOR ");
}
Else {
Return "none ";
}
}
Function iptype3 (){
If (getenv ("REMOTE_ADDR ")){
Return getenv ("REMOTE_ADDR ");
}
Else {
Return "none ";
}
}
Function ip (){
$ Ip1 = iptype1 ();
$ Ip2 = iptype2 ();
$ Ip3 = iptype3 ();
If (isset ($ ip1) & $ ip1! = "None" & $ ip1! = "Unknown "){
Return $ ip1;
}
Elseif (isset ($ ip2) & $ ip2! = "None" & $ ip2! = "Unknown "){
Return $ ip2;
}
Elseif (isset ($ ip3) & $ ip3! = "None" & $ ip3! = "Unknown "){
Return $ ip3;
}
Else {
Return "none ";
}
}

Echo ip ();
?>
--------------------------------------------------------------------------------



23: how to read all records from the database within three days

First, the table requires a DATETIME field to record the time,
Format: '2017-7-15 16:50:00'

SELECT * FROM 'xltxlm 'WHERE TO_DAYS (NOW ()-TO_DAYS ('date') <= 3;


24: how to remotely connect to the Mysql database


In the added mysql table, there is a host field, changed to "%", or specify the IP address that allows connection, so that you can call it remotely.

$ Link = mysql_connect ("192.168.1.80: 3306", "root ","");


25: how to use regular expressions

Click here
Special characters in regular expressions


26: After Apache is used, the homepage is garbled


Method 1:
Adddefadefacharset ISO-8859-1 changed to adddefadefacharset off

Method 2:
Adddefacharcharset GB2312
========================================================== ======================
Tip:
When you paste code, GB2312 will be interpreted ??????

This won't happen.

When I post the data name from one web page to another, why can't I get any value when I output $ name? In versions later than PHP4.2, reg...

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.