php常見問題和解決方法
Jun 08, 2016 pm 05:33 PM1:為什么我得不到變量
我在一網(wǎng)頁向另一網(wǎng)頁P(yáng)OST數(shù)據(jù)name,為什么輸出$name時卻得不到任何值?
在PHP4.2以后的版本中register_global默認(rèn)為off
若想取得從另一頁面提交的變量:
方法一:在PHP.ini中找到register_global,并把它設(shè)置為on.
方法二:在接收網(wǎng)頁最前面放上這個extract($_POST);extract($_GET);(注意extract($_SESSION)前必須要有Session_Start()).
方法三:一個一個讀取變量$a=$_GET["a"];$b=$_POST["b"]等,這種方法雖然麻煩,但比較安全.
2:調(diào)試你的程序
在運(yùn)行時必須知道某個變量為何值。我是這樣做的,建立一文件debug.php,其內(nèi)容如下:
PHP代碼:--------------------------------------------------------------------------------
Ob_Start();
Session_Start();
Echo?"
";<br> <br> Echo?"本頁得到的_GET變量有:";<br> Print_R($_GET);<br> <br> Echo?"本頁得到的_POST變量有:";<br> Print_R($_POST);<br> <br> Echo?"本頁得到的_COOKIE變量有:";<br> Print_R($_COOKIE);<br> <br> Echo?"本頁得到的_SESSION變量有:";<br> Print_R($_SESSION);<br> Echo?"";
?>
--------------------------------------------------------------------------------
然后在php.ini中設(shè)置:include_path?=?"c:/php",并將debug.php放在此文件夾,
以后就可以在每個網(wǎng)頁里包含此文件,查看得到的變量名和值.
3:如何使用session
凡是與session有關(guān)的,之前必須調(diào)用函數(shù)session_start();
為session付值很簡單,如:
PHP代碼:--------------------------------------------------------------------------------
Session_start();
$Name?=?"這是一個Session例子";
Session_Register("Name");//注意,不要寫成:Session_Register("$Name");
Echo?$_SESSION["Name"];
//之后$_SESSION["Name"]為"這是一個Session例子"
?>
--------------------------------------------------------------------------------
在php4.2之后,可以為session直接付值:
PHP代碼:--------------------------------------------------------------------------------
Session_Start();
$_SESSION["name"]="value";
?>
--------------------------------------------------------------------------------
取消session可以這樣:
PHP代碼:--------------------------------------------------------------------------------
session_start();
session_unset();
session_destroy();
?>
--------------------------------------------------------------------------------
取消某個session變量在php4.2以上還有BUG.
注意:
1:在調(diào)用Session_Start()之前不能有任何輸出.例如下面是錯誤的.
==========================================
1行
2行? 3行?Session_Start();//之前在第一行已經(jīng)有輸出
4行?.....
5行??>
==========================================
提示1:
凡是出現(xiàn)"........headers?already?sent..........",就是Session_Start()之前向瀏覽器輸出信息.
去掉輸出就正常,(COOKIE也會出現(xiàn)這種錯誤,錯誤原因一樣)
提示2:
如果你的Session_Start()放在循環(huán)語句里,并且很難確定之前哪里向瀏覽器輸出信息,可以用下面這種方法:
1行?
........這里是你的程序......
2:這是什么錯誤
Warning:?session_start():?open(/tmp\sess_7d190aa36b4c5ec13a5c1649cc2da23f,?O_RDWR)?failed:....
因為你沒有指定session文件的存放路徑.
解決方法:
(1)在c盤建立文件夾tmp
(2)打開php.ini,找到session.save_path,修改為session.save_path=?"c:/tmp"
4:為什么我向另一網(wǎng)頁傳送變量時,只得到前半部分,以空格開頭的則全部丟失
PHP代碼:--------------------------------------------------------------------------------
$Var="hello?php";//修改為$Var="?????hello?php";試試得到什么結(jié)果
$post=?"receive.php?Name=".$Var;
header("location:$post");
?>
--------------------------------------------------------------------------------
receive.php的內(nèi)容:
PHP代碼:--------------------------------------------------------------------------------
Echo?"
";<br> Echo???$_GET["Name"];<br> Echo?"";
?>
--------------------------------------------------------------------------------
正確的方法是:
PHP代碼:--------------------------------------------------------------------------------
$Var="hello?php";
$post=?"receive.php?Name=".urlencode($Var);
header("location:$post");
?>
--------------------------------------------------------------------------------
在接收頁面你不需要使用Urldecode(),變量會自動編碼.
5:如何截取指定長度漢字而不會出現(xiàn)以"?>"結(jié)尾,超出部分以"..."代替
一般來說,要截取的變量來自Mysql,首先要保證那個字段長度要足夠長,一般為char(200),可以保持100個漢字,包括標(biāo)點.
PHP代碼:--------------------------------------------------------------------------------
$str="這個字符好長呀,^_^";
$Short_Str=showShort($str,4);//截取前面4個漢字,結(jié)果為:這個字符...
Echo???"$Short_Str";
Function?csubstr($str,$start,$len)?
{?
$strlen=strlen($str);?
$clen=0;?
for($i=0;$i {?
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?.=?"...";?//要以什么結(jié)尾,修改這里就可以.
return?$tempstr;?
}
--------------------------------------------------------------------------------
6:規(guī)范你的SQL語句
在表格,字段前面加上"`",這樣就不會因為誤用關(guān)鍵字而出現(xiàn)錯誤,
當(dāng)然我并不推薦你使用關(guān)鍵字.
例如
$Sql="INSERT?INTO?`xltxlm`?(`author`,?`title`,?`id`,?`content`,?`date`)?VALUES?('xltxlm',?'use`',?1,?'criterion?your?sql?string?',?'2003-07-11?00:00:00')"
"`"怎么輸入??在TAB鍵上面.
7:如何使Html/PHP格式的字符串不被解釋,而是照原樣顯示
PHP代碼:--------------------------------------------------------------------------------
$str="
PHP
";Echo?"被解釋過的:?".$str."
經(jīng)過處理的:";
Echo???htmlentities(nl2br($str));
?>
--------------------------------------------------------------------------------
8:怎么在函數(shù)里取得函數(shù)外的變量值
PHP代碼:--------------------------------------------------------------------------------
$a="PHP";
foo();
Function?foo()
{
??global?$a;//刪除這里看看是什么結(jié)果
??Echo?"$a";
}
?>
--------------------------------------------------------------------------------
9:我怎么知道系統(tǒng)默認(rèn)支持什么函數(shù)
PHP代碼:--------------------------------------------------------------------------------
$arr?=?get_defined_functions();?
Function?php()?{
}
echo???"
";?<br> Echo???"這里顯示系統(tǒng)所支持的所有函數(shù),和自定以函數(shù)php\n";<br> print_r($arr);?<br> echo???"";?
?>?
--------------------------------------------------------------------------------
10:如何比較兩個日期相差幾天
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???"偶已經(jīng)奮斗了?$Days?天^_^";
?>
--------------------------------------------------------------------------------
11:為什么我升級PHP后,原來的程序出現(xiàn)滿屏的?Notice:?Undefined?variable:
這是警告的意思,由于變量未定義引起的.
打開php.ini,找到最下面的error_reporting,修改為error_reporting?=?E_ALL?&?~E_NOTICE
對于Parse?error錯誤
error_reporting(0)無法關(guān)閉.
如果你想關(guān)閉任何錯誤提示,打開php.ini,找到display_errors,設(shè)置為display_errors?=?Off.以后任何錯誤都不會提示.
那什么是error_reporting?
12:我想在每個文件最前,最后面都加上一文件.但一個一個添加很麻煩
1:打開php.ini文件
設(shè)置?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文件就相當(dāng)于
PHP代碼:--------------------------------------------------------------------------------
Include?"auto_prepend_file.php"?;
.......//這里是你的程序
Include?"auto_append_file.php";
?>
--------------------------------------------------------------------------------
13:如何利用PHP上傳文件
PHP代碼:--------------------------------------------------------------------------------
?
?
?
$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?"對不起,你的文件容量大于規(guī)定";
exit;
}
//?檢查讀寫文件
if?(file_exists($store_dir?.?$upload_file_name)?&&?!$accept_overwrite)?{
Echo???"存在相同文件名的文件";
exit;
}
//復(fù)制文件到指定目錄
if?(!move_uploaded_file($upload_file,$store_dir.$upload_file_name))?{
echo?"復(fù)制文件失敗";
exit;
}
}
Echo???"
你上傳了文件:";
echo??$_FILES['upload_file']['name'];
echo?"
";
//客戶端機(jī)器文件的原名稱。?
Echo???"文件的?MIME?類型為:";
echo?$_FILES['upload_file']['type'];
//文件的?MIME?類型,需要瀏覽器提供該信息的支持,例如“image/gif”。?
echo?"
";
Echo???"上傳文件大小:";
echo?$_FILES['upload_file']['size'];
//已上傳文件的大小,單位為字節(jié)。?
echo?"
";
Echo???"文件上傳后被臨時儲存為:";
echo?$_FILES['upload_file']['tmp_name'];
//文件被上傳后在服務(wù)端儲存的臨時文件名。?
echo?"
";
$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
設(shè)置extension_dir?=?"c:/php/extensions/";
3:
extension=php_gd2.dll;把extension前面的逗號去掉,如果沒有php_gd2.dll,php_gd.dll也一樣,保證確實存在這一文件c:/php/extensions/php_gd2.dll
4:運(yùn)行下面程序進(jìn)行測試
PHP代碼:--------------------------------------------------------------------------------
Ob_end_flush();
//注意,在此之前不能向瀏覽器輸出任何信息,要注意是否設(shè)置了?auto_prepend_file.
header?("Content-type:?image/png");
$im?=?@imagecreate?(200,?100)
????or?die?("無法創(chuàng)建圖像");
$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);
?>

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

