'Upload a file Using PHP and JavaScript

I selected a image using:

<input type="file" id="pimg" name="pimg" accept='image/*'/>  

My javascript code:

p_img =document.getElementById("pimg").value;  
param= 'pn='+p_img;  
xmlhttp.open("GET","add_prod.php?"+param,false);  
xmlhttp.send();  

My php code:

p_img=$_GET['img'];
$con = mysqli_connect('localhost', 'admin', 'admin', 'products');
$sql="INSERT INTO prod (img) VALUES ('$p_img')";
if (!mysqli_query($con,$sql))
{
    die('Error: ' . mysqli_error($con));
}  

This will store only the name of the file. But i want to copy the file from pc to directory. Its necessary to use Javascript as I'm using complete add product to pass values using AJAX



Solution 1:[1]

Use POST (form) to send data to the php file.

With $_FILES["pimg"]["tmp_name"] you can move the uploaded file (with the php function move_uploaded_file to you webserver.

Link to PHP Function http://php.net/manual/de/function.move-uploaded-file.php

Solution 2:[2]

You can upload the file without page refresh using simple JavaScript and PHP. Using JavaScript, the file would be passed to the PHP file and using move_uploaded_file() function file would be uploaded to the server.

The live demo and source code would found from here - Upload file using JavaScript and PHP

Solution 3:[3]

xmlhttp.open("GET","add_prod.php?"+param,false);  

i think open method's parameter must contain true.

Solution 4:[4]

Create index.html file

<!DOCTYPE html>
<html>
<body>
    <form action="upload_file.php" method="post" enctype="multipart/form-data">
        <label for="file">Filename:</label>
        <input type="file" name="file" id="file"><br>
        <input type="submit" name="submit" value="Submit">
    </form>
</body>
</html>

Create Php file upload_file.php

<?php

if ($_FILES["file"]["error"] > 0) {
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
}

?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 q0re
Solution 2 JoyGuru
Solution 3 K55555
Solution 4 Black