-1

so I'm trying now for hours to store an Image in my Database, but I just don't get it. Currently I'm trying to get the image via file upload from the user, then store in the database as a BLOB. So practically storing the binary data of the image in the database.

<form action="editor.php" class="createBlogForm" autocomplete="off">
                    <input type="text" name="title" placeholder="Title" class="title">
                
                <?php include 'editor.html'; ?>
            </div>
            <div id="catAndSave">
                <select name="categoriesOnCreate" class="categoriesOnCreate">
                    <option value="option1">Option 1</option>
                    <option value="option2" selected="selected">Anderes</option>
                </select>
                <div id="coverImageDiv">
                    <label for="inputTag">
                        Select Cover Photo <br/>
                        <i class="fa fa-2x fa-camera"></i>
                        <input id="inputTag" type="file" name="image"/>
                        <br/>
                        <span id="imageName"></span>
                    </label>
                </div>
                  <script>
                    let input = document.getElementById("inputTag");
                    let imageName = document.getElementById("imageName")
            
                    input.addEventListener("change", ()=>{
                        let inputImage = document.querySelector("input[type=file]").files[0];
            
                        imageName.innerText = inputImage.name;
                    })
                </script>
                <button type="submit" class="blogSave" onclick="save();">Save</button>
                </form>

So this is my form, I know very unstructured and things, but it doesn't have to be.

When you click on the button this Code should be executed:

<script>
                function save(){
                    var xmlhttp = new XMLHttpRequest();
                    var content = document.getElementsByClassName('content')[0].innerHTML;
                    var title = document.getElementsByClassName('title')[0].value;
                    var category = document.getElementsByClassName('categoriesOnCreate')[0].value;
                    var data = new FormData();
                    data.append("content", content);
                    data.append("title", title);
                    data.append("category", category);
                    const queryString = window.location.search;
                    const urlParams = new URLSearchParams(queryString);
                    const id = urlParams.get('id');
                    xmlhttp.open("POST","editor.php?id=" + id ,true);
                    xmlhttp.send(data);
                    window.location = "http://192.168.56.104/sodablog/editor.php";
                };
            </script>

Doesn't quite work tho, because it never executes this, because i wrote in my form: action="editor.php". But that's not the point and doesn't matter, cause that's not the problem.

The problem is that PHP doesn't get my file to upload it. Here:

<?php
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
    session_start();
    include 'dbconnect.php';

    $content = $_POST['content'];
    $title = $_POST['title'];
    $category = $_POST['category'];

    date_default_timezone_set('Europe/Rome');
    $date = date("YmdHis"); 

  
    $status = 'error'; 
    if(!empty($_FILES["image"]["name"])) { 
        // Get file info 
        $fileName = basename($_FILES["image"]["name"]); 
        $fileType = pathinfo($fileName, PATHINFO_EXTENSION); 
         
        // Allow certain file formats 
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            $image = $_FILES['image']['tmp_name']; 
            $imgContent = addslashes(file_get_contents($image));
         
            // Insert image content into database 
            $insert = $db->query("INSERT INTO `blog_posts`(`coverImage`) VALUES ('$imgContent');");
             
            if($insert){ 
                $status = 'success'; 
                $statusMsg = "File uploaded successfully."; 
            }else{ 
                $statusMsg = "File upload failed, please try again."; 
            }  
        }else{ 
            $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        } 
    }else{ 
        $statusMsg = 'Please select an image file to upload.'; 
    } 

 
// Display status message 
echo $statusMsg;

    $sql = "INSERT INTO `blog_posts`(`created_at`, `last_updated_at`, `content`, `title`, `category`) 
    VALUES('$date', '$date', '$content', '$title', '$category');";
    $execution = mysqli_query($conn, $sql) or die("Fehler");
?>

For testing you could just here give these lines:

$content = $_POST['content'];
    $title = $_POST['title'];
    $category = $_POST['category'];

a value so no error appears because of these.

But I still get the error: Please select an image file to upload.

I'm new to PHP and JavaScript and Web-development in general, so sorry for the chaotic code.

  • 1
    I’m not a `php` dev but just want to share with you that you should never store image blob in your db. Use any object storage provider to store any file and simply save the unique object `key` in your db to access it later on. – devpolo Feb 19 '23 at 10:07
  • @devpolo thanks, but it's just really not important cause it's for a silly school project and I just want i to be done – theCrashinator Feb 19 '23 at 10:11
  • 1
    addslashes could corrupt the image data. This is completely the wrong way to put any data into a sql query from php. It's insecure (due to the possibility of sql injection) and also unreliable, and/or with the potential to corrupt the data. Learn to use prepared statements and parameters to do this correctly- hopefully your tutor will see the value in that too, if they know what they are talking about. See https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement to learn what to do. Your other sql query is done incorrectly too. – ADyson Feb 19 '23 at 10:33
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Feb 19 '23 at 17:39

1 Answers1

1

You are not sending your image from your frontend to your backend.

function save(){
...    
var image = document.getElementById('inputTag').value;
...
var data = new FormData();
...
data.append(image.name,image.files[0]);
...
M-JM
  • 93
  • 6