restricting the uploading files size in php

2019-08-16 18:02发布

问题:

I am working with multiple file upload in PHP and I also fixed an upload limit of 10MB using the following HTML commands in an upload form PHP file:

   <input type="hidden" name="MAX_FILE_SIZE" value="10000000"> 
   <input id="infile" type="file" name="infile[]" multiple="true" />

In the PHP file that takes care of upload function I was initially expecting that if I try to upload a file of size greater than 10MB then the function call statement

   move_uploaded_file($_FILES['infile']['tmp_name'][$i], $dir . $fPath);

will fail and I can show an "Error upload file of size less than 10MB" message. But it didnt happen. It was trying to upload and it didnt display any error message as expected.

So I tried to restrict the file size specifically in the code by using the if statement as:

  if ($_FILES["infile"]["size"][$i]<10000000) 
    {
       move_uploaded_file($_FILES['infile']['tmp_name'][$i], $dir . $fPath);
    }
  else
    echo "error";

But still it doesnt echo error as expected. Can anyone please point out the mistake I am doing here?

回答1:

You can add the following line to your target script that handle your form:

ini_set('upload_max_filesize', '10M');

Or if you can access your php.ini, just change the following :

upload_max_filesize = 10M

Manual page : http://php.net/manual/en/ini.core.php



回答2:

Try this

<?php
if(isset($_POST["file_uploaded"])){
    $f_id= $_GET["id"]; 
    $dir_name="dir_hal_".$f_id; 
    $u=0; 
    if(!is_dir($dir_name))
    {
        mkdir($dir_name); 
    }
    $dir=$dir_name."/"; 
    $file_realname = $_FILES['infile']['name'];
    $c=count($_FILES['infile']['name']);
    for($i = 0;$i<$c;$i++) 
    {
        $ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1); 
        $fname = substr($_FILES['infile']['name'][$i],0,strpos($_FILES['infile']['name'][$i], "."));
        $fPath = $fname."_(".substr(md5(rand() * time()),0,4).")".".$ext"; 
        if($_FILES["infile"]["size"][$i]>10000000)
        {
            echo 'File uploaded exceeds maximum upload size.';
        }
        else{
            if(move_uploaded_file($_FILES['infile']['tmp_name'][$i], $dir . $fPath)) 
            {
                $u=$u+1;
                echo "Upload is successful\n";
            }
            else 
            {
                echo "error\n"; 
            }
        }
    }
    if($u==$c)
    {
        echo "count is correct";
    }
}
?>