Home >Backend Development >PHP Tutorial >PHP beginner mistakes set
Please turn on all error prompts when doing development: error_reporting = E_ALL | E_STRICT
Blocking error prompts is equivalent to hiding your ears and stealing the bell.
Writing code in a standardized manner will reduce errors by half.
1: Why can’t I get the variable
I POST data name from one web page to another web page, why can’t I get any value when I output $name?
In PHP4.2 and later versions, register_global defaults to off
If you want to get the variables submitted from another page:
Method 1: Find register_global in PHP.ini and set it to on.
Method 2: Put this extract($_POST) at the front of the receiving web page; extract($_GET);(Note that there must be Session_Start() before extract($_SESSION)).
//extract ( array $var_array [, int $extract_type [, string $prefix ]] )
//This function is used to import variables from the array into the current symbol table. Accepts the associative array var_array as argument and uses the key //name as the variable name and the value as the variable's value. For each key/value pair a variable is created in the current symbol table, affected by the //extract_type and prefix parameters.
//import_request_variables ( string $types [, string $prefix ] ) is super global and has loopholes in $_ $*
Method 3: Read variables one by one $a=$_GET["a"];$b= $_POST["b"], etc. Although this method is troublesome, it is safer.
2: Debugging your program
You must know the value of a certain variable at runtime. This is what I did, create a file debug.php, its content is as follows:
PHP code: ---------------------------- -------------------------------------------------- --
Copy code
Ob_Start();
Session_Start();
Echo "
";<br> Echo "The _GET variables obtained on this page are:";<br> Print_R($_GET);<br> Echo " The _POST variables obtained on this page are: ";<br> Print_R($_POST);<br> Echo "The _COOKIE variables obtained on this page are: ";<br> Print_R($_COOKIE);<br> Echo "The _SESSION variables obtained on this page are :";<br> Print_R($_SESSION);<br> Echo "";
";<br>Echo $_GET["Name"];<br>Echo "";
";<br>Echo "Here displays all functions supported by the system, and custom functions phpn";<br>print_r($arr);<br>echo "";
You Uploaded 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, the browser needs to provide support for this 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 "After the file is uploaded, it is temporarily stored as:";
echo $_FILES['upload_file']['tmp_name'];
//The temporary file name stored on the server after the file is uploaded.
echo "
";
$Erroe=$_FILES['upload_file']['error'];
switch($Erroe){
1:
.
Case 3: c Echo "files are only uploaded"; Break;
Case 4:
Echo "No files are uploaded"; break;
}
[/pHP]
------------------------------------------------------------------------------------------------------------------------ -------------------------------------------------- --------------------
14: How to configure the GD library
The following is my configuration process
1: Use dos command (can also be operated manually , copy all dll files in the dlls folder to the 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 extension. If there is no php_gd2.dll, the same goes for php_gd.dll. Make sure this file does exist c:/php/extensions/php_gd2.dll
4: Run the following program to test
PHP code:------------------------------------------------ ----------------------------------
[php]
Ob_end_flush();
//Attention, here No information can be output to the browser before. Please pay attention to whether auto_prepend_file is set.
header ("Content-type: image/png");
$im = @imagecreate (200, 100)
or die ("Unable to 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 UBB code
UBB code is a variant of HTML, which is adopted by Ultimate Bulletin Board (a foreign BBS program, and many places in China also use this program) A special TAG.
Even if the use of HTML is prohibited, you can still use UBBCode? to achieve it. Maybe you prefer to use UBBCode? instead of HTML, even if the forum allows the use of HTML, because it uses less code and is safer.
Q3boy's UBB has examples, you can run the test directly
16: I want to modify the MySQL user and password
First of all, I must declare that in most cases, modifying MySQL requires root permissions in mysql.
So general users cannot change their passwords unless they request the administrator.
Method 1
Use phpmyadmin, this is the simplest, modify the user table of the mysql library,
But don’t forget to use the PASSWORD function.
Method 2
Using mysqladmin, this is a special case stated earlier.
Mysqladmin -u root -p password mypasswd
After entering this command, you need to enter the original password of root, and then the password of root will be changed to mypasswd.
Change root in the command to your username, and you can change your own password.
Of course, if your mysqladmin cannot connect to the mysql server, or you cannot execute mysqladmin,
then this method is invalid.
And mysqladmin cannot clear the password.
The following methods are all used at the mysql prompt and must have mysql root permissions:
Method 3
mysql> INSERT INTO mysql.user (Host,User,Password)
VALUES('%','jeffrey', PASSWORD('biscuit'));
mysql> FLUSH PRIVILEGES
To be precise, this is adding a user with the username jeffrey and the password biscuit.
There is this example in the "mysql Chinese Reference Manual", so I wrote it out.
Note to use the PASSWORD function, and then use FLUSH PRIVILEGES.
Method 4
Same as method 3, just using the REPLACE statement
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,
But there is no need to use FLUSH PRIVILEGES.
Method 6
Use GRANT... IDENTIFIED BY statement
mysql> GRANT USAGE ON *.* TO jeffrey@"%" IDENTIFIED BY 'biscuit';
The PASSWORD() function is unnecessary here, and there is no need to use FLUSH PRIVILEGES.
Note: PASSWORD() [does not] perform password encryption in the same way as Unix password encryption.
17: I want to know which website he connected to this page through
PHP code:-------------------------- -------------------------------------------------- ----
[php]
//You must enter through a super connection to have output
Echo $_SERVER['HTTP_REFERER'];
[/php]
------------- -------------------------------------------------- ------------------
18: What should you pay attention to when putting data into the database and taking it out to display on the page
When entering the database
$str=addslashes($str) ;
$sql="insert into `tab` (`content`) values('$str')";
When leaving the library
$str=stripslashes($str);
When displaying
$str=htmlspecialchars(nl2br( $str)) ;
addslashes() function adds a backslash before the specified predefined characters.
These predefined characters are:
single quote (')
double quote (")
backslash()
NULL
stripslashes() function removes backslashes added by addslashes() function.
htmlspecialchars( ) function converts some predefined characters into 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("/(.*)&$/","$1",$se);
$se?$se="?".$se:"";
echo $s."?$se";
[/php]
-------------------------------------------------- ------------------------------------
20: I clicked the back button, why before The filled-in items are missing
This is because you used session.
Solution:
PHP code:-------------------------- -------------------------------------------------- ---
[php]
session_cache_limiter('private, must-revalidate');
session_start();
..........
..........
[ /php]
------------------------------------------------ ----------------------------------
21: How to display IP address in pictures
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 user’s real IP
PHP code:------------------------------------------------ ----------------------------------
[php]
function iptype1 () {
if (getenv( "Http_client_ip") {
Return Getenv ("http_client_ip"); Forwardeded_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();
[/php]
-------------------------- -------------------------------------------------- ----
23: How to read all records within three days from the database
First of all, there must be a DATETIME field in the table to record the time,
The format is '2003-7-15 16:50:00'
SELECT * FROM `xltxlm` WHERE TO_DAYS(NOW()) - TO_DAYS(`date`) <= 3;
24: How to remotely connect to Mysql database
There is a host field in the mysql table where users are added, Change it to "%", or specify the 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 regular expressions
Click here
Special characters in regular expressions
26:Use After Apache, garbled characters appear on the homepage
Method one:
AddDefaultCharset ISO-8859-1 changed to AddDefaultCharset off
Method two:
AddDefaultCharset GB2312
==================== ======================================
tip:
GB2312 will be explained when everyone posts the code
If you change it to this, it will not happen
GB2312
10: How to compare the number of days between two dates, (simpler algorithm)
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 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 rounds to the number of decimal places specified by length . When length is negative, numeric_expression is based on the left side of the decimal point as specified by Length; ------- .45), CEILING(0.0)
The following is the result set:
--------- ================================================== ================
27: Why do single quotes and double quotes become ('") on the acceptance page
Solution:
Method 1: In php.ini Setting: magic_quotes_gpc = Off
Method 2: $str=stripcslashes($str)
28: How to keep the program running instead of stopping after more than 30 seconds
set_time_limit(60)//Maximum running time one Minutes
set_time_limit(0)//Run until the program ends by itself, or stop manually
29: Calculate the number of people currently online
Example 1: Use text to implement
PHP code:---------- -------------------------------------------------- -------------------
[php]
//First you must have permission to read and write files
//This program can be run directly, and an error will be reported the first time, You can do it later
$online_log = "count.dat"; //Save the file of the number of people,
$timeout = 30; //If there is no action within 30 seconds, it will be considered offline
$entries = file($online_log);
$temp = array();
for ($i=0;$i
if (($entry[0] != getenv('REMOTE_ADDR')) && ($entry[1] > time() )) {
array_push($temp,$entry[0].",".$entry[1]."n"); //Get the information of other viewers, remove the timeout ones, and save it in $temp
}
}
array_push($temp,getenv('REMOTE_ADDR').",".(time() + ($timeout))."n"); //Update the viewer's time
$users_online = count($ temp); //Calculate the number of people online
$entries = implode("",$temp);
//Write to file
$fp = fopen($online_log,"w");
flock($fp,LOCK_EX) ; //flock() does not work properly in NFS and some other network file systems
fputs($fp,$entries);
flock($fp,LOCK_UN);
fclose($fp);
echo "Current There is ".$users_online."人在线";
[/php]
-------------------------------- ----------------------------------------
Example 2:
Use database to implement online users
30: What is a template and how to use it
Here are several articles about templates
I use phplib template
Here are the uses of several of the functions
$T->Set_File("Any definition","template file.tpl");
$T->Set_Block("defined in set_file","" ,"define whatever you want");
$T->Parse("defined in Set_Block","",true);
$T->Parse( "Output the results at will", "defined in Set_File");
Set the loop format to:
How to generate a static web page from a template
PHP code:--------------------------------------------- ----------------------------------------
[php]
//here Use phplib template
$tpl->get("output");// $output is 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 file
Wfile($FILE,$output);
header("location:$FILE");//Redirect to the generated web page
}
[/php]
---- -------------------------------------------------- --------------------------
phplib download address smarty download address
31: How to use php to interpret characters
For example: Input 2+2*(1+2) and automatically output 8
You can use the eval function
PHP code:-------------------------- -------------------------------------------------- ----