PHP Part FAQ Summary _php Foundation

Source: Internet
Author: User
Tags explode flush html form parse error php code strlen

PHP Part FAQ 1: Why I can't get a variable

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

Register_global defaults to off in later versions of PHP4.2
To obtain a variable submitted from another page:

Method One: Find the Register_global in the php.ini and set it to on.
Method Two: The Extract ($_post) is placed at the front of the receiving page, and extract ($_get) must have extract () before the $_session (Session_Start) is noted.
Method Three: One reads the variable $a=$_get["a"]; $b =$_post["B"] and so on, this method although troublesome, but relatively safe.

2: Debug Your Program

You must know the value of a variable at run time. I did that by creating a document debug.php, which reads as follows:

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

? Php
Ob_start ();
Session_Start ();
Echo "<pre>";

Echo "The _get variables obtained on this page are:";
Print_r ($_get);

Echo "The _post variables obtained on this page are:";
Print_r ($_post);

Echo "The _cookie variables obtained on this page are:";
Print_r ($_cookie);

Echo "The _session variables obtained on this page are:";
Print_r ($_session);
Echo "</pre>";
?>

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

Then set it in php.ini: include_path = "c:/php" and place debug.php in this folder,
You can then include this file in each page to see the resulting variable name and value.

3: How to use Session

When it comes to session, you must call the function session_start ();

Paying for the session is simple, such as:


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

<?php
Session_Start ();
$Name = "This is a session example";
Session_register ("Name");/note, do not write: Session_register ("$Name");
Echo $_session["Name"];
Then $_session["Name" as "This is a session example"
?>

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



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

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

? Php
Session_Start ();
$_session["Name"]= "value";
?>

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

Canceling a session can be like this:

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

<?php
Session_Start ();
Session_unset ();
Session_destroy ();
?>

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


Cancel a session variable above php4.2 and bug.



Attention:

1: cannot have any output before calling Session_Start (). For example, the following is wrong.
==========================================
1 lines
2 line;? Php
3 line Session_Start ();//previous output in the first line
4 lines ...
5 Lines?>
==========================================


Tip 1:

The "... headers already sent ..." is the output of the information to the browser before the Session_Start () is present.
Remove output is normal, (cookies can also appear this error, the same reason for error)

Tip 2:

If your session_start () is in a looping statement and it is difficult to determine where to output the information to the browser before, you can use the following method:
1 line;? PHP Ob_start ();?>
........ Here is your program ...



2: What's wrong with that?

Warning:session_start (): Open (/tmp\sess_7d190aa36b4c5ec13a5c1649cc2da23f, O_RDWR) failed: .....
Because you did not specify a path for the session file to be stored.

Workaround:
(1) Create folder TMP in C disk
(2) Open php.ini, find Session.save_path, modify to Session.save_path= "C:/tmp"



4: Why I transfer a variable to another page, only the first half of the part, the beginning of a space is all lost


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

<?php
$Var = "Hello php";//Modify to $var= "Hello php"; try to get a result
$post = "receive.php?" Name= ". $Var;
Header ("Location: $post");
?>

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

Content of receive.php:

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

? Php
Echo "<pre>";
Echo $_get["Name"];
Echo "</pre>";
?>

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


The correct approach is to:

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

<?php
$Var = "Hello php";
$post = "receive.php?" Name= ". UrlEncode ($Var);
Header ("Location: $post");
?>

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


On the receiving 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 with the "?>" End, Beyond the section "..." instead


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

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

? Php
$str = "This character is so long, ^_^";
$Short _str=showshort ($STR, 4);//intercept the front 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. = "..."; What you want to end with, modify it here.

return $tempstr;
}

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



6: Specification of your SQL statement


In the table, precede the field with "'" so that no error occurs because of misuse of the keyword.
Of course I don't recommend using 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 enter? Above the TAB key.


7: How to make the string in html/php format not interpreted, but as shown


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

? Php
$str = "Echo "was explained:". $str. " <br> treated by: ";
Echo htmlentities (NL2BR ($STR));
?>

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



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's the result
Echo "$a";
}
?>

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



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


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

<?php
$arr = Get_defined_functions ();
Function php () {
}
echo "<pre>";
Echo "Here shows all the functions supported by the system, and the custom function php\n";
Print_r ($arr);
echo "</pre>";
?>
--------------------------------------------------------------------------------


10: How to compare two date difference days


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

? Php
$Date _1= "2003-7-15";//may 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 for $Days days ^_^";
?>

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


