如何验证文件大小上传php mysql
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何验证文件大小上传php mysql相关的知识,希望对你有一定的参考价值。
我刚刚使用php + mysql,我有这个脚本将文件上传到服务器并将数据插入数据库。一切正常,但我不知道如何将文件大小限制为3MB。这是代码:
// limit file types
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp' , 'pdf' , 'doc' , 'ppt'); // valid extensions
$path = 'uploads/'; // upload directory
if(!empty($_POST['name']) || !empty($_POST['email']) || $_FILES['image'])
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// rename file to prevent rewrite existing files
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "File uploaded succesfully";
$name = $_POST['name'];
$email = $_POST['email'];
//include database configuration file
include_once 'db.php';
//insert form data in the database
$insert = $db->query("INSERT uploading (name,email,file_name) VALUES ('".$name."','".$email."','".$path."')");
}
}
else
{
echo 'File not uploaded, try again';
}
}
我会感激任何帮助。
答案
首先,以KB为单位获取文件大小:
$fileSize = $_FILES['image']['size'];
然后您可以将字节转换为MB,如下所示:
$fileSizeInMB = ($fileSize)/(1024*1024)
;
然后你可以检查这个$ fileSizeInMB是否大于3。
另一答案
您可以修改php.ini文件以设置允许上载的最大文件大小。
upload_max_filesize = 40M
或者您可以在脚本中设置它
$fileSize = $_FILES['image']['size'];
而不是使用if语句
if ($fileSize < 3000000) {
echo "this image cannot be uploaded";
}
插入脚本中。
<?php
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp' , 'pdf' , 'doc' , 'ppt'); // valid extensions
$path = 'uploads/'; // upload directory
if(!empty($_POST['name']) || !empty($_POST['email']) || $_FILES['image'] )
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size']
// get uploaded file extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// rename file to prevent rewrite existing files
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
// if condition to make sure filesize is less than 3000000 bytes, 3MB
if($fileSize < 3000000){ //php uses bytes so 3000000 is 3MB
if(move_uploaded_file($tmp,$path))
{
echo "File uploaded succesfully";
$name = $_POST['name'];
$email = $_POST['email'];
//include database configuration file
include_once 'db.php';
//insert form data in the database
$insert = $db->query("INSERT uploading (name,email,file_name) VALUES ('".$name."','".$email."','".$path."')");
}
} else {
echo 'Cannot upload file too large' ;
}
}
else
{
echo 'File not uploaded, try again';
}
}
?>
另一答案
$ _FILES是PHP中的全局变量和数组元素,包含名为的键
size
,这是您尝试上传的文件的大小,您可以在此关键元素上添加任何验证。
参考:http://php.net/manual/en/reserved.variables.files.php
以上是关于如何验证文件大小上传php mysql的主要内容,如果未能解决你的问题,请参考以下文章
ajaxFileUpload上传带参数文件及JS验证文件大小
如何使用 PHP 将大型 Excel 文件导入 MySql 数据库
linux+nginx+mysql+php系统修改文件上传大小限制