我创建了很多网站,允许管理员将文件上传到他们自己的网站。由于现在允许用户自定义在网站上变得越来越重要,我想我应该分享一下用 PHP 处理文件上传是多么容易。
XHTML 表单
<form action="accept-file.php" method="post" enctype="multipart/form-data"> Your Photo: <input type="file" name="photo" size="25" /> <input type="submit" name="submit" value="Submit" /> </form>
您需要为表单的 enctype 属性使用 multipart/form-data 值。您显然还需要至少一个 file 类型的输入元素。表单的操作标签必须提供一个 URL,该 URL 指向包含下面 PHP 片段的文件。
PHP
//if they DID upload a file...
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
//you get the following information for each file:
$_FILES['field_name']['name']
$_FILES['field_name']['size']
$_FILES['field_name']['type']
$_FILES['field_name']['tmp_name']
我在上面的 PHP 中的评论概述了该过程的工作方式,所以我只提一些关于 PHP 文件上传的注意事项:
- 许多共享托管服务器允许非常低的最大文件上传大小。如果您计划接受更大的文件,您应该考虑专用或虚拟专用服务器。
- 要在 PHP 中调整文件上传大小,请修改 php.ini 文件的“upload_max_filesize”价值。您还可以使用 PHP 的 .ini_set() 函数调整此值。
- 文件上传计入托管环境的 $_POST 大小,因此您可以需要增加php.ini 文件的post_max_size 值。
- 确保在允许用户上传文件时进行大量文件验证。允许用户将 .exe 文件上传到您的服务器会有多可怕?他们可以在服务器上做一些可怕的事情。
