0

I am building a PHP application where a new user has to upload an avatar. I managed to save the uploaded file path into my database, but now I have to move the uploaded image from the temporary to the permanent directory, which is the folder 'avatars'. I have searched through many answers on the same problem but haven't managed to find a working one. Since I am really new to PHP I'm gonna need some help for a working solution.

I have also tried copy() instead of move_uploaded_file with no luck.

HTML:

<div class="input-form">
  <label for="avatar">Kies een profielfoto</label>
  <input type="file" id="avatar-input" name="avatar" accept="image/*" onchange="loadFile(event)">
  <img id="output" width="150" />
  <input type="submit" id="submit-btn" name="vervolledig-submit" value="START">
</div>

PHP:

if(!empty($_POST)){

    $fileSize = $_FILES["avatar"]["size"];

    if($fileSize < 2000000){

        $fileSizeOk = true;

    }else{

        throw new Exception("Je profielfoto heeft een grotere file size dan is toegelaten (max 2MB)");
        $imgSizeOk = false;

    }

    $img = $_FILES["avatar"]["name"];

    if($imgSizeOk == true){

        move_uploaded_file($_FILES["avatar"]["tmp_name"], "avatars/$img");

    }
}

EDIT: was asked to share my JS code:

  1. a function that shows a preview of the uploaded picture:
let loadFile = function(event) {
    let image = document.getElementById('output');
    image.src = URL.createObjectURL(event.target.files[0]);
}; 
  1. Suggested solution with AJAX
$('#submit-btn').on('click', function() {
    var file_data = $('#avatar-input').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('avatar', file_data);
    alert(form_data);                             
    $.ajax({
        url: 'profielVervolledigen.php', // point to server-side PHP script 
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // display response from the PHP script, if any
        }
     });
});

with the following php code:

if(!empty($_POST)){
    if ( 0 < $_FILES['avatar']['error'] ) {
        echo 'Error: ' . $_FILES['avatar']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['avatar']['tmp_name'], 'avatars/' . $_FILES['avatar']['name']);
    }
}

the alert gives [object FormData]

Thanks for any help

bok
  • 17
  • 3
  • `move_uploaded_file` returns false or true? – user3783243 Apr 26 '20 at 15:25
  • do you have permissions to write in that directory? try a `var_dump(is_writable('avatars/'));` – the_nuts Apr 26 '20 at 15:25
  • Check this: https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php – Salim Ibrohimi Apr 26 '20 at 15:35
  • @user3783243 I don't really know, when I try to check it with: `if(move_uploaded_file($_FILES["avatar"]["tmp_name"], "avatars/$img")){ echo "true"; }else{ echo "false"; }` it doesnt return anything at all @the_nuts I do have permission, it returns true – bok Apr 26 '20 at 16:06
  • @SalimIbrogimov . I tried this code, I only changed the ID's, folder path, and input name ('file' to 'avatar'). Since I don't know AJAX, is there anything else i have to change to fit my code ? the alert `alert(php_script_response)` says: `[object FormData]`, sorry, I'm really a noob at coding :) edit: I also changed url path to my php page – bok Apr 26 '20 at 16:14
  • Please, also add you relevant JS code. Thanks! – Salim Ibrohimi Apr 26 '20 at 16:16
  • @SalimIbrogimov I edited my post! – bok Apr 26 '20 at 16:27
  • Is this filename is correct: profielVervolledigen.php? – Salim Ibrohimi Apr 26 '20 at 16:34
  • Also, instead of alert(form_data); try "console.log(form_data);" and check your browser's console for it's output. – Salim Ibrohimi Apr 26 '20 at 16:35
  • `var_dump(move_uploaded_file($_FILES["avatar"]["tmp_name"], "avatars/$img"))` gives back what? If you don't get a result than your code isn't executing there, or you have a fatal error. Is the status code 500? – user3783243 Apr 26 '20 at 16:51
  • I don't get any result here – bok Apr 26 '20 at 17:03

0 Answers0