user1801060
user1801060

Reputation: 2821

Print/debug cause of upload error in PHP

I'm a PHP newbie and have written a script to process form uploads. It works for small files(less than 1Mb). However when I try to upload an ~4Mb pdf file it returns an error message. What am I doing wrong?

PS: I ran php_info, got the value of "upload_tmp_dir" and set it to a directory owned by the apache process(www-data)

My client-side code is

<form action="upper.php" method="post" enctype="multipart/form-data"> 
    <input type="file" name="myFile"><br>
    <input type="submit" value="Upload">
</form>

Upper.php contains

define("UPLOAD_DIR", "/var/www/html/upload/");

if (!empty($_FILES["myFile"])) {
    $myFile = $_FILES["myFile"];

    if ($myFile["error"] !== UPLOAD_ERR_OK) {
        echo "Error is " . $myFile["error"];
        //echo "<p>An error occurred.</p>";
        exit;
    }    

    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

    // don't overwrite an existing file
    $i = 0;
    $parts = pathinfo($name);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

    // preserve file from temporary directory
    $success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . $name);
    if (!$success) {
        echo "<p>Unable to save file.</p>";
        exit;
    }

    // set proper permissions on the new file
    chmod(UPLOAD_DIR . $name, 0644);
}

Upvotes: 1

Views: 446

Answers (2)

Avishake
Avishake

Reputation: 470

You ned to set values in php.in file.
Open the file, Find upload_max_filesize and post_max_size lines.
Change this two value. (M= MB)

; Maximum allowed size for uploaded files.
upload_max_filesize = 20M
; Must be greater than or equal to upload_max_filesize
post_max_size = 20M

Restart the sever for effect.
Note:

  1. You can set any number. But not use any decimal value.
  2. Open the php.ini file in NOTEPAD. Don't user wordpad or any word processor.

Upvotes: 1

Krzysztof Duszczyk
Krzysztof Duszczyk

Reputation: 693

Most probably you have wrong config in you php.ini file.

You need to set

; Maximum allowed size for uploaded files.
upload_max_filesize = 40M

; Must be greater than or equal to upload_max_filesize
post_max_size = 40M

its already described here: PHP change the maximum upload file size

Upvotes: 1

Related Questions