search
HomeBackend DevelopmentPHP TutorialSummary of Php FAQs Page 1/2_PHP Tutorial

Summary of Php FAQs Page 1/2_PHP Tutorial

Jul 21, 2016 pm 04:12 PM
phpErrorexistplacecommon problemSummarizepartquestion



若有出错地方或者你有更好的想法,欢迎跟贴.


在提问题前请先仔细查阅PHP手册,MYSQL手册  以及PHPINFO里面的设置
另外希望你读一下PHP编程标准

PHP手册下载地址

1:为什么我得不到变量

我在一网页向另一网页POST数据name,为什么输出$name时却得不到任何值?

在PHP4.2以后的版本中register_global默认为off
若想取得从另一页面提交的变量:

方法一:在PHP.ini中找到register_global,并把它设置为on.
方法二:在接收网页最前面放上这个extract($_POST);extract($_GET);(注意extract($_SESSION)前必须要有Session_Start()).
方法三:一个一个读取变量$a=$_GET["a"];$b=$_POST["b"]等,这种方法虽然麻烦,但比较安全.

2:调试你的程序

在运行时必须知道某个变量为何值。我是这样做的,建立一文件debug.php,其内容如下:

CODE:
[Copy to clipboard]
Ob_Start();
Session_Start();
Echo 
"
"
;

Echo 
"本页得到的_GET变量有:";
Print_R($_GET);

Echo 
"本页得到的_POST变量有:";
Print_R($_POST);

Echo 
"本页得到的_COOKIE变量有:";
Print_R($_COOKIE);

Echo 
"本页得到的_SESSION变量有:";
Print_R($_SESSION);
Echo 
"";
?>
然后在php.ini中设置:include_path = "c:/php",并将debug.php放在此文件夹,
以后就可以在每个网页里包含此文件,查看得到的变量名和值.

3:如何使用session

凡是与session有关的,之前必须调用函数session_start();


为session付值很简单,如:

CODE:
[Copy to clipboard]
Session_start();
$Name "这是一个Session例子";
Session_Register("Name");//注意,不要写成:Session_Register("[color=red]$Name[/color]");
Echo $_SESSION["Name"];
//之后$_SESSION["Name"]为"这是一个Session例子"
?>
在php4.2之后,可以为session直接付值:

CODE:
[Copy to clipboard]
Session_Start();
$_SESSION["name"]="value";
?>
取消session可以这样:

CODE:
[Copy to clipboard]
session_start();
session_unset();
session_destroy();
?>
取消某个session变量在php4.2以上还有BUG.



注意:


1:在调用Session_Start()之前不能有任何输出.例如下面是错误的.

==========================================
1行
2行 3行 Session_Start();//之前在第一行已经有输出
4行 .....
5行 ?>
==========================================


提示1:

凡是出现"........headers already sent..........",就是Session_Start()之前向浏览器输出信息.
去掉输出就正常,(COOKIE也会出现这种错误,错误原因一样)

提示2:

如果你的Session_Start()放在循环语句里,并且很难确定之前哪里向浏览器输出信息,可以用下面这种方法:
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:为什么我向另一网页传送变量时,只得到前半部分,以空格开头的则全部丢失


CODE:
[Copy to clipboard]
$Var="hello php";//修改为$Var="     hello php";试试得到什么结果
$post"receive.php?Name=".$Var;
header("location:$post");
?>
receive.php的内容:

CODE:
[Copy to clipboard]
Echo "
"
;
Echo   
$_GET["Name"];
Echo 
"";
?>
正确的方法是:

CODE:
[Copy to clipboard]
$Var="hello php";
$post"receive.php?Name=".urlencode($Var);
header("location:$post");
?>
在接收页面你不需要使用Urldecode(),变量会自动编码.


5:如何截取指定长度汉字而不会出现以"?>"结尾,超出部分以"..."代替


一般来说,要截取的变量来自Mysql,首先要保证那个字段长度要足够长,一般为char(200),可以保持100个汉字,包括标点.

CODE:
[Copy to clipboard]
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:规范你的SQL语句


在表格,字段前面加上"`",这样就不会因为误用关键字而出现错误,
当然我并不推荐你使用关键字.

例如
$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格式的字符串不被解释,而是照原样显示


CODE:
[Copy to clipboard]
$str="

PHP

"
;
Echo 
"被解释过的: ".$str."
经过处理的:"
;
Echo   
htmlentities(nl2br($str));
?>

8:怎么在函数里取得函数外的变量值


CODE:
[Copy to clipboard]
$a="PHP";
foo();
Function 
foo()
{
  global 
$a;//删除这里看看是什么结果
  
Echo "$a";
}
?>

9:我怎么知道系统默认支持什么函数


