2013-08-19 72 views
2

嗨,我想限制文件上傳如果文件大小超過特定的大小 但我的問題是如果文件的大小超過最大大小我沒有得到任何信息 關於文件在PHP服務器我的代碼在HTML如下,請幫我爲什麼我 沒有得到的信息。驗證文件上傳在php

<?php echo $form->create('Add', array('id'=>'addFile', 'enctype'=>'multipart/form-data', 'url'=>'/content/upload?path='.$contentItem['url_path']),array(   
    'inputDefaults' => array('label' => false))); ?>  
<div class="_100 formText"> 
    <label>Section&nbsp;: </label> 
    <input type="input" value="<?php echo (!empty($contentItem['display_text'])) ? $contentItem['display_text'] : $contentItem['parent_disp_txt'] ;?>" name="data[Add][section]" readonly="readonly"/> 
</div> 
<div class="clear" style="height: 5px;"></div> 
<div class="_100 formText"> 
    <label>File Name&nbsp;: </label> 
    <input type="input" value="" name="data[Add][file]" class="filePath"/> 
</div> 
<div class="clear" style="height: 5px;"></div> 
<div class="_99 formText"> 
    <label>File Description&nbsp;: </label> 
    <textarea rows="3" cols="" name="data[Add][description]" class="description" style="resize:none;"></textarea> 
</div> 
<div class="clear" style="height: 15px;"></div> 
<div class="_99 formText"> 
    <label>Select File to Upload: </label> 
    <input type="file" name="data[Add][upload]" class="filesToUpload" id="file"/> 
</div> 
<?php echo $html->tags['formend'];?>  
+0

請參閱:[如何在PHP中限制文件上傳類型文件大小?](http://stackoverflow.com/questions/9153224/how-to-limit-file-upload-type-file-size-in- php) – Itay

+0

[限制上傳swf文件時的檢查條件]可能的重複(http://stackoverflow.com/questions/10151960/limiting-the-checking-condition-while-uploading-swf-files)如果文件大小超過 – Baba

+0

使用ini_set文件定義的最大大小不提交 – user2590163

回答

1
if(isset($_FILES['uploaded_file'])) { 
    $errors  = array(); 
    $maxsize = 2097152; 
    $acceptable = array(
     'application/pdf', 
     'image/jpeg', 
     'image/jpg', 
     'image/gif', 
     'image/png' 
    ); 

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) { 
     $errors[] = 'File too large. File must be less than 2 megabytes.'; 
    } 

    if(!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) { 
    $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.'; 
} 

if(count($errors) === 0) { 
    move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file'); 
} else { 
    foreach($errors as $error) { 
     echo '<script>alert("'.$error.'");</script>'; 
    } 

    die(); //Ensure no more processing is done 
} 
} 

試試這個代碼。