PHP Rookie Anomaly Set

Source: Internet
Author: User
Tags flock parse error
PHP Beginner Error Set


Source: http://bbs.php100.com/read.php?tid-150.html

Do development please turn on all error prompts: error_reporting = E_all | E_strict
Mask error prompt equals deceiving. The
code writes a specification with half the error.

1: Why I can't get a variable

I post data to another page on one page name, why can't I get any value when I output $name?

Register_global defaults to OFF in PHP4.2 versions
if you want to get a variable submitted from another page:

Method One: Find Register_global in php.ini and set it to on.
Method Two: Put this extract ($_post) in front of the receiving page, extract ($_get);(Note Extract ($_session) must have Session_Start ()).
//extract (Array $var _array [, int $extract _type [, String $prefix])

//This function is used to import variables from the array into the current symbol table. Accept the associative array var_array as the argument and the key//name as the variable name, and the value as the value of the variable. For each key/value pair, the variables are created in the current symbol table and are affected by the//extract_type and prefix parameters.
//import_request_variables (String $types [, String $prefix]) Hyper-Global, $_ $* Vulnerability

Method Three: One read variable $a=$_get["a"]; $b = $_post["B"] etc., this method is troublesome, but relatively safe.

2: Debugging your program

must know the value of a variable at run time. I did this by creating a file debug.php with the following contents:

PHP Code:--------------------------------------------

Copy code

??? Ob_start ();
??? Session_Start ();
??? Echo "

";
??? Echo "This page has the _get variable:";
??? Print_r ($_get);
??? Echo "This page has the _post variable:";
??? Print_r ($_post);
??? Echo "This page has the _cookie variable:";
??? Print_r ($_cookie);
??? Echo "This page has the _session variable:";
??? Print_r ($_session);
??? Echo "
";



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

Then set in php.ini: include_path = "c:/php" and place debug.php in this folder,
In the future, you can include this file in each page to see the variable names and values you get.

3: How to use Session

The function session_start () must be called before the session.

It is simple to pay for the session, such as:


PHP Code:--------------------------------------------

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

PHP Code:--------------------------------------------

[PHP]
Session_Start ();
$_session["Name"]= "value";
[/php]

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

The cancellation session can be done like this:

PHP Code:--------------------------------------------

[PHP]
Session_Start ();
Session_unset ();
Session_destroy ();
[/php]

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


Cancel a Session variable above php4.2 there is a bug.



Attention:

1: cannot have any output before calling Session_Start (). For example, the following is an error.
==========================================
1 rows
2 lines [PHP]
3 lines session_start ();//before the first line already has output
4 lines .....
5 rows [/php]
==========================================


Tip 1:

Anything that appears ".... Headers already sent ..." is the output of information to the browser before Session_Start ().
Remove the output is normal, (the cookie will also appear this error, the same reason)

Tip 2:

If your session_start () is placed in a looping statement and it is difficult to determine where to export the information to the browser before, you can use the following method:
1 lines [PHP] Ob_start (); [/php]
........ Here is your program ...



2: What is wrong with this

Warning:session_start (): Open (/tmpsess_7d190aa36b4c5ec13a5c1649cc2da23f, O_RDWR) failed: ....
Because you did not specify a path to store the session file.

Workaround:
(1) Set up folder TMP on C disk
(2) Open php.ini, find Session.save_path, change to Session.save_path= "C:/tmp"



4: Why do I transfer a variable to another page, only the first half of it, and all the ones that start with a space are lost


PHP Code:--------------------------------------------

[PHP]
$Var = "Hello php";//modified to $var= "????? Hello php "; try to get what results
$post = "receive.php?" Name= ". $Var;
Header ("Location: $post");
[/php]

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

Content of receive.php:

PHP Code:--------------------------------------------

[PHP]
Echo "
";
Echo??? $_get["Name"];
Echo "
";
[/php]

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


The correct method is:

PHP Code:--------------------------------------------

[PHP]
$Var = "Hello php";
$post = "receive.php?" Name= ". UrlEncode ($Var);
Header ("Location: $post");
[/php]

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


