0

我有以下 php 代码,它允许用户上传图像。如何修改我的代码,以便对上传的图像大小有限制(比如说最大 20 k)。这是我的代码。

<?php
/// another code ///
if($_POST)
{   

    if(!isset($_FILES['mFile']))
    {
        //required variables are empty
        die("Please add a image");
    }

    if($_FILES['mFile']['error'])
    {
        //File upload error encountered
        die(upload_errors($_FILES['mFile']['error']));
    }

    $FileName           = strtolower($_FILES['mFile']['name']);
    $auto                           = mysql_real_escape_string($_POST['auto']);
    $FileType           = $_FILES['mFile']['type']; //file type
    $FileSize           = $_FILES['mFile']["size"]; //file size


            if(move_uploaded_file($_FILES['mFile']["tmp_name"], $UploadDirectory . $NewFileName ))
         {


        mysql_query("INSERT INTO posts (title, post, img_name) VALUES ('$FileTitle', '$postURL', '$NewFileName')");

        die('Thank you for your submission.');

   }else{
        die('There seems to be a problem. please try again.');
   }
}
/// another code ///
?>
4

4 回答 4

1

设置成这样

<?php
ini_set('post_max_size', '20K');
ini_set('upload_max_filesize', '20K'); 
于 2013-11-13T10:05:17.130 回答
1

有几种方法可以做到这一点:

以编程方式:

ini_set('post_max_size', '20K');
ini_set('upload_max_filesize', '20K');

通过 php.ini:

post_max_size = 20K
upload_max_filesize = 20K

通过.htaccess:

php_value upload_max_filesize 20K
php_value post_max_size 20K
于 2013-11-13T10:06:36.570 回答
1

这是上传、更改表和变量的图片大小使用限制的个人示例

$picture = $_FILES['pic']['name'];
$picsize = $_FILES['pic']['size'];
$pictype = $_FILES['pic']['type'];

if(!empty($picture)){
        if(($pictype == 'image/gif') || ($pictype == 'image/jpeg') || ($pictype == 'image/pjpeg') || ($pictype == 'image/png') && ($picsize > 0) && ($picsize <= 30000 )){
            if($_FILES['pic']['error'] == 0)
                {
                $target = UPLOADPATH . $user_name;
                echo $target;
                if(move_uploaded_file($_FILES['pic']['tmp_name'], $target))
                {
                    $query2 = "UPDATE users SET profile_image = '{$user_name}' WHERE user_name = '{$user_name}'";
                    $result2 = mysql_query($query2);
                }
                }
            else{
                echo 'upload failed';
            }


        }
        elseif(($pictype != 'image/gif') && ($pictype != 'image/jpeg') && ($pictype != 'image/pjpeg') && ($pictype != 'image/png')){
            echo 'incorrect file type';
        }
        elseif(($picsize <= 0) || ($picsize > 30000 ))
        {
            echo 'incorrect file size';
        }
于 2013-11-13T10:08:17.997 回答
-2

php.ini 中有一个设置,您可以在其中限制它。有些人为此目的使用隐藏字段,但我不喜欢它。

于 2013-11-13T10:04:54.100 回答