Home >Backend Development >PHP Tutorial >Summary of some common problems in Php
Please carefully read the PHP manual, MYSQL manual and the settings in PHPINFO before asking questions
In addition, I hope you read the PHP programming standards
PHP manual download address
1: Why can’t I get the variables
I am on a web page POST data name to another web page, why can’t I get any value when I output $name?
In versions after PHP 4.2, 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);extract($_GET); at the front of the receiving web page (note that extract($_SESSION) must be There is Session_Start()).
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 with the following content:
<?PHP Ob_Start(); Session_Start(); Echo "<pre class="brush:php;toolbar:false">"; Echo "本页得到的_GET变量有:"; Print_R($_GET); Echo "本页得到的_POST变量有:"; Print_R($_POST); Echo "本页得到的_COOKIE变量有:"; Print_R($_COOKIE); Echo "本页得到的_SESSION变量有:"; Print_R($_SESSION); Echo ""; ?>
Then set: include_path = "c:/php" in php.ini, and put debug.php in this folder,
from now on You can include this file in each web page and view the obtained variable names and values.
3: How to use session
Everything related to session must call the function session_start() before;
Paying value for session is very simple. For example:
<?php Session_start(); $Name = "这是一个Session例子"; Session_Register("Name");//注意,不要写成:Session_Register("[color=red]$Name[/color]"); Echo $_SESSION["Name"]; //之后$_SESSION["Name"]为"这是一个Session例子" ?>
After php4.2, you can pay the value directly for the session:
<?PHP Session_Start(); $_SESSION["name"]="value"; ?>
Cancel the session like this:
<?php session_start(); session_unset(); session_destroy(); ?>
Cancel a session variable There is a BUG in php4.2 and above.
Note:
1: There cannot be any output before calling Session_Start(). For example, the following is wrong.
============================== =============
Line 1
Line 2c5d116c4fb518f99396dd72c0b9de21e
============================================
Tips 1 :
Any time ".....headers already sent....." appears, it means that information is output to the browser before Session_Start().
It will be normal if you remove the output, (COOKIE will also appear This kind of error has the same error reason)
Tips 2:
If your Session_Start() is placed in a loop statement, and it is difficult to determine where the information was output to the browser before, you can use the following method:
Line 1607531f624f00b5a705457a77c6ae252
.....Here is your program...
2: What is the error? Warning: session_start(): open(/tmpsess_7d190aa36b4c5ec13a5c1649cc2da23f, O_RDWR ) failed:....
Because you did not specify the storage path of the session file.
Solution:
(1) Create the folder tmp on the c drive
(2) Open php.ini, find session.save_path, and modify it to session.save_path= "c:/tmp"
4: Why when I transfer variables to another web page, I only get the first half, and all the ones starting with spaces are lost
<?php $Var="hello php";//修改为$Var=" hello php";试试得到什么结果 $post= "receive.php?Name=".$Var; header("location:$post"); ?>The content of receive.php:
<?PHP Echo "<pre class="brush:php;toolbar:false">"; Echo $_GET["Name"]; Echo ""; ?>Correct The method is:
<?php $Var="hello php"; $post= "receive.php?Name=".urlencode($Var); header("location:$post"); ?>You don’t need to use Urldecode() on the receiving page, the variables will be automatically encoded.
5: How to intercept Chinese characters of a specified length without ending with "?>", and the excess part will end with ".. ."Replace
Generally speaking, the variables to be intercepted come from Mysql. First, make sure that the field length is long enough, usually char(200), which can hold 100 Chinese characters, including punctuation.
<?PHP $str="这个字符好长呀,^_^"; $Short_Str=showShort($str,4);//截取前面4个汉字,结果为:这个字符... 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 .= "..."; //要以什么结尾,修改这里就可以. return $tempstr; } ?>6: Standardize your SQL Statement
Add "`" in front of the table and fields, so that errors will not occur 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 ', '2003-07-11 00:00 :00')"
"`"How to input? On the TAB key.
<?PHP $str="<h1>PHP</h1>"; Echo "被解释过的: ".$str."<br>经过处理的:"; Echo htmlentities(nl2br($str)); ?>8: How to get the function in the function External variable values
<?PHP $a="PHP"; foo(); Function foo() { global $a;//删除这里看看是什么结果 Echo "$a"; } ?>9: How do I know what functions are supported by the system by default?
<?php $arr = get_defined_functions(); Function php() { } echo "<pre class="brush:php;toolbar:false">"; Echo "这里显示系统所支持的所有函数,和自定以函数phpn"; print_r($arr); echo ""; ?>
10: How to compare the number of days between two dates
<?PHP $Date_1="2003-7-15";//也可以是:$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,0,$Date_List_2[1],$Date_List_2[2],$Date_List_2[0]); $Days=round(($d1-$d2)/3600/24); Echo "偶已经奋斗了 $Days 天^_^"; ?>
11: Why did the original program appear full after I upgraded PHP? Screen's Notice: Undefined variable:
这是警告的意思,由于变量未定义引起的.
打开php.ini,找到最下面的error_reporting,修改为error_reporting = E_ALL & ~E_NOTICE
对于Parse error错误
error_reporting(0)无法关闭.
如果你想关闭任何错误提示,打开php.ini,找到display_errors,设置为display_errors = Off.以后任何错误都不会提示.
那什么是error_reporting?
12:我想在每个文件最前,最后面都加上一文件.但一个一个添加很麻烦
1:打开php.ini文件
设置 include_path= "c:"
2:写两个文件
auto_prepend_file.php 和 auto_append_file.php 保存在c盘,他们将自动依附在每个php文件的头部和尾部.
3:在php.ini中找到:
Automatically add files before or after any PHP document.
auto_prepend_file = auto_prepend_file.php;依附在头部
auto_append_file = auto_append_file.php;依附在尾部
以后你每个php文件就相当于
<?php Include "auto_prepend_file.php" ; .......//这里是你的程序 Include "auto_append_file.php"; ?>
13:如何利用PHP上传文件
<html><head> <title>上载文件表单</title></head> <body> <form enctype="multipart/form-data" action="" method="post"> 请选择文件: <br> <input name="upload_file" type="file"><br> <input type="submit" value="上传文件"> </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;// 1M限制文件上传最大容量(bytes) $store_dir = "d:/";// 上传文件的储存位置 $accept_overwrite = 1;//是否允许覆盖相同文件 // 检查文件大小 if ($upload_file_size > $file_size_max) { echo "对不起,你的文件容量大于规定"; exit; } // 检查读写文件 if (file_exists($store_dir . $upload_file_name) && !$accept_overwrite) { Echo "存在相同文件名的文件"; exit; } //复制文件到指定目录 if (!move_uploaded_file($upload_file,$store_dir.$upload_file_name)) { echo "复制文件失败"; exit; } } Echo "<p>你上传了文件:"; echo $_FILES['upload_file']['name']; echo "<br>"; //客户端机器文件的原名称。 Echo "文件的 MIME 类型为:"; echo $_FILES['upload_file']['type']; //文件的 MIME 类型,需要浏览器提供该信息的支持,例如“image/gif”。 echo "<br>"; Echo "上传文件大小:"; echo $_FILES['upload_file']['size']; //已上传文件的大小,单位为字节。 echo "<br>"; Echo "文件上传后被临时储存为:"; echo $_FILES['upload_file']['tmp_name']; //文件被上传后在服务端储存的临时文件名。 echo "<br>"; $Erroe=$_FILES['upload_file']['error']; switch($Erroe){ case 0: Echo "上传成功"; break; case 1: Echo "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值."; break; case 2: Echo "上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。"; break; case 3: Echo "文件只有部分被上传";break; case 4: Echo "没有文件被上传";break; } ?>
14:如何配置GD库
下面是我的配置过程
1:用dos命令(也可以手动操作,拷贝dlls文件夹里所有dll文件到system32目录下) copy c:\php\dlls\*.dll c:\windows\system32\
2:打开php.ini
设置extension_dir = "c:/php/extensions/";
3:
extension=php_gd2.dll;把extension前面的逗号去掉,如果没有php_gd2.dll,php_gd.dll也一样,保证确实存在这一文件c:/php/extensions/php_gd2.dll
4:运行下面程序进行测试
<?php Ob_end_flush(); //注意,在此之前不能向浏览器输出任何信息,要注意是否设置了 auto_prepend_file. header ("Content-type: image/png"); $im = @imagecreate (200, 100) or die ("无法创建图像"); $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); ?>
15:什么是UBB代码
UBB代码是HTML的一个变种,是Ultimate Bulletin Board (国外一个BBS程序,国内也有不少地方使用这个程序)采用的一种特殊的TAG.
即使禁止使用 HTML,你也可以用 UBBCode? 来实现.也许你更希望使用 UBBCode? 而不是 HTML, 即使论坛允许使用 HTML, 因为使用起来代码较少也更安全.
Q3boy的UBB里面付有例子,可以直接运行测试
16:我想修改MySQL的用户,密码
首先要声明一点,大部分情况下,修改MySQL是需要有mysql里的root权限的,
所以一般用户无法更改密码,除非请求管理员.
方法一
使用phpmyadmin,这是最简单的了,修改mysql库的user表,
不过别忘了使用PASSWORD函数。
方法二
使用mysqladmin,这是前面声明的一个特例。
mysqladmin -u root -p password mypasswd
输入这个命令后,需要输入root的原密码,然后root的密码将改为mypasswd。
把命令里的root改为你的用户名,你就可以改你自己的密码了。
当然如果你的mysqladmin连接不上mysql server,或者你没有办法执行mysqladmin,
那么这种方法就是无效的。
而且mysqladmin无法把密码清空。
下面的方法都在mysql提示符下使用,且必须有mysql的root权限:
方法三
mysql> INSERT INTO mysql.user (Host,User,Password)
VALUES('%','jeffrey',PASSWORD('biscuit'));
mysql> FLUSH PRIVILEGES
确切地说这是在增加一个用户,用户名为jeffrey,密码为biscuit。
在《mysql中文参考手册》里有这个例子,所以我也就写出来了。
注意要使用PASSWORD函数,然后还要使用FLUSH PRIVILEGES。
方法四
和方法三一样,只是使用了REPLACE语句
mysql> REPLACE INTO mysql.user (Host,User,Password)
VALUES('%','jeffrey',PASSWORD('biscuit'));
mysql> FLUSH PRIVILEGES
方法五
使用SET PASSWORD语句,
mysql> SET PASSWORD FOR jeffrey@"%" = PASSWORD('biscuit');
你也必须使用PASSWORD()函数,
但是不需要使用FLUSH PRIVILEGES。
方法六
使用GRANT ... IDENTIFIED BY语句
mysql> GRANT USAGE ON *.* TO jeffrey@"%" IDENTIFIED BY 'biscuit';
这里PASSWORD()函数是不必要的,也不需要使用FLUSH PRIVILEGES。
注意: PASSWORD() [不是]以在Unix口令加密的同样方法施行口令加密。
17:我想知道他是通过哪个网站连接到本页
<?php //必须通过超级连接进入才有输出 Echo $_SERVER['HTTP_REFERER']; ?>
18:数据放入数据库和取出来显示在页面需要注意什么
入库时 $str=addslashes($str); $sql="insert into `tab` (`content`) values('$str')"; 出库时 $str=stripslashes($str); 显示时 $str=htmlspecialchars(nl2br($str)) ;
19:如何读取当前地址栏信息
<?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:我点击后退按钮,为什么之前填写的东西不见
这是因为你使用了session.
解决办法:
<?php session_cache_limiter('private, must-revalidate'); session_start(); ........... .......... ?>
21:怎么在图片里显示IP地址
<?php Header("Content-type: image/png"); $img = ImageCreate(180,50); $ip = $_SERVER['REMOTE_ADDR']; ImageColorTransparent($img,$bgcolor); $bgColor = ImageColorAllocate($img, 0x2c,0x6D,0xAF); // 背景颜色 $shadow = ImageColorAllocate($img, 250,0,0); // 阴影颜色 $textColor = ImageColorAllocate($img, oxff,oxff,oxff); // 字体颜色 ImageTTFText($img,10,0,78,30,$shadow,"d:/windows/fonts/Tahoma.ttf",$ip); //显示背景 ImageTTFText($img,10,0,25,28,$textColor,"d:/windows/fonts/Tahoma.ttf","your ip is".$ip); // 显示IP ImagePng($img); imagecreatefrompng($img); ImageDestroy($img); ?>
22:如何取得用户的真实IP
<? 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() { $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:如何从数据库读取三天内的所有记录
首先表格里要有一个DATETIME字段记录时间,
格式为'2003-7-15 16:50:00'
SELECT * FROM `xltxlm` WHERE TO_DAYS(NOW()) - TO_DAYS(`date`) 1f9ebcf3712a525cabd1a1b70d780bd0Set_File("随便定义","模板文件.tpl");
$T->Set_Block("在set_file中定义的","8df7370e569ae52d60d422d8c7359710","随便定义");
$T->arse("在Set_Block中定义的","8df7370e569ae52d60d422d8c7359710",true);
$T->arse("随便输出结果","在Set_File中定义的");
设置循环格式为:
e5871baf21f6bccfa8172bf32431c17f
如何将模板生成静态网页
<?php //这里使用phplib模板 ............ ............ $tpl->parse("output","html"); $output = $tpl->get("output");// $output 为整个网页内容 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; } // 写到文件里 Wfile($FILE,$output); header("location:$FILE");//重定向到生成的网页 } ?>
phplib下载地址 smarty下载地址
31:怎么用php解释字符
比如:输入2+2*(1+2),自动输出8
可以用eval函数
<form method=post action=""> <input type="text" name="str"><input type="submit"> </form> <?php $str=$_POST['str']; eval("$o=$str;"); Echo "$o"; ?>
另外,用此函数必须特别小心!!
如果有人输入format: d:会是什么结果?