添加限制php上传图片

时间:2014-08-25 21:38:27

标签: php jquery ajax

我使用php ajax脚本在我的网站上传图片,并且它没有上传图片的限制。 我希望用户只能上传例如3张图片。如何在我的代码中添加此限制? 这是我上传图片的php代码:

 if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
      {
     $vpb_upload_image_directory = "uploads/";

  $vpb_allowed_extensions = array("gif", "jpg", "jpeg", "png");


foreach($_FILES as $file)
{
    /* Variables Declaration and Assignments */
    $vpb_image_filename = basename($file['name']);
    $vpb_image_tmp_name = $file['tmp_name'];;
    $vpb_file_extensions = pathinfo(strtolower($vpb_image_filename), PATHINFO_EXTENSION);

    //New file name
    $random_name_generated = time().rand(1234,9876).'.'.$vpb_file_extensions;

    if($vpb_image_filename == "") 
    {
        //Browse for a photo that you wish to use
    }
    else
    {
        if (in_array($vpb_file_extensions, $vpb_allowed_extensions)) 
        {
            if(move_uploaded_file($vpb_image_tmp_name, $vpb_upload_image_directory.$random_name_generated)) 
             {
                 //Display Uploaded Files 
                 $image .= '
                 <div class="vpb_wrapper" style="padding:10px;">
                 <img src="'.$vpb_upload_image_directory.$random_name_generated.'" class="vpb_image_style" />
                 </div>';

                 //$image .= '<div class="vpb_wrapper" style="padding:10px; text-decoration:none;">'.$vpb_image_filename.' uploaded</div>';

             }
        }
        else
        {
            // Do not upload files which are not in the allowed file array
        }

       }
    }
    //Display the files
    if($image != "") echo $image;
    }
     ?>

1 个答案:

答案 0 :(得分:0)

在javascript中,你可以做这样的事情,

$(document).ready(function(){
$('#photoUploader').click(function(){
      $('#photoUI').toggle('slow');
});
var ctr = 1;
$('#add').click(function(){
    if(ctr < 3)
    { 
        $('#ulPhoto').append("<li><input type='file' name='file[]' onchange='loadPreview(this,"+ctr+")' id='photo"+ctr+"' /><br /><img id='img"+ctr+"' src='#' alt='' style='width:100px' /><input type='text' autocomplete='off' name='caption[]' id='caption"+ctr+"' placeholder='ID Number' /></li>");
        ctr++;
    }
    else
    {
      alert('Only 3 Images Allowed at a time');
    }
});
});

<强> HTML

<div id="photoUI" style="display:none; height: auto">
   <ul id="ulPhoto">
     <li>
     <input type="file" name="file[]" id="photo0" />
     <br />
     <img id="img0" src="#" alt="" style="width:100px" />
     <input type="text" autocomplete="off" name="caption[]" onchange="loadPreview(this,0)" id="caption0" placeholder="Default ID Number" readonly disabled />
     </li>
   </ul>
   <span id="add" style="cursor:pointer">Add More...</span>
</div>