PHP page caching improves website performance by reducing server load and speeding up page loading. 1. Basic file cache avoids repeated generation of dynamic content by generating static HTML files and providing services during the validity period; 2. Enable OPcache to compile PHP scripts into bytecode and store them in memory, improving execution efficiency; 3. For dynamic pages with parameters, they should be cached separately according to URL parameters, and avoid cached user-specific content; 4. Lightweight cache libraries such as PHPFastCache can be used to simplify development and support multiple storage drivers. Combining these methods can effectively optimize the caching strategy of PHP projects.

ToquicklytestaPHPcodesnippet,useanonlinePHPsandboxlike3v4l.orgorPHPize.onlineforinstantexecutionwithoutsetup;runcodelocallywithPHPCLIbycreatinga.phpfileandexecutingitviatheterminal;optionallyusephp-rforone-liners;setupalocaldevelopmentenvironmentwith

Upgrading the PHP version is actually not difficult, but the key lies in the operation steps and precautions. The following are the specific methods: 1. Confirm the current PHP version and running environment, use the command line or phpinfo.php file to view; 2. Select the suitable new version and install it. It is recommended to install it with 8.2 or 8.1. Linux users use package manager, and macOS users use Homebrew; 3. Migrate configuration files and extensions, update php.ini and install necessary extensions; 4. Test whether the website is running normally, check the error log to ensure that there is no compatibility problem. Follow these steps and you can successfully complete the upgrade in most situations.

TopreventCSRFattacksinPHP,implementanti-CSRFtokens.1)Generateandstoresecuretokensusingrandom_bytes()orbin2hex(random_bytes(32)),savethemin$_SESSION,andincludetheminformsashiddeninputs.2)ValidatetokensonsubmissionbystrictlycomparingthePOSTtokenwiththe

To set up a PHP development environment, you need to select the appropriate tools and install the configuration correctly. ①The most basic PHP local environment requires three components: the web server (Apache or Nginx), the PHP itself and the database (such as MySQL/MariaDB); ② It is recommended that beginners use integration packages such as XAMPP or MAMP, which simplify the installation process. XAMPP is suitable for Windows and macOS. After installation, the project files are placed in the htdocs directory and accessed through localhost; ③MAMP is suitable for Mac users and supports convenient switching of PHP versions, but the free version has limited functions; ④ Advanced users can manually install them by Homebrew, in macOS/Linux systems