In the Receive page you do not need to use UrlDecode (), the variable is automatically encoded.


5: How to intercept the specified length of Chinese characters without appearing at the end of "[/php]", Beyond the section with "..." instead


In general, the variables to be intercepted from MySQL, first of all to ensure that the field length is long enough, usually char (200), you can maintain 100 characters, including punctuation.

PHP Code:--------------------------------------------

[PHP]
$str = "This character is very long, ^_^";
$Short _str=showshort ($STR, 4);//intercept the first 4 characters, 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. = "..."; To what end, modify here can be.

return $tempstr;
}

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



6: Standardize your SQL statements


In the table, precede the field with "'" so that there is no error due to misuse of the keyword,
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 s Tring ', ' 2003-07-11 00:00:00 ') "

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


7: How to make html/php format strings not interpreted, but displayed as-is


PHP Code:--------------------------------------------

[PHP]
$str = "

Php

";
Echo "was explained:". $str. "
After treatment: ";
Echo??? Htmlentities (NL2BR ($STR));
[/php]

The NL2BR () function inserts an HTML newline character before each new line (\ n) in the string (
)。
Htmlentities (String,quotestyle,character-set)
????

Quotestyle is optional. Specifies how to encode single and double quotation marks.

??? Ent_compat-Default. Encodes only double quotes.
??? Ent_quotes-encodes double and single quotation marks.
??? Ent_noquotes-do not encode any quotation marks.

Character-set

Iso-8859-1-Default. Western europe.
Iso-8859-15-Western Europe (added Euro symbol and French, Finnish alphabet).
UTF-8-ASCII-compatible multi-byte 8-bit Unicode
Cp866-dos dedicated Cyrillic Character Set
Cp1251-windows dedicated Cyrillic Character Set
Cp1252-windows Special Western European character set
Koi8-r-Russian
GB2312-Simplified Chinese, national standard character set
BIG5-Traditional Chinese
--------------------------------------------



8: How to get the value of the variable outside the function in the function


PHP Code:--------------------------------------------

[PHP]
$a = "PHP";
Foo ();
Function foo ()
{
? Global $a;//delete here to see what the results
? Echo "$a";
}
[/php]

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



9: How do I know what functions the system supports by default


PHP Code:--------------------------------------------

[PHP]
$arr = Get_defined_functions ();
Function php () {
}
Echo??? "
";
Echo??? "This shows all the functions supported by the system, and the custom function PHPN";
Print_r ($arr);
Echo??? "
";
[/php]
--------------------------------------------


10: How to compare two dates for a few days


PHP Code:--------------------------------------------

[PHP]
$Date _1= "2003-7-15";//can also be: $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);
$d 1=mktime (0,0,0, $Date _list_1[1], $Date _list_1[2], $Date _list_1[0]);
$d 2=mktime (0,0,0, $Date _list_2[1], $Date _list_2[2], $Date _list_2[0]);
$Days =round (($d 1-$d 2)/3600/24);
Echo??? "I have struggled $Days days ^_^";
[/php]

(Strtotime ($Date _1)-Strtotime ($Date _2))/3600/24
--------------------------------------------


11: Why did I upgrade PHP, the original program appears full screen notice:undefined variable:


This is the warning, because the variable is undefined.
Open PHP.ini, find the bottom error_reporting, modify to Error_reporting = E_all & ~e_notice

For parse Error Error
Error_reporting (0) cannot be closed.
If you want to turn off any error prompts, open php.ini, locate display_errors, set to Display_errors = off. No future errors will be prompted.

Then what is error_reporting?



12: I want to add a file to the top of each file and the last. But one adds a lot of trouble

1: Open php.ini file
Set include_path= "C:"

2: Write two files
Auto_prepend_file.php and auto_append_file.php are saved in the C drive and they will automatically be attached to the head and tail of each PHP file.

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

After you each PHP file is equivalent to

PHP Code:--------------------------------------------

[PHP]
Include "auto_prepend_file.php";

...//This is your program.


Include "auto_append_file.php";
[/php]

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




13: How to upload files using PHP



PHP Code:--------------------------------------------
[PHP]

<title>Uploading a file form</title>





$upload _file=$_files[' upload_file ' [' tmp_name '];
$upload _file_name=$_files[' upload_file ' [' name '];

if ($upload _file) {
$file _size_max = 1000*1000;//1M limit file upload maximum capacity (bytes)
$store _dir = "d:/";//storage location of uploaded files
$accept _overwrite = 1;//allows overwriting of the same file
Check File size
if ($upload _file_size > $file _size_max) {
echo "Sorry, your file size is greater than the provision";
Exit
}

Check read and write files
if (file_exists ($store _dir. $upload _file_name) && $accept _overwrite) {
Echo??? "Files with the same file name exist";
Exit
}

Copy files to the specified directory
if (!move_uploaded_file ($upload _file, $store _dir. $upload _file_name)) {
echo "Failed to copy 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 '];
The MIME type of the file requires the browser to provide support for that information, such as "Image/gif".
echo "
";

Echo??? "Upload file size:";
echo $_files[' upload_file ' [' Size '];
The size of the uploaded file, in bytes.
echo "
";

Echo??? "The file is temporarily stored as:" After uploading;
echo $_files[' upload_file ' [' tmp_name '];
Temporary file names stored on the server after the files have been uploaded.
echo "
";


$Erroe =$_files[' upload_file ' [' Error '];
Switch ($Erroe) {
??????? Case 0:
??????????? Echo??? "Upload success"; Break
??????? Case 1:
??????????? Echo??? "The uploaded file exceeded the value of the Upload_max_filesize option limit 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??? "Files are only partially uploaded";
??????? Case 4:
??????????? Echo??? "No files were uploaded";
}
[/php]

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



14: How to configure the GD library


Here's my configuration process
1: Use DOS command (can also manually, copy all DLL files in DLLs folder to system32 directory) copy C:phpdlls*.dll c:windowssystem32
2: Open php.ini
Set extension_dir = "c:/php/extensions/";
3:
Extension=php_gd2.dll, remove the comma in front of the extension, and if there is no php_gd2.dll,php_gd.dll, ensure that the file does exist C:/php/extensions/php_gd2.dll
4: Run the following program to test

PHP Code:--------------------------------------------

[PHP]
Ob_end_flush ();
Note that you cannot output any information to the browser before, and be aware that Auto_prepend_file is set.
Header ("Content-type:image/png");
$im = @imagecreate (200, 100)
??? Or Die ("Cannot create image");
$background _color = imagecolorallocate ($im, 0, 0, 0);
$text _color = imagecolorallocate ($im, 230, 140, 150);
Imagestring ($im, 3, 30, 50,? "A Simple Text String", $text _color);
Imagepng ($im);
[/php]

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



Click here to view the results



15: What is the UBB code


UBB code is a variant of HTML, is Ultimate Bulletin Board (a foreign BBS program, there are many places in the country using this program) a special tag.
Even if HTML is forbidden, can you use Ubbcode? To achieve. Maybe you'd rather use Ubbcode? Instead of HTML, even if the forum allows HTML, it is safer to use less code.

Q3boy's UBB has an example, you can run the test directly


16: I want to modify the MySQL user, password

The first thing to declare is that in most cases, MySQL is required to have root privileges in MySQL,
So the general user cannot change the password unless the administrator is requested.

Method One
Using phpMyAdmin, this is the simplest, modify the MySQL library's user table,
But don't forget to use the password function.

Method Two
Using Mysqladmin, this is a special case of the preceding declaration.
Mysqladmin-u root-p Password mypasswd
After entering this command, you need to enter the root's original password, then the root password will be changed to MYPASSWD.
Change the root of the command to your username, and you can change your own password.
Of course if your mysqladmin is not connected to MySQL server, or you have no way to execute mysqladmin,
Then this method is ineffective.
And mysqladmin can't erase the password.

The following methods are used at the MySQL prompt and must have root privileges for MySQL:
Method Three
Mysql> INSERT into Mysql.user (Host,user,password)
VALUES ('% ', ' Jeffrey ', PASSWORD (' biscuit '));
Mysql> FLUSH Privileges
Specifically, this is the addition of a user named Jeffrey, with a password of biscuit.
There is this example in the MySQL Chinese reference manual, so I wrote it out.
Note that you want to use the password function, and then you also use the flush privileges.

Method Four
As with method Three, just use the Replace statement
Mysql> REPLACE into Mysql.user (Host,user,password)
VALUES ('% ', ' Jeffrey ', PASSWORD (' biscuit '));
Mysql> FLUSH Privileges

Method Five
Using 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 Six
Use Grant ... Identified by statement
Mysql> GRANT USAGE on * * to jeffrey@ "%" identified by ' biscuit ';
Here the password () function is unnecessary and does not require the use of flush privileges.

Note: PASSWORD () [NOT] Execute password encryption in the same way that the UNIX password is encrypted.


17: I want to know which website he is connecting to this page



PHP Code:--------------------------------------------

[PHP]
The output must be entered through a super connection
Echo $_server[' Http_referer '];
[/php]

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



18: Data put into the database and taken out to show what needs to be noted on the page

When in storage
$str =addslashes ($STR);
$sql = "INSERT INTO ' tab ' (' Content ') VALUES (' $str ')";
When you are out of the library
$str =stripslashes ($STR);
When displayed
$str =htmlspecialchars (NL2BR ($STR));



The Addslashes () function adds a backslash before the specified predefined character.

These predefined characters are:

??? Single quotation mark (')
??? Double quotation marks (")
??? Back slash (\)
??? Null

The Stripslashes () function deletes a backslash added by the addslashes () function.
The Htmlspecialchars () function converts some pre-defined characters to HTML entities

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 ("/(. *) &$/", "$", $se);
$se? $se = "?". $se: "";
Echo??? $s. "? $se ";
[/php]
--------------------------------------------




20: I click on the Back button, why did the thing before fill disappear

This is because you used the session.
Workaround:

PHP Code:--------------------------------------------

[PHP]
Session_cache_limiter (' Private, must-revalidate ');
Session_Start ();
...........
..........
[/php]

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



21: How to show the IP address in the picture


PHP Code:--------------------------------------------

[PHP]
? 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,oxff,oxff);??????? Font Color
? Imagettftext ($img, 10,0,78,30, $shadow, "D:/windows/fonts/tahoma.ttf", $IP); Show 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);
[/php]

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



22: How to get the real IP of the user


PHP Code:--------------------------------------------

[PHP]
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 () {
$ip 1 = iptype1 ();
? $ip 2 = iptype2 ();
$ip 3 = Iptype3 ();
if (Isset ($ip 1) && $ip 1! = "None" && $ip 1! = "Unknown") {
??? return $IP 1;
}
ElseIf (Isset ($ip 2) && $ip 2! = "None" && $ip 2! = "Unknown") {
??? return $IP 2;
}
ElseIf (Isset ($ip 3) && $ip 3! = "None" && $ip 3! = "Unknown") {
??? return $IP 3;
}?
? else {
? return "None";
}
}

Echo IP ();
[/php]
--------------------------------------------



23: How to read all records from the database in three days

First, there is a datetime field in the table to record the time,
Formatted as ' 2003-7-15 16:50:00 '

SELECT * from ' xltxlm ' WHERE to_days (now ())-to_days (' Date ') <= 3;


24: How to remotely link MySQL database


In the MySQL table for adding users, there is a host field, modified to "%", or an IP address that allows the connection, so that you can call it remotely.

$link =mysql_connect ("192.168.1.80:3306", "Root", "" ");


25: How to use the regular

Click here
Special characters in regular expressions


26: After using Apache, the main page appears garbled


Method One:
Adddefaultcharset iso-8859-1 change to adddefaultcharset off

Method Two:
Adddefaultcharset GB2312
========================================================
Tip
GB2312 will be interpreted as?????? when you post code.

Change it so that it doesn't
GB2312

10: How to compare two dates in a couple of days (simpler algorithm)


PHP Code:--------------------------------------------

[PHP]
$Date _1= "2003-7-15";//can also be: $Date _1= "2003-7-15 23:29:14";
$Date _2= "1982-10-1";
$d 1=strtotime ($Date _1);
$d 2=strtotime ($Date _2);
$Days =round (($d 1-$d 2)/3600/24);
Echo??? "I have struggled $Days days ^_^";
[/php]

--------------------------------------------
Round (123.456,2)? = 123.46
ROUND?? (?? numeric_expression??,?? length)

Round (123.456,-2)? =100

When?? Length?? is a positive number, numeric_expression?? Rounding for?? Length?? The number of decimal digits that are specified. When?? Length?? is negative, numeric_expression?? Then press?? Length?? The specified value is rounded to the left of the decimal point;

? Floor (123.45),????? Floor ( -123.45),????? Floor ($123.45)

? ---------???????????? ---------?????????? -----------

? 123????????????????? -124??????????????? 123.0000??????

?

? CEILING (123.45),?? CEILING ( -123.45),?? CEILING (0.0)

? The following is a set of results:

? ---------????????? ---------????????? ------------------??

? 124?????????????? -123?????????????????? 0??

======================================================================

27: Why single quotes, double quotes in the Accept page becomes (' ")


Workaround:
Method One: Set in php.ini: MAGIC_QUOTES_GPC = Off
Method Two: $str =stripcslashes ($STR)


28: How to keep the program running, not more than 30 seconds to stop


Set_time_limit (60)//maximum run time one minute
Set_time_limit (0)//run to the end of the program itself, or manually stop


29: Calculate the current number of people online

Example one: implementation with text

PHP Code:--------------------------------------------

[PHP]
First, you have permission to read and write files.
This program can be run directly, the first error, after you can
? $online _log = "Count.dat"; Save the number of documents,
? $timeout = 30;//30 sec No move author, think drop line
? $entries = File ($online _log);

? $temp = Array ();

? for ($i =0; $i ??? $entry = Explode (",", Trim ($entries [$i]));
??? if ($entry [0]! = getenv (' remote_addr ')) && ($entry [1] > Time ())) {
??? Array_push ($temp, $entry [0]. ",". $entry [1]. " n "); Take out other visitors ' information and remove the timeout and save into $temp
??? }
? }

??? Array_push ($temp, getenv (' remote_addr '). ",". ( Time () + ($timeout)). " n "); Time to update visitors
? $users _online = count ($temp); Calculate the number of people online

? $entries = Implode ("", $temp);
? Write file
? $fp = fopen ($online _log, "w");
??? Flock ($FP, LOCK_EX); Flock () does not work correctly in NFS and some other network file systems
??? Fputs ($fp, $entries);
??? Flock ($FP, lock_un);
??? Fclose ($FP);

??? echo "currently has". $users _online. " People online ";

[/php]
--------------------------------------------

Example two:
Implementing online users with a database


30: What is a template, how to use


Here are a few articles about the template

I'm using a phplib template.
Here are the use of several of these functions

$T->set_file ("arbitrarily defined", "template file. TPL");

$T->set_block ("defined in Set_file", " "," arbitrarily defined ");

$T->parse ("defined in Set_block", " ", true);

$T->parse ("Random Output results", "defined in Set_file");

Set the loop format to:



How to generate a static Web page from a template

PHP Code:--------------------------------------------

[PHP]
Use the Phplib template here
??? ............
??? ............
??? $TPL->parse ("Output", "html");
??? $output = $tpl->get ("output");//$output for the entire Web page content


??? 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 the file.
??? Wfile ($FILE, $output);
??? Header ("Location: $FILE");//redirect to the generated Web page
}
[/php]
--------------------------------------------



Phplib Download address smarty Download address


31: How to interpret characters in PHP

For example: Input 2+2* (1+2), auto output 8
You can use the Eval function

PHP Code:--------------------------------------------


[PHP]
$str =$_post[' str '];
Eval ("$o = $str;");
Echo??? "$o";
[/php]

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


In addition, use this function to be particularly careful!!
If someone entered Format:d: What would be the result?

  • 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.

    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.