Solved

php getimagesize not working

Posted on 2016-09-25
13
93 Views
Last Modified: 2016-11-08
Hi:
I'm trying to upload an image file to the server as shown in the directory structure and script below.
Yet it fails to put the file into the sub-directory.
I've looked through the Q&As but cannot get this to work with me.
Any ideas guys?
Thanks.

<?php
error_reporting(E_ALL);

/*
Directory structure:
/web/cr-app-epub/getimagesize-test.php
/web/cr-app-epub/initial-uploads-media/(expect image file to be here)
*/

if(isset($_POST['submit_image']))
{
    echo "file = ".$_FILES["fileToUpload"]["name"]."<br>";

    $uploadOk = 1;
    $target_dir = "initial-uploads-media/";
    $target_file = $target_dir.basename($_FILES["fileToUpload"]["name"]);
    echo "target_file = ".$target_file."<br>";
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    echo "imageFileType = ".$imageFileType."<br>";

    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    echo "check = ".$check['mime']."<br>";
    if ($check === false)
    {
        echo "Invalid image file<br>";
        $uploadOk = 0;
        goto end;
    }
    else
    {
        echo "File is an image: ".$check['mime']."<br>";
    }

    list($width, $height, $type, $attr) = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    echo "width, height, type, attr = ".$width.", ".$height.", ".$type.", ".$attr."<br>";
    if ($width > 400 OR $height > 400)
    {
        echo "The maximum width and height of your image has been exceeded. Please upload images below H400xW400px in size<br>";        ##
        $uploadOk = 0;
        goto end;
    }
    else
    {
        echo "values known<br>";
    }

    end:
    echo "uploadOk = ".$uploadOk;
    exit();
}
?>

<!DOCTYPE html>
<html>
<body>

<form method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image file" name="submit_image">
</form>

</body>
</html>

<?php
/*
Output:
file = image.jpg
target_file = initial-uploads-media/image.jpg
imageFileType = jpg
Warning: getimagesize(): Filename cannot be empty in ..../web/cr-app-epub/getimagesize-test.php on line 19 check =
Invalid image file
uploadOk = 0

Comment: The image file is not in the 'initial-uploads-media/' sub-directory
*/
?>

Open in new window

0
Comment
Question by:krotb
13 Comments
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
Have you made sure you have 'write' permissions in that directory?
0
 
LVL 21

Assisted Solution

by:Kim Walker
Kim Walker earned 375 total points
Comment Utility
Are you sure the code you've posted is exactly the same as the code you're running. The first error suggests that there is a getimagesize function execution on line 19. Yet line 19 of the code you've posted just echos the value of $imageFileType. (By the way, the value of $imageFileType is being extracted from the file extension in the path, not from the actual file.

So assuming that line 21 of the code you've posted is line 19 of the code you're running, it would be prudent to confirm that a file was actually uploaded. Replace line 21 with the following:
    if (is_uploaded_file($_FILES["fileToUpload"]["tmp_name"]) ) {
	    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
	    echo "check = ".$check['mime']."<br>";
	} else {
	    exit("Image failed to upload. Error = {$_FILES['fileToUpload']['error']}<br>");
	}

Open in new window

There are many factors that would prevent the file from being uploaded which are described here. Are you sure that the file you're trying to upload is not larger than upload_max_filesize or post_max_size? How large is the file you're testing with? If you are exceeding either of these limits, the upload will proceed as normal until the limit is exceeded at which point it will terminate without error. The process will appear to succeed. In fact it will succeed but without the uploaded file attached. Perhaps try a smaller file.

It may also be helpful to dump your fileToUpload array to see what's there. Add this near the top of your code:
echo "<pre>\n";
var_dump($_FILES['fileToUpload']);
echo "</pre>\n";

Open in new window

You may also want to check the Apache log file to see if an error is being recorded there.

EDITED to add bold font weight.
0
 

Author Comment

by:krotb
Comment Utility
Here's the correct output (I believe I added rems):

file = Jay_Mantri_EmoRoad.jpg
target_file = initial-uploads-media/Jay_Mantri_EmoRoad.jpg
imageFileType = jpg
Warning: getimagesize(): Filename cannot be empty in ..../web/cr-app-epub/getimagesize-test.php on line 21 check =
Invalid image file
uploadOk = 0
0
 

Author Comment

by:krotb
Comment Utility
With your changes, Kim:

/*
Same file as original:
array(5) {
    ["name"]=>
    string(22) "Jay_Mantri_EmoRoad.jpg"
    ["type"]=>
    string(0) ""
    ["tmp_name"]=>
    string(0) ""
    ["error"]=>
    int(1)
    ["size"]=>
    int(0)
}

file = Jay_Mantri_EmoRoad.jpg
target_file = initial-uploads-media/Jay_Mantri_EmoRoad.jpg
imageFileType = jpg
Image failed to upload. Error = 1
uploadOk = 0

Much smaller file:
array(5) {
    ["name"]=>
    string(19) "flowers-250x166.png"
    ["type"]=>
    string(9) "image/png"
    ["tmp_name"]=>
    string(14) "/tmp/phpu6QRiW"
    ["error"]=>
    int(0)
    ["size"]=>
    int(239292)
}

file = flowers-250x166.png
target_file = initial-uploads-media/flowers-250x166.png
imageFileType = png
check = image/png
File is an image: image/png
width, height, type, attr = 250, 166, 3, width="250" height="166"
values known
uploadOk = 1
*/

