Summary of Php FAQs Page 1/2_PHP Tutorial
You uploaded a file:"
若有出错地方或者你有更好的想法,欢迎跟贴.
在提问题前请先仔细查阅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,其内容如下:
Session_Start();
Echo ""</font><font color="#007700">;<br><br>Echo </font><font color="#dd0000">"本页得到的_GET变量有:"</font><font color="#007700">;<br></font><font color="#0000bb">Print_R</font><font color="#007700">(</font><font color="#0000bb">$_GET</font><font color="#007700">);<br><br>Echo </font><font color="#dd0000">"本页得到的_POST变量有:"</font><font color="#007700">;<br></font><font color="#0000bb">Print_R</font><font color="#007700">(</font><font color="#0000bb">$_POST</font><font color="#007700">);<br><br>Echo </font><font color="#dd0000">"本页得到的_COOKIE变量有:"</font><font color="#007700">;<br></font><font color="#0000bb">Print_R</font><font color="#007700">(</font><font color="#0000bb">$_COOKIE</font><font color="#007700">);<br><br>Echo </font><font color="#dd0000">"本页得到的_SESSION变量有:"</font><font color="#007700">;<br></font><font color="#0000bb">Print_R</font><font color="#007700">(</font><font color="#0000bb">$_SESSION</font><font color="#007700">);<br>Echo </font><font color="#dd0000">"
";
?>
以后就可以在每个网页里包含此文件,查看得到的变量名和值.
3:如何使用session
凡是与session有关的,之前必须调用函数session_start();
为session付值很简单,如:
$Name = "这是一个Session例子";
Session_Register("Name");//注意,不要写成:Session_Register("[color=red]$Name[/color]");
Echo $_SESSION["Name"];
//之后$_SESSION["Name"]为"这是一个Session例子"
?>
$_SESSION["name"]="value";
?>
session_unset();
session_destroy();
?>
注意:
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:为什么我向另一网页传送变量时,只得到前半部分,以空格开头的则全部丢失
$post= "receive.php?Name=".$Var;
header("location:$post");
?>
"</font><font color="#007700">;<br>Echo </font><font color="#0000bb">$_GET</font><font color="#007700">[</font><font color="#dd0000">"Name"</font><font color="#007700">];<br>Echo </font><font color="#dd0000">"
";
?>
$post= "receive.php?Name=".urlencode($Var);
header("location:$post");
?>
5:如何截取指定长度汉字而不会出现以"?>"结尾,超出部分以"..."代替
一般来说,要截取的变量来自Mysql,首先要保证那个字段长度要足够长,一般为char(200),可以保持100个汉字,包括标点.
$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格式的字符串不被解释,而是照原样显示
PHP
";
Echo "被解释过的: ".$str."
经过处理的:";
Echo htmlentities(nl2br($str));
?>
8:怎么在函数里取得函数外的变量值
foo();
Function foo()
{
global $a;//删除这里看看是什么结果
Echo "$a";
}
?>
9:我怎么知道系统默认支持什么函数
Function php() {
}
echo ""</font><font color="#007700">; <br>Echo </font><font color="#dd0000">"这里显示系统所支持的所有函数,和自定以函数phpn"</font><font color="#007700">;<br></font><font color="#0000bb">print_r</font><font color="#007700">(</font><font color="#0000bb">$arr</font><font color="#007700">); <br>echo </font><font color="#dd0000">"
";
?>
10:如何比较两个日期相差几天
$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文件就相当于
.......//这里是你的程序
Include "auto_append_file.php";
?>
13:如何利用PHP上传文件
$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 "
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:运行下面程序进行测试
//注意,在此之前不能向浏览器输出任何信息,要注意是否设置了 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:我想知道他是通过哪个网站连接到本页
Echo $_SERVER['HTTP_REFERER'];
?>
18:数据放入数据库和取出来显示在页面需要注意什么
入库时
$str=addslashes($str);
$sql="insert into `tab` (`content`) values('$str')";
出库时
$str=stripslashes($str);
显示时
$str=htmlspecialchars(nl2br($str)) ;
19:如何读取当前地址栏信息
$se='';
foreach ($_GET as $key => $value) {
$se.=$key."=".$value."&";
}
$se=Preg_Replace("/(.*)&$/","$1",$se);
$se?$se="?".$se:"";
echo $s."?$se";
?>
20:我点击后退按钮,为什么之前填写的东西不见
这是因为你使用了session.
解决办法:
session_start();
...........
..........
?>
21:怎么在图片里显示IP地址
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
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`) <= 3;
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

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

DeepSeekAI Tool User Guide and FAQ DeepSeek is a powerful AI intelligent tool. This article will answer some common usage questions to help you get started quickly. FAQ: The difference between different access methods: There is no difference in function between web version, App version and API calls, and App is just a wrapper for web version. The local deployment uses a distillation model, which is slightly inferior to the full version of DeepSeek-R1, but the 32-bit model theoretically has 90% full version capability. What is a tavern? SillyTavern is a front-end interface that requires calling the AI model through API or Ollama. What is breaking limit
