我是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';
}
}
我会尽力帮助您。
答案 0 :(得分:0)
首先,以KB为单位提取文件大小:
$fileSize = $_FILES['image']['size'];
然后您可以将字节转换为MB,如下所示:
$fileSizeInMB = ($fileSize)/(1024*1024)
;
然后,您可以检查此$ fileSizeInMB是否大于3。
答案 1 :(得分:0)
您可以修改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';
}
}
?>
答案 2 :(得分:0)
$ _ FILES是PHP中的全局变量和一个数组元素,并包含名为
的键。 size
,
这是您要上传的文件的大小,您可以在此关键元素上添加任何验证。