skyguy skyguy - 4 months ago 18x
PHP Question

Upload image file (NOT selected via form, just within a folder) to mysql via PHP?

I'm just unclear how to format this- in the past I have have users upload an image they select from their computer via a form and javascript like so:

$("#uploadimage").on('submit',(function(e) {

url: "../php/upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds


Which sends the file to a php script:

$validextensions = array("jpeg", "jpg", "png");
$maxsize = 99999999;
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < $maxsize)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {

$size = getimagesize($_FILES['file']['tmp_name']);
$type = $size['mime'];
$imgfp = fopen($_FILES['file']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['file']['name'];

$sql = new mysqli("localhost","username","password","sqlserver");
$imgfp64 = base64_encode(stream_get_contents($imgfp));
$update = "UPDATE sqlserver.imageblob set image='".$imgfp64."', image_type='".$type."', image_name='".$name."', image_size='".$size."' where user_id=".$account['id'];

And then I have been able to display the image like this and echoing HTML:

$imgdata = $array['image']; //store img src
$src = 'data:image/jpeg;base64,'.$imgdata;

But now I need to upload an image file that i have STORED already in a folder i.e.
NOT an uploaded file from a form.

Ideally I would write:

$imgfile = "../images/image1.png"

Then plug this into my php in place of
but I do not know how to properly write this out. I am new to mysql and am getting error messages just passing a file name like above.

How can I upload an image that I already have in my folder to mysql table?

What I have tried:

enter image description here


You can use DirectoryIterator:

Save this file to your images folder and run it:


    $validextensions = array("jpeg", "jpg", "png");
    $dir = new DirectoryIterator(dirname(__FILE__));
    foreach ($dir as $fileinfo) {
        if (!$fileinfo->isDot()) {

            $extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION)); /* GET EXTENSION OF FILE */

            if(in_array($extension, $validextensions)){ /* IF FILE IS IMAGE; JPEG, JPG, OR PNG */

                $check = $sql->query("SELECT * FROM image_table WHERE image_col = ?"); /* REPLACE NECESSARY TABLE AND COLUMN NAME */
                $check->bind_param("s", $fileinfo->getFilename());
                $noofrows = $check->num_rows;

                if($noofrows == 0){ /* IF IMAGE NAME IS NOT YET IN THE DATABASE */
                    /* INSERT FILE NAME TO DATABASE */
                    $stmt = $sql->query("INSERT INTO image_table (image_col) VALUES (?)"); /* REPLACE NECESSARY TABLE AND COLUMN NAME */
                    $stmt->bind_param("s", $fileinfo->getFilename());



Above will save the image name to your database.

And when you want to display the images, just run this query:

$getimg = $sql->prepare("SELECT image_col FROM image_table"); /* REPLACE NECESSARY TABLE AND COLUMN NAME */
    echo '<img src="images/'.$image.'">';