CODE:
[Copy to clipboard]
$arr get_defined_functions(); 
Function 
php() {
}
echo   
"
"

Echo   
"这里显示系统所支持的所有函数,和自定以函数phpn";
print_r($arr); 
echo   
""
?>

10:如何比较两个日期相差几天


CODE:
[Copy to clipboard]
$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:为什么我升级PHP后,原来的程序出现满屏的 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文件就相当于

CODE:
[Copy to clipboard]
Include "auto_prepend_file.php" ;

.......
//这里是你的程序


Include "auto_append_file.php";
?>

13:如何利用PHP上传文件


CODE:
[Copy to clipboard]

Upload file form


Please select a file:









$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 ;//Whether overwriting the same file is allowed
//Check file size
if ($upload_file_size > $file_size_max) {
echo
"Sorry, your file size is larger than specified";
exit;
}

// Check read and write files
if (file_exists( $store_dir . $upload_file_name) && !$accept_overwrite) {
Echo
"File with the same file name exists";
exit;
}

//Copy the file to the specified directory
if (!move_uploaded_file($upload_file,$store_dir .$upload_file_name)) {
echo
"Failed to copy file";
exit;
}

}

Echo
"

You uploaded a 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'];
//File MIME type, which requires the browser to provide support for this information, such as "image/gif". 
echo "
"
;

Echo   
"上传文件大小:";
echo 
$_FILES['upload_file']['size'];
//已上传文件的大小,单位为字节。 
echo "
"
;

Echo   
"文件上传后被临时储存为:";
echo 
$_FILES['upload_file']['tmp_name'];
//文件被上传后在服务端储存的临时文件名。 
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
设置extension_dir = "c:/php/extensions/";
3:
extension=php_gd2.dll;把extension前面的逗号去掉,如果没有php_gd2.dll,php_gd.dll也一样,保证确实存在这一文件c:/php/extensions/php_gd2.dll
4:运行下面程序进行测试

CODE:
[Copy to clipboard]
Ob_end_flush();
//注意,在此之前不能向浏览器输出任何信息,要注意是否设置了 auto_prepend_file.
header ("Content-type: image/png");
$im = @imagecreate (200100)
    or die (
"无法创建图像");
$background_color imagecolorallocate ($im0,00);
$text_color imagecolorallocate ($im230140150);
imagestring ($im33050,  "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:我想知道他是通过哪个网站连接到本页


CODE:
[Copy to clipboard]
//必须通过超级连接进入才有输出
Echo $_SERVER['HTTP_REFERER'];
?>

18:数据放入数据库和取出来显示在页面需要注意什么

入库时
$str=addslashes($str);
$sql="insert into `tab` (`content`) values('$str')";
出库时
$str=stripslashes($str);
显示时
$str=htmlspecialchars(nl2br($str)) ;





19:如何读取当前地址栏信息


CODE:
[Copy to clipboard]
$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.
解决办法:

CODE:
[Copy to clipboard]
session_cache_limiter('private, must-revalidate');
session_start(); 
...........
..........
?>

21:怎么在图片里显示IP地址


CODE:
[Copy to clipboard]

  Header
("Content-type: image/png");
  
$img ImageCreate(180,50);
  
$ip $_SERVER['REMOTE_ADDR'];
  
ImageColorTransparent($img,$bgcolor);
  
$bgColor ImageColorAllocate($img0x2c,0x6D,0xAF); // 背景颜色
  
$shadow ImageColorAllocate($img250,0,0);    // 阴影颜色
  
$textColor ImageColorAllocate($imgoxff,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


CODE:
[Copy to clipboard]
 
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: 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,
in the format of ' 2003-7-15 16:50:00'

SELECT * FROM `xltxlm` WHERE TO_DAYS(NOW()) - TO_DAYS(`date`)

24: How to remotely connect to Mysql database


There is a host field in the mysql table for adding users, change it to "%", or specify permission The IP address of 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: After using Apache, garbled characters appear on the homepage


Method one:
AddDefaultCharset ISO-8859-1 changed to AddDefaultCharset off

Method two:
AddDefaultCharset GB2312
================================================ ==========
tip:
When everyone posts code, GB2312 will be interpreted as ??????

Change it like this and it won’t be
[color=#000000]GB[/color]2312

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

I am writing here for the time being. Since the posts are too scattered and difficult to read, I concentrated them without classifying the content. I hope it will be useful to you.
In the future I will post if there are any questions and I will not edit this post again

http://www.bkjia.com/PHPjc/313760.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/313760.htmlTechArticleIf there are any mistakes or you have better ideas, please leave a comment. Please read it carefully before asking questions PHP manual, MYSQL manual and the settings in PHPINFO. I also hope you can read the PHP programming standards...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.