用php文件创建表,使用PHP创建单个文件上传表单的最佳方式是什么?

文件上传教程

HTML

> action.php是将处理上传的PHP文件的名称(如下所示)

> MAX_FILE_SIZE必须在输入类型文件之前立即出现。该值可以很容易地在客户端上操作,所以不应该依赖它。其主要优点是在用户上传之前向用户提供他们的文件太大的预警。

>您可以使用类型文件更改输入的名称,但请确保它不包含任何空格。您还必须更新PHP文件中的相应值(如下)。

PHP

$uploaddir = "/www/uploads/";

$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '

';

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {

echo "Success.\n";

} else {

echo "Failure.\n";

}

echo 'Here is some more debugging info:';

print_r($_FILES);

print "

";

?>

上传文件夹不应位于可通过HTTP访问的地方,否则可能会上传PHP脚本并在服务器上执行。

打印$ _FILES的值可以提供一些提示。例如:

Array

(

[userfile] => Array

(

[name] => Filename.ext

[type] =>

[tmp_name] =>

[error] => 2

[size] => 0

)

)

此结构提供了关于文件名,MIME类型,大小和错误代码的一些信息。

错误代码

0 Indicates that there was no errors and file has been uploaded successfully

1 Indicates that the file exceeds the maximum file size defined in php.ini. If you would like to change the maximum file size, you need to open your php.ini file, identify the line which reads: upload_max_filesize = 2M and change the value from 2M (2MB) to whatever you need

2 Indicates that the maximum file size defined manually, within an on page script has been exceeded

3 Indicates that file has only been uploaded partially

4 Indicates that the file hasn’t been specified (empty file field)

5 Not defined yet

6 Indicates that there´s no temporary folder

7 Indicates that the file cannot be written to the disk

php.ini配置

当使用较大的文件运行此设置时,您可能会收到错误。检查你的php.ini文件这些键:

max_execution_time = 30

upload_max_filesize = 2M

酌情增加这些值可能有所帮助。使用Apache时,此文件的更改需要重新启动。

当文件被上传到tmp目录时,最大内存允许值(通过memory_limit设置)不起作用。 tmp目录的位置可以通过upload_tmp_dir进行控制。

检查文件模式

您应该检查用户正在上传的文件类型 – 最佳做法是根据允许的文件类型列表进行验证。允许任何文件的潜在风险是用户可能会将PHP代码上传到服务器,然后运行它。

您可以使用非常有用的fileinfo扩展(取代旧的mime_content_type功能)来验证mime类型。

// FILEINFO_MIME set to return MIME types, will return string of info otherwise

$fileinfo = new finfo(FILEINFO_MIME);

$file = $fileinfo->file($_FILE['filename']);

$allowed_types = array('image/jpeg', 'image/png');

if(!in_array($file, $allowed_types))

{

die('Files of type' . $file . ' are not allowed to be uploaded.');

}

// Continue

更多信息

您可以在PHP.net manual上阅读更多关于处理文件上传的信息。

对于PHP 5.3

//For those who are using PHP 5.3, the code varies.

$fileinfo = new finfo(FILEINFO_MIME_TYPE);

$file = $fileinfo->file($_FILE['filename']['tmp_name']);

$allowed_types = array('image/jpeg', 'image/png');

if(!in_array($file, $allowed_types))

{

die('Files of type' . $file . ' are not allowed to be uploaded.');

}

// Continue

更多信息

您可以在PHP.net documentation上阅读有关FILEINFO_MIME_TYPE的更多信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值