Open in new window


I didn't limit the file size. So why would that prevent the upload?
0
 

Author Comment

by:krotb
Comment Utility
php.ini had post_max_size set at 4m and upload_max_filesize set at 2m. The file was 4.34m, so neither would allow it to upload. So I reset both in php.ini to 8m and ran the script again uploading the large file, but it still failed ..
array(5) {
  ["name"]=>
  string(22) "Jay_Mantri_EmoRoad.jpg"
  ["type"]=>
  string(0) ""
  ["tmp_name"]=>
  string(0) ""
  ["error"]=>
  int(1)
  ["size"]=>
  int(0)
}

file = Jay_Mantri_EmoRoad.jpg
target_file = initial-uploads-media/Jay_Mantri_EmoRoad.jpg
imageFileType = jpg
Image failed to upload. Error = 1
uploadOk = 0

Open in new window


Any ideas why that would be? (btw I'm on a shared remote linux server, so I'm not sure how I'd get an Apache log file).
0
 
LVL 21

Assisted Solution

by:Kim Walker
Kim Walker earned 375 total points
Comment Utility
Have you confirmed your php.ini modifications? Error = 1 should indicate that the file size exceeded upload_max_filesize. Try displaying that value on your page:
echo "<pre>\n";
echo 'upload_max_filesize = '.ini_get('upload_max_filesize')."\n";
var_dump($_FILES['fileToUpload']);
echo "</pre>\n";

Open in new window

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
What type of control panel does your hosting provider use? There should be some tool in the hosting control panel to view the log or at least view errors. For example, cPanel has an Errors button under the Metrics section.
0
 

Author Comment

by:krotb
Comment Utility
upload_max_filesize = 2M
array(5) {
  ["name"]=>
  string(22) "Jay_Mantri_EmoRoad.jpg"
  ["type"]=>
  string(0) ""
  ["tmp_name"]=>
  string(0) ""
  ["error"]=>
  int(1)
  ["size"]=>
  int(0)
}

On the site you recommended, I noticed this comment (from 18 days ago):
"[Editor's note: to be more precise, MAX_FILE_SIZE can't exceed PHP_INT_MAX before PHP 7.1.]
Please note that the field MAX_FILE_SIZE cannot exceed 2147483647. Any greater value will lead to an upload error that will be displayed at the end of the upload"

My shared server uses PHP 5.2, archaic I know. I'm guessing this must be the issue.

The error log must be requested, so I've done so.
0
 
LVL 21

Assisted Solution

by:Kim Walker
Kim Walker earned 375 total points
Comment Utility
According to the first line of the feedback, upload_max_filesize is still 2M. So the modification you made to php.ini didn't stick.
upload_max_filesize = 2M

Open in new window

Regarding MAX_FILE_SIZE, this is a hidden input you add to your HTML to invoke a custom maximum file size for a particular form. You haven't included this in your HTML and there is no need to at this point.
0
 

Author Comment

by:krotb
Comment Utility
I believe the 2M issue will be resolved when I launch on a managed server and can define the system limits myself. Meanwhile, for dev purposes I can manage with <2M.

Thanks guys. Much appreciated.

PS I don't see the usual points message, only the assist/best one.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 125 total points
Comment Utility
Here's my teaching example showing how to upload files and visualize errors, if any.  The relevant man pages are marked in the comments.
<?php // demo/upload_example.php
/**
 * Demonstrate how to upload one or more files, using HTML5 and PHP
 *
 * REQUIRED: Man Page References
 * http://www.w3schools.com/tags/att_input_multiple.asp
 *
 * http://php.net/manual/en/reserved.variables.files.php
 * http://php.net/manual/en/features.file-upload.php
 * http://php.net/manual/en/features.file-upload.post-method.php
 * http://php.net/manual/en/features.file-upload.common-pitfalls.php
 * http://php.net/manual/en/features.file-upload.errors.php
 * http://php.net/manual/en/features.file-upload.multiple.php
 *
 * http://php.net/manual/en/function.move-uploaded-file.php
 *
 * IMPORTANT: If dealing with large files
 * http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
 * http://php.net/manual/en/ini.core.php#ini.post-max-size
 * http://php.net/manual/en/info.configuration.php#ini.max-input-time
 */
error_reporting(E_ALL);

// MAY NOT BE NEEDED - CHECK PHP_INI PARAMETERS FOR YOUR TIMEZONE
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('storage' DIRECTORY)
$storage = 'storage';
if (!is_dir($storage))
{
    mkdir($storage);
}

// ESTABLISH THE BIGGEST FILE SIZE WE WILL ACCEPT - ABOUT 8 MB
$max_file_size = 8 * 1024 * 1024;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE WILL ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
, 'doc'
, 'docx'
)
;

// ARRAY OF ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( UPLOAD_ERR_OK         => "Success!"
, UPLOAD_ERR_INI_SIZE   => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, UPLOAD_ERR_FORM_SIZE  => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, UPLOAD_ERR_PARTIAL    => "The uploaded file was only partially uploaded"
, UPLOAD_ERR_NO_FILE    => "No file was uploaded"
, 5                     => "UNDEFINED ERROR #5"
, UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder"
, UPLOAD_ERR_CANT_WRITE => "Cannot write file to disk"
, UPLOAD_ERR_EXTENSION  => "A PHP extension stopped the file upload"
)
;


// IF WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
if (!empty($_POST))
{
    echo "<h2>Results: File Upload</h2>" . PHP_EOL;

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH IN THE REQUEST
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>";

    // REORGANIZE THE CONTENTS OF $_FILES SO WE CAN USE AN ITERATOR MORE SENSIBLY
    $nf = count($_FILES['userfile']['name']);
    while ($nf)
    {
        $nf--;
        $my_uploaded_files[$nf]['name']     = $_FILES['userfile']['name'][$nf];
        $my_uploaded_files[$nf]['type']     = $_FILES['userfile']['type'][$nf];
        $my_uploaded_files[$nf]['tmp_name'] = $_FILES['userfile']['tmp_name'][$nf];
        $my_uploaded_files[$nf]['error']    = $_FILES['userfile']['error'][$nf];
        $my_uploaded_files[$nf]['size']     = $_FILES['userfile']['size'][$nf];
    }

    // ITERATE OVER THE COLLECTION OF UPLOADED FILES
    foreach ($my_uploaded_files as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == UPLOAD_ERR_NO_FILE) continue;

        // IF THERE ARE ERRORS
        if ($error_code != UPLOAD_ERR_OK)
        {
            $error_message = $errors[$error_code];
            trigger_error("Upload error code: $error_code: $error_message", E_USER_WARNING);
            continue;
        }

        // SYNTHESIZE THE NEW FILE NAME
        $f_type = explode('.', basename($my_uploaded_file['name']));
        $f_type = end($f_type);
        $f_type = trim(strtolower($f_type));

        $f_name = explode('.', basename($my_uploaded_file['name']));
        $f_name = current($f_name);
        $f_name = trim(strtolower($f_name));

        // SERVER PATH TO THE NEW FILE
        $my_file_path
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $storage
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // URL PATH TO THE NEW FILE
        $my_file_url
        = $storage
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts))
        {
            trigger_error("$f_type Not allowed", E_USER_WARNING);
            continue;
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_file_path))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_file_path))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file_url</i></b> already exists." . PHP_EOL;

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d\THis');
                $my_bak = $my_file_path . '.' . $now . '.bak';
                if (!copy($my_file_path, $my_bak))
                {
                    trigger_error("Backup Failed for $my_file_url", E_USER_WARNING);
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_file_path))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten." . PHP_EOL; }
        if ($upload_success == 1) { echo "<br/><b>$my_file_url</b> has been saved." . PHP_EOL; }
        if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>" . PHP_EOL; }
        if ($upload_success < 0)  { echo "<br/><b>ERROR: $my_file_url NOT SAVED - SEE WARNING FROM <i>move_uploaded_file()</i></b>" . PHP_EOL; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded." . PHP_EOL;
            if (!chmod ($my_file_path, 0755))
            {
                echo '<br/>chmod(0755) FAILED: fileperms() = ';
                echo substr(sprintf('%o', fileperms($my_file_path)), -4);
            }
            echo '<br/>See the file: <a target="_blank" href="' . $my_file_url . '">' . $my_file_url . '</a><br/>' . PHP_EOL;
        }
    } // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
} // END ACTION SCRIPT


// CREATE THE HTML FORM USING HEREDOC NOTATION
$form = <<<EOF
<h2>Upload file(s)</h2>
<!--
    SOME IMPORTANT THINGS TO NOTE ABOUT THIS FORM...
    REQUIRES THE HTML5 DOCTYPE
    ENCTYPE= ATTRIBUTE IN THE HTML <FORM> TAG
    MAX_FILE_SIZE HIDDEN CONTROL MUST PRECEDE THE FILE INPUT CONTROLS
    INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN _FILES ARRAY
    ABSENCE OF ACTION= ATTRIBUTE IN <FORM> TAG CAUSES POST TO SAME URL
-->
<form name="UploadForm" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
<p>
Find the file(s) you want to upload and click the "Upload" button below.
</p>

<input type="file" multiple name="userfile[]" size="80" />

<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
<input type="submit" value="Upload" />
</form>
EOF;

echo $form;

Open in new window

0
 

Author Comment

by:krotb
Comment Utility
Ray, thank you. That's awesome!
0

Featured Post

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now