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:
<? PHP
Ob_start ();
Session_start ();
Echo "<PRE> ";
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 "</PRE> ";
?>
Then in PHP. set in ini: Export de_path = "C:/PHP" and debug. PHP is placed in this folder, and you can include this file in each web page 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:
<? PHP
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:
<? PHP
Session_start ();
$ _ Session ["name"] = "value ";
?>
You can cancel the session as follows:
PHP code:
<? PHP
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:
Anything that appears "........ headers already sent .......... ", that is, 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 <? PHP ob_start ();?>
... 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:
<? PHP
$ 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:
<? PHP
Echo "<PRE> ";
Echo $ _ Get ["name"];
Echo "</PRE> ";
?>
The correct method is:
PHP code:
<? PHP
$ 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:
<? PHP
$ 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 to avoid errors due to misuse of keywords. Of course, I do not recommend you to 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:
<? PHP
$ STR = "Echo "interpreted:". $ Str. "<br> processed :";
Echo htmlentities (nl2br ($ Str ));
?>
8: how to obtain variable values outside the Function
PHP code:
<? PHP
$ 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:
<? PHP
$ Arr = get_defined_functions ();
Function PHP (){
}
Echo "<PRE> ";
Echo "This shows all functions supported by the system, and custom functions PHP/N ";
Print_r ($ ARR );
Echo "</PRE> ";
?>
10: how to compare the differences between two dates for a few days
PHP code:
<? PHP
$ Date_1 = "2003-7-15"; // It can also be: $ date_1 = "2003-7-15 23:29:14 ";
$ Date_2 = "1982-10-1 ";
$ D1 = strtotime ($ date_1 );
$ D2 = strtotime ($ date_2 );
$ 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:
<? PHP
Include "auto_prepend_file.php ";
... // Here is your program
Include "auto_append_file.php ";
?>
13: How to Use PHP to upload files
PHP code:
<HTML> <Title> Upload File Form </title> <Body>
<Form enctype = "multipart/form-Data" Action = "" method = "Post">
Select a file: <br>
<Input name = "upload_file" type = "file"> <br>
<Input type = "Submit" value = "Upload File">
</Form>
</Body>
</Html>
<?
$ 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 "<p> you uploaded the file :";
Echo $ _ FILES ['upload _ file'] ['name'];
Echo "<br> ";
// 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 "<br> ";
Echo "Upload file size :";
Echo $ _ FILES ['upload _ file'] ['SIZE'];
// Size of the uploaded file, in bytes.
Echo "<br> ";
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 "<br> ";
$ 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:
<? PHP
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.
[Review]: the previous section introduced 15 questions, including "debugging programs", "How to Use sessions", and "standardized SQL statements" (PhP experts lead the way-problem summary and answers [1]). This episode continues to provide answers to 16 frequently asked questions.
16: I want to modifyMySQLUser, 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:
<? PHP
// Output is available only when input through the super connection
Echo $ _ server ['HTTP _ referer'];
?>
18: data placementDatabaseAnd display on the page.
Warehouse receiving
$ STR = addslashes ($ Str );
$ SQL = "insert into 'tab' ('content') values ('$ STR ')";
Warehouse picking
$ STR = stripslashes ($ Str );
Display time
$ STR = htmlspecialchars (nl2br ($ Str ));
<? PHP
// $ Content comes from the database
$ Content = nl2br (htmlspecialchars ($ content ));
$ Content = str_replace ("", "& nbsp;", $ content );
$ Content = str_replace ("/N", "<br>/N", $ content );
?>
19: how to read the current address bar Information
PHP code:
<? PHP
$ 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:
<? PHP 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 Address
Imagepng ($ IMG );
Imagecreatefrompng ($ IMG );
Imagedestroy ($ IMG );
?>
<? 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: howDatabaseRead all records 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 connectMySQLDatabase
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
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
27: Why do single quotes and double quotes become on the acceptance page (/'/")
Solution:
Method 1: Set magic_quotes_gpc = off in PHP. ini.
Method 2: $ STR = stripcslashes ($ Str)
28: how to keep the program running instead of stopping it in over 30 seconds
Set_time_limit (60) // The maximum running time is one minute.
Set_time_limit (0) // run until the program ends or stops manually.
29: calculates the number of online users.
Example 1: Use text
PHP code:
30: What is a template and how to use it
I use the phplib template.
The following are the usage of several functions.
$ T-> set_file ("customizable", "template file. TPL ");
$ T-> set_block ("defined in set_file", "<! -- From template --> "," customized ");
$ T-> parse ("defined in set_block", "<! -- From template --> ", true );
$ T-> parse ("output result casually", "defined in set_file ");
Set the cycle format:
<! -- (More than one space) Begin $ handle (more than one space) -->
How to generate a static webpage from a template
PHP code:
<? PHP
// Use the phplib template here
............
............
$ TPL-> parse ("output", "html ");
$ Output = $ TPL-> get ("output"); // $ output indicates the content of the entire webpage.
Function wfile ($ file, $ content, $ mode = 'W '){
$ Oldmask = umask (0 );
$ Fp = fopen ($ file, $ mode );
If (! $ FP) return false;
Fwrite ($ FP, $ content );
Fclose ($ FP );
Umask ($ oldmask );
Return true;
}
// Write to file
Wfile ($ file, $ output );
Header ("Location: $ file"); // redirect to the generated webpage
}
?>
Phplib smarty
31: How to Use PHP to explain characters
For example, input 2 + 2*(1 + 2) and automatic output 8 can use the eval function.
PHP code:
<Form method = post action = "">
<Input type = "text" name = "str"> <input type = "Submit">
</Form>
<? PHP
$ STR = $ _ post ['str'];
Eval ("/$ o = $ STR ;");
Echo "$ o ";
?>
At this point, the PHP questions and answers have been introduced to you, and I hope to help you.
<? PHP
// First, you must have the permission to read and write files.
// This program can be run directly. The first error will be reported later
$ Online_log = "count. dat"; // the object that stores the number of people,
$ Timeout = 30; // The author is not moved within 30 seconds.
$ Entries = file ($ online_log );
$ Temp = array ();
For ($ I = 0; $ I <count ($ entries); $ I ++ ){
$ Entry = explode (",", trim ($ entries [$ I]);
If ($ entry [0]! = Getenv ('remote _ ADDR ') & ($ entry [1]> time ()))
{
Array_push ($ temp, $ entry [0]. ",". $ entry [1]. "/N"); // retrieves the information of other viewers, removes the timeout, and saves the information to $ temp
}
}
Array_push ($ temp, getenv ('remote _ ADDR '). ",". (Time () + ($ timeout). "/N ");
// Update the viewer's time
$ Users_online = count ($ temp); // calculate the number of online users
$ Entries = implode ("", $ temp );
// Write a file
$ Fp = fopen ($ online_log, "W ");
Flock ($ FP, lock_ex); // flock () cannot work normally in NFS or some other network file systems
Fputs ($ FP, $ entries );
Flock ($ FP, lock_un );
Fclose ($ FP );
Echo "currently". $ users_online. "online users ";
?>
22: how to obtain the user's real IP Address
PHP code: