PHP file upload analysis

小云云
Release: 2023-03-17 11:18:02
Original
6699 people have browsed it

PHP file upload is something that every programmer will encounter. So how much do you know about PHP file upload? This article mainly describes the detailed method of uploading PHP files. You can refer to it.

1. General file upload, unless the file is very small. Like a 5M file, it may take more than a minute to upload. But in PHP, the default maximum execution time of this page is 30 Seconds. That is to say, if it exceeds 30 seconds, the script will stop executing. This will result in the inability to open the web page. At this time, we can modify max_execution_time

Look for

max_execution_time
Copy after login
# in php.ini ##The default is 30 seconds. Change it to

max_execution_time = 0
Copy after login

0 to indicate no limit.

Another method is to add

set_time_limit();
Copy after login

to the php program to set the maximum page time. Execution time.

set_time_limit(0);//0表示没有限制
Copy after login

2. Modify post_max_size to set the maximum size allowed for POST data. This setting also affects file uploads.

The default post_max_size of php is 2M. If the POST data size is greater than post_max_size $_POST and $_FILES superglobals will be empty.

Find post_max_size. Change it to

post_max_size = 150M
Copy after login

3. Many people will change the second step. But when uploading files, the maximum is still 8M.

Why? We also need to change a parameter upload_max_filesize to indicate the maximum size of the uploaded file.

Look for upload_max_filesize, the default is 8M and change it to

upload_max_filesize = 100M
Copy after login

Another thing to note is: post_max_size is better than upload_max_filesize.

File upload analysis:

File upload uses the POST method. A basic file upload form is as follows:

fileupload.htm

<form enctype="multipart/form-data" action="dealfileupload.php" method="POST">
Copy after login

Select the Uploaded file:

<input name="userfile" type="file"/>
<input type="submit" value="上传"/>
</form>
Copy after login

What needs to be noted is the value of the enctype attribute and the name attribute in the file control, which are used to identify the uploaded file. The processing script for this form is as follows:

dealfileupload.php

<?php
$docroot=$_SERVER[&#39;DOCUMENT_ROOT&#39;];
$fileupload=$docroot."/upload/".$_FILES[&#39;userfile&#39;][&#39;name&#39;];
if (move_uploaded_file($_FILES[&#39;userfile&#39;][&#39;tmp_name&#39;],$fileupload))
{
echo "文件上传成功";
}
else
{
echo "文件上传失败";
}
?>
Copy after login

If the upload is successful, the file will be saved to the upload directory under the root directory of the website. Let's analyze this simple processing script.

1.1 $_FILES array

1, $_FILES system function

PHP file upload analysis

Please note here, $_FILES['myFile'][ 'name'] in "myFile" is the value of the name attribute of the text box used to store the file path in the file upload form.

2. move_uploaded_file function (function to move the file to the target location after uploading)

move_uploaded_file (temporary file, relative path of the target location and file name);

3. is_uploaded_file function (function to determine uploaded MIME type file function)

is_uploaded_file(MIME);

If the value of the name attribute in the file control in the form is userfile, then $_FILES['userfile'] contains information about the uploaded file. Suppose we upload a file named temp.txt, then:

$_FILES['userfile']['name']="temp.txt" File name

$_FILES[' userfile']['tmp_name']="c:/tmp1" Complete temporary file name

$_FILES['userfile']['type']="text/plain" File type

$_FILES['userfile']['size']=1024 File size (number of bytes)

$_FILES['userfile']['error']=0 Error code, 0 means success

1.2 

bool move_uploaded_file (string filename, string destination)
Copy after login

This function is specifically responsible for transferring uploaded files. filename represents the complete temporary file name, usually $_FILES['file1']['tmp_name']; destination represents the complete destination file name, generally $_SERVER['DOCUMENT_ROOT']."/upload/".$_FILES[ 'file1']['name']. If the upload is successful, 1 is returned, otherwise 0 is returned and an error is reported. If you want to hide the error message, you can write like this: @move_uploaded_file(...)

1.3 If you need to upload multiple files, you can set multiple file controls. Note that the name attribute must be set to different values. For example:

filesupload.htm

<form enctype="multipart/form-data" action="dealfilesupload.php" method="POST">
Copy after login

Select the file to upload 1:

 <input name="file1" type="file"/>
Copy after login

Select the file to upload 2:

<input name="file2" type="file"/>
Copy after login
<input type="submit" value="上传"/>
</form>
dealfilesupload.php
<?php
$docroot=$_SERVER[&#39;DOCUMENT_ROOT&#39;];
$file1upload=$docroot."/upload/".$_FILES[&#39;file1&#39;][&#39;name&#39;];
$file2upload=$docroot."/upload/".$_FILES[&#39;file2&#39;][&#39;name&#39;];
if (@move_uploaded_file($_FILES[&#39;file1&#39;][&#39;tmp_name&#39;],$file1upload))
{
echo "文件1上传成功";
}
else
{
echo "文件1上传失败";
}
print "<br/>";
if (@move_uploaded_file($_FILES[&#39;file2&#39;][&#39;tmp_name&#39;],$file2upload)){
echo "文件2上传成功";
}else{
echo "文件2上传失败";
}
?>
Copy after login

1.4 PHP generates HTML File principle

1. Part of PHP file operation functions

(1) fopen open file function

fopen (path and file name, opening method); //R-only Read W - Write A - Read and write

'r' Open in read-only mode and point the file pointer to the file header.

'r+' Open in read-write mode and point the file pointer to the file header.

'w' turns on writing mode, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try to create it.

'w+' Open in read-write mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it.

'a' Open writing mode and point the file pointer to the end of the file. If the file does not exist, try to create it.

'a+' Open in read-write mode and point the file pointer to the end of the file. If the file does not exist, try to create it.

(2) fread reads the file content

fread (open file, end position);//in bytes

(3) filesize reads the file size , in bytes as the unit of measurement, for files between 2~4GB, you can use sprintf("%u", filesize($file))//(formatted output function) to process

filesize ( path and file name);

(4) fwrite 写入文件内容

fwrite (打开的文件,写入的内容);

(5) fclose 关闭打开的文件

fclose (打开的文件);

(6) file_get_contents(“路径和文件名”);//功能是读取整个文件内容

(7) file_ exists(path);//函数检查文件或目录是否存在

(8) chmod(相对路径,代表PHP可访问的权限数值八进制);//更改文件或文件夹的访问权限模式

2、目录操作常用函数

mkdir() 建立新目录函数

语法:

mkdir(path,[int mode,][recursive,][context])
Copy after login

说明:path是必须参数,给出将要新建的文件夹所在的路径和名称,最好是使用绝对路径;mode是可选参数,默认值是0777(尝试以最大目录权限进行操作),该参数是八进制,即要设置该参数就必须将数值以0开头;recursive是可选参数,指出是否使用递归模式;context是可选参数,规定文件句柄的环境。Context 是可修改流的行为的一套选项。创建成功返回TRUE,否则返回FALSE。

rmdir()删除一个指定名称的空目录

语法:rmdir(目录路径和名称)

说明:尝试删除 目录路径和名称 所指定的目录。该目录必须是空的,而且要有相应的权限。如果成功则返回 TRUE,失败则返回 FALSE。

unlink() 删除文件函数

   语法:unlink(路径和文件名)

说明:删除 路径和文件名称 所指定的文件。和 Unix C 的 unlink() 函数相似。如果成功则返回 TRUE,失败则返回 FALSE。

3、其它文件操作函数

(1)string basename(string path [,string suffix]) ,path参数给出一个文件的全路径字符串,函数返回基本的文件名。如文件名以suffix结束,则去掉这部分

(2)string dirname(string path) ,返回路径中的目录部分。

(3)array pathinfo(string path) ,返回文件路径的信息,包含以下的数组单元dirname,basename,extension.

(4)string realpath(string path) ,返回规范化的绝对路径名

(5)bool copy( string source ,string dest) ,将文件从source复制到dest

例:copy("hello.txt","temp.php");

(6)float disk_free_space(string directory ) ,返回目录中的可用空间

例:$df = disk_free_space("F:\");

echo $df.''
'';

(7)float disk_total_space(string directory) ,获取指定磁盘总空间

例:

$df=disk_total_space("F:\");
echo $df.&#39;&#39;<br>&#39;&#39;;
Copy after login

(8)int file_put_contents(string filename,string data[,int flags[,resource context]]),将一个字符串写入文件

(9)string file_get_contents(string filename [,int use_include_path[,resource context]]) ,将整个文件作为一个字符串读入。不需要之前fopen()

例:

$lines=file_get_contents("hello.txt");
  echo nl2br($lines);
Copy after login

(10)int fileatime(string filename) ,取得文件的上次访问时间

例:

echo date("F d Y H:i:s",fileatime($filename);
Copy after login

(11)int filemtime(string filename),取得文件的最近修改时间

例:

echo date("F d Y H:i:s",filemtime($filename);
Copy after login

(12)array stat(string filename) 给出文件的信息or lstat( string filename) or fstat( resource handle)

例:

 $fileinfo =stat($filename);
Copy after login
echo "<table border=1><th>数字下标</th><th>关键(自PHP 5.1.4)</th>";
foreach($fileinfo as $num=>$info)
{
echo "<tr><td>".$num."</td><td>".$info."</td></tr>";
}
echo "</table>";
Copy after login

(13)string filetype(string filename) ,获取文件的类型

例:echo filetype($filename);

(14)bool is_dir(string filename) ,判断给定的文件名是否是一个目录

例:

if(is_dir($filename))
echo $filename.&#39;&#39;为目录<br>&#39;&#39;;
else
echo $filename.&#39;&#39;非目录<br>&#39;&#39;;
Copy after login

(15)bool flock(int handle,int operation [,int &wouldblock]) ,进行文件锁定

operation: LOCK_SH:共享锁定

LOCK_EX: 独占锁定

LOCK_UN: 释放锁定

(16)bool is_uploaded_file(string filename)

判断文件是否通过HTTP POST上传

(17)bool move_uploaded_file(string filename,string destination)

检测文件是否是合法的上传文件,是则移动到destination 指定的文件

(18)array file(path,include_path,context)

函数把整个文件读入一个数组中。与 file_get_contents() 类似,不同的是 file() 将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败,则返回 false。

path 必需。规定要读取的文件。include_path 可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 "1"。context 可选。规定文件句柄的环境。 context 是一套可以修改流的行为的选项。若使用 null,则忽略。

注释:如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。

(19) string fgetss()

fgetss() 函数从打开的文件中读取一行并过滤掉 HTML 和 PHP 标记。与 fgets() 相同,不同的是 fgetss 尝试从读取的文本中去掉任何 HTML 和 PHP 标记。

使用方法:fgetss(file,length,tags)

file 必需。规定要读取的文件。length 可选。规定要读取的字节数。默认是 1024 字节。该参数在 PHP 5 之前是必需的。tags 可选。规定将被删除的标签。可以用可选的第三个参数 tags 指定哪些标记不被去掉。若失败,则返回 false。

<?php
$file = fopen("test.htm","r");
echo fgetss($file,1024,"<p>,<b>");//保留p和b标记
fclose($file);
?>
Copy after login

(20) string fgets()

fgets() 函数从文件指针中读取一行。file 必需。规定要读取的文件。length 可选。规定要读取的字节数; 默认是 1024 字节。

从 file 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(要看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。

若失败,则返回 false。

4、遍历文件夹中的文件

$dir=opendir(''文件夹路径名'');//打开文件夹,返回一个文件夹对象(句柄)

while($fileName=readdir($dir))//readdir(参数是用opendir打开的文件夹对象名),每执行一次都会

取出指定文件夹中的一个文件名称,且文件指针向下移动一个

{
echo &#39;&#39;fileName=&#39;&#39;.$fileName. &#39;&#39;<br />&#39;&#39;;//输出取得的文件名
}
?>
Copy after login

opendir() 函数返回一个目录句柄即文件夹对象,可由 closedir(),readdir() 和 rewinddir() 使用。

若成功,则该函数返回一个目录流,否则返回 false 以及一个 error。可以通过在函数名前加上 "@" 来隐藏 error 的输出。

readdir() 函数返回由 opendir() 打开的目录句柄中的文件名称。若成功,则该函数返回一个文件名,否则返回 false。

5、文件上传成功后要清除其所占用的内存,方法是使用imagedestroy()函数。详见手册

篇幅有点长,希望帮助到大家,让大家对PHP文件上传有更清楚的思路。

相关推荐:

php实现文件上传的示例代码分享

php网页常见文件上传功能的实现实例

用php实现常用文件上传类的方法

The above is the detailed content of PHP file upload analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!