1
<?php

require_once "core/init.php";

if(isset($_FILES['file'])){
    $file = $_FILES['file'];

    // File properties
    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];

    // Work out the file extension
    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));

    $allowed = array('jpg', 'png');

    if(in_array($file_ext, $allowed)) 
    {
        echo 'Your file will be processed shortly, thank you.';
    }

    if($file_error == true) 
    {
        echo 'Failed to upload file';
    }

    if($file_size <= 2097152) {

        $file_name_new = uniqid('', true) . '.' . $file_ext;
        $file_destination = 'profilepictures/' . $file_name_new;

        if(move_uploaded_file($file_tmp, $file_destination));
            echo $destination;
    }
}
?>

Simple problem, just frustrated at the moment. I'm trying to get it to echo Failed to upload file on a failed upload, but it's doing it on a successful upload and failed upload. I get both messages, the successful one and failed one on good uploads, but when it's a bad upload I only get the failed one.

1
  • Try dumping $file_error on a successful upload - see what it says? Commented Nov 11, 2015 at 17:18

2 Answers 2

1

$file_error will return a value (and will therefore be true) even if the upload is successful. See PHP page.

Change your check to:

if($file_error !== UPLOAD_ERR_OK){ //...

Or

if($file_error !== 0){ //...
Sign up to request clarification or add additional context in comments.

1 Comment

Same thing is happening as I commented on the other answer I have
1

Try replacing if($file_error == true) by if($file_error != 0)

Here is the explanation : http://php.net/manual/en/features.file-upload.errors.php

7 Comments

I've actually done this method already, it doesn't echo my message with the ! If I remove it, it will echo my message, but also shows up with the successful upload message on good uploads.
Where is the successful message ?
if(in_array($file_ext, $allowed)) { echo 'Your file will be processed shortly, thank you.'; }
Of course it will be shown, for example if your png file is transfert but it too heavy, it will validate the in_array test but not the != 0 test.
Well it was here and it still wasn't working right, it took place of echo $destination if(move_uploaded_file($file_tmp, $file_destination)); { echo $destination; }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.