在php中验证文件上传

时间:2013-08-19 08:13:21

标签: php html

嗨我正在尝试限制文件上传,如果文件大小超过特定大小   但我的问题是如果文件大小超过最大大小我没有得到任何信息   关于php服务器中的文件我在HTML中的代码如下,请帮我解释为什么我   没有得到这些信息。

<?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'];?>    

1 个答案:

答案 0 :(得分:3)

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
}
}

试试这段代码。