11: Why I upgraded PHP, the original program appears full screen of notice:undefined variable:


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

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

Then what is error_reporting?



12: I want to add a file to the top of each file and the last one. But one of the added very troublesome

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 disk and they will automatically attach 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

Every PHP file you have in the future is equivalent

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

<?php
Include "auto_prepend_file.php";

...//This is your program.


Include "auto_append_file.php";
?>

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




13: How to upload files using PHP



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

<title> Upload File Form </title><body>
<form enctype= "Multipart/form-data" action= "" method= "POST" >
Please select File: <br>
<input name= "Upload_file" type= "file" ><br>
<input type= "Submit" value= "Upload file" >
</form>
</body>

?
$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:/";//upload file storage location
$accept _overwrite = 1;//whether to allow overwriting of the same file
Check File size
if ($upload _file_size > $file _size_max) {
echo "Sorry, your file capacity is greater than the provisions";
Exit
}

Check read and write files
if (file_exists ($store _dir. $upload _file_name) &&! $accept _overwrite) {
Echo "file with same filename";
Exit
}

Copying files to a specified directory
if (!move_uploaded_file ($upload _file, $store _dir. $upload _file_name)) {
echo "Copy file failed";
Exit
}

}

Echo "<p> you uploaded the file:";
echo $_files[' upload_file ' [' name '];
echo "<br>";
The original name of the client machine file.

The MIME type of the Echo file is: ";
echo $_files[' upload_file ' [' type '];
The MIME type of the file, which requires the browser to provide support for that information, such as "Image/gif".
echo "<br>";

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

Echo "file is temporarily stored as:";
echo $_files[' upload_file ' [' tmp_name '];
The temporary file name stored on the server after the file is uploaded.
echo "<br>";


$Erroe =$_files[' upload_file ' [' Error '];
Switch ($Erroe) {
Case 0:
Echo "Upload success"; Break
Case 1:
Echo "uploaded a file that exceeds the Upload_max_filesize option limit in php.ini." Break
Case 2:
Echo "The size of the upload file exceeds the value specified by the Max_file_size option in the HTML form.    "; Break
Case 3:
Echo "file is only partially uploaded";
Case 4:
Echo "no file uploaded";
}
?>

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



14: How to configure the GD library


The following is my configuration process
1: With dos command (can also manually operate, copy all DLL files in DLLs folder to 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, and if there is no php_gd2.dll,php_gd.dll, make sure that the document exists 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 until then, 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, M, "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, is Ultimate Bulletin Board (a foreign BBS program, there are many places in the domestic use of this program) a special tag.
Even if you prohibit the use of HTML, you can use Ubbcode? Maybe you'd prefer to use Ubbcode? Instead of HTML, even if the forums allow HTML, it's safer to use less code.

Q3boy's UBB has an example to 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,
Therefore, the general user cannot change the password unless the administrator is requested.

Method One
Using phpMyAdmin, this is the easiest, to 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 previous declaration.
Mysqladmin-u root-p Password mypasswd
After entering this command, you need to enter the original password for root, and then the root password will be changed to MYPASSWD.
Change the command root to your username, and you can change your 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 empty the password.

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

Method Four
And 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,
But you don't 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 () [is not] the password encryption is performed in the same way as the UNIX password encryption.


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



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

<?php
Must go through the super connection to have output
Echo $_server[' Http_referer '];
?>

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



18: Data into the database and take out to display in the page need to pay attention to what

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));





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 ";
?>
--------------------------------------------------------------------------------




20: I click on the Back button, why the missing items before filling

This is because you use the session.
Solution:

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

<?php
Session_cache_limiter (' Private, must-revalidate ');
Session_Start ();
...........
..........
?>

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



21: How to display the IP address in the picture


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,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); Show ip
Imagepng ($IMG);
Imagecreatefrompng ($IMG);
Imagedestroy ($IMG);
?>

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



22: How to get the user's real IP


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 () {
$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 ();
?>
--------------------------------------------------------------------------------



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

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

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


24: How to remotely link the MySQL database


In the Add user's MySQL table there is a host field, modified to "%", or specifies the IP address that allows the connection, so that you can call it remotely.

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


25: Exactly how to use

Click here
Special characters in regular expressions


26: With Apache, the homepage appears garbled


Method One:
Adddefaultcharset Iso-8859-1 changed to adddefaultcharset off

Method Two:
Adddefaultcharset GB2312
========================================================
Tip
GB2312 will be interpreted as a?????? when everyone pastes the code.

That's not going to happen.

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.