how to get a file from an html input (in a form) to a php file for processing

Viewed 54

so, this is really hard to phrase, but I'm trying to use jQuery to move the file of an input element to a php file to put it into a message.

here's the code

HTML:

<form name="message" action="">
  <input name="usermsg" type="text" id="usermsg"/>
  <input name="userimg" type="file" id="userimg" accept="image/*"/>
  <input name="submitmsg" type="submit" id="submitmsg" value="Send"/>
</form>

jQuery:

$(document).ready(function () {
  $("#submitmsg").click(function () {
    var clientmsg = $("#usermsg").val();
    var clientimg = $("#userimg").val();
  $.post("post.php", { text: clientmsg, img: clientimg });
    $("#usermsg").val("");
    return false;
  });
//other stuff here
});

PHP:

$text = $_POST['text'];
$img = $_POST['img'];
    $text_message = "<div class='msgln'><span class='chat-time'>".date("m-d, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars(preg_replace('/\pM/u', '', $text)))."<br><br>".$img."</div><!--". $_SESSION['ipAddr'] ."-->

";
        file_put_contents('log.html', $text_message, FILE_APPEND | LOCK_EX);

If I add no file, it posts the message as usual (username and text), but if I add a file it says C:\fakepath\[file name and extension] note: fakepath is not a filler -- that's actually what it returns.

1 Answers

Please replace your js code and check again.

$(document).ready(function () {
  $("#submitmsg").click(function (e) {

        e.preventDefault();

        var myFormData = new FormData();
        myFormData.append('text',$('#usermsg').val());
        myFormData.append('img',$('#userimg').get(0).files[0]); // Here's the important bit

        $.ajax({
            url: 'post.php',
            type: 'POST',
            data: myFormData,
            dataType: 'json',
            mimeType: 'multipart/form-data', // this too
            contentType: false,
            cache: false,
            processData: false,
            success: function(data){
                $("#usermsg").val("");
                return false;

            },
            error: function(error){
                console.log(error);
            }
        });

    });

});

php code:

$text = isset($_POST['text']) ? $_POST['text'] : '';
$img = $_FILES['img']['name'];
$target_file = basename($_FILES["img"]["name"]);
$name = isset($_SESSION['name']) ? $_SESSION['name'] : '';

// upload image in your root folder
if(move_uploaded_file($_FILES["img"]["tmp_name"], $target_file)) {
    
}

$text_message = "<div class='msgln'><span class='chat-time'>".date("m-d, g:i A")."</span> <p><b class='user-name'>".$name."</b></p> ".stripslashes(htmlspecialchars(preg_replace('/\pM/u', '', $text)))."<br><br><img src='".$img."' alt=''></div>";

// if you want to previous file delete.
if(file_exists('log.html')){
    unlink('log.html');
}


file_put_contents('log.html', $text_message, FILE_APPEND | LOCK_EX);

echo $img;
Related