PHP文件上传限制

时间:2014-03-11 19:05:17

标签: php

我想对上传的图片大小加以限制。 下面我有图像大小的条件。

if ($_FILES["upload_attachment"]["size"] < 25000)) // Max File Size: 25KB
  {
  echo "File size exceeds maximum.";
  }

我想在此代码中插入条件。

   if ( $_FILES ) {
    $files = $_FILES['upload_attachment'];
    foreach ($files['name'] as $key => $value) {
    if ($files['name'][$key]) {
    $file = array(
    'name' => $files['name'][$key],
    'type' => $files['type'][$key],
    'tmp_name' => $files['tmp_name'][$key],
    'error' => $files['error'][$key],
    'size' => $files['size'][$key]
    );

    $_FILES = array("upload_attachment" => $file);

    foreach ($_FILES as $file => $array) {
    $newupload = insert_attachment($file,$post->ID);
    }
    }
    }
    }

1 个答案:

答案 0 :(得分:0)

基本上,您希望在继续进行文件处理之前尽早检查,这样您就不会让服务器做任何工作,如果它不必要的话。

另外,FYI,上传大小以字节为单位,所以如果你想要25KB,它将是(25 * 1024)= 25600字节。

要合并这个条件,你可以这样做。它有点粗糙,所以我在关闭括号上添加了评论,注意哪些关闭了什么。 fe = foreach

if ( $_FILES ) {//if files exist

    if ($_FILES["upload_attachment"]["size"] < 25600) { // Max File Size: 25KB 

          //I would also recommend adding error handling early.
        if ($_FILES['filename']['error'] > 0){

            echo 'Error: ' . $_FILES['filename']['error'] . '<br />';

        } else { 

            $files = $_FILES['upload_attachment'];
            foreach ($files['name'] as $key => $value) {
                if ($files['name'][$key]) {
                    $file = array(
                    'name' => $files['name'][$key],
                    'type' => $files['type'][$key],
                    'tmp_name' => $files['tmp_name'][$key],
                    'error' => $files['error'][$key],
                    'size' => $files['size'][$key]
                    );
            $_FILES = array("upload_attachment" => $file);
                    foreach ($_FILES as $file => $array) {
                        $newupload = insert_attachment($file,$post->ID);
                    }//fe
                }//if
            }//fe
        }//if no errors (else)
    } //if size ok
    else {
        echo "File size exceeds maximum.";
    } 
}//if $_FILES