0

I'm working on a gallery-upload-function with

  • jQuery Ajax
  • PHP

The whole gallery-function contains 3 parts:

Form as view_create-char.php

    <form id='gallery_upload' method='post' enctype='multipart/form-data'>
     <input type='file' name='file' id='file'>
     <input type='hidden' name='name' value='".$_GET['c']."' id='owner'>
     <input type='button' class='create_submit' value='Upload' 
     id='add_image_gallery'>
    </form>";

Ajax Script as main.js

$(document).ready(function(){

    $("#add_image_gallery").click(function(){

        var fd = new FormData();
        var files = $('#file')[0].files[0];
        var name = $('#owner').attr("value");
        fd.append('file',files);
        fd.append('name',name);


        $.ajax({
            url: 'includes/gallery_upload.php',
            type: 'post',
            data: fd,
            contentType: false,
            processData: false,
            success: function(response){
                if(response != 0){
                    alert('file  uploaded');


                }else{
                    alert('file not uploaded');
                }
            },
        });
    });
});

PHP-Script as gallery_upload.php

<?php
include 'dbh.inc.php';

        $owner = $_POST['name'];
        $file = $_FILES['file'];
        $fileName = $_FILES['file']['name'];
        $fileTmpName = $_FILES['file']['tmp_name'];
        $fileSize = $_FILES['file']['size'];
        $fileError = $_FILES['file']['error'];
        $fileType = $_FILES['file']['type'];

        $fileExt = explode('.', $fileName);
        $fileActualExt = strtolower(end($fileExt));
        $allowed = array('jpg', 'jpeg', 'png', 'gif');
        $fileNameNew = uniqid('', true).'.'.$fileActualExt;
        $fileDestination = 'uploads/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);

        $sql = "INSERT INTO 
        characters_gallery (owner, image) VALUES ('$owner', 
        '$fileNameNew');";
        $result = mysqli_query($conn, $sql);

The goal is to upload the image with Ajax and insert two values inside the characters_gallery-table. First, the owner of the table, then the name of the actual image, generated by the PHP Script. This works.

But the actual file is not getting moved to the designated folder /uploads by move_uploaded_file(). It remains empty although the table in my database is filled with the two values $owner and $fileNamenew. What confuses me is that before I used this Ajax-Script this PHP-Script to move files to the uploads-folder worked fine. It doesn't work with the script though.

I'm grateful for any help

Edit --- Reaction to warning concerning SQL Injections:

I'm not sure if I'm using this edit like I'm supposed to do but it is an additional information. If I'm wrong, please delete my edit.

I tried to add prepared statements and wondered if I eliminated any greater risk of SQL Injection:

<?php
include_once 'characterfunctions.inc.php'; 
include 'dbh.inc.php';

        $owner = mysqli_real_escape_string($conn, $_POST['name']);
        $file = mysqli_real_escape_string($conn, $_FILES['file']);
        $fileName = $_FILES['file']['name'];
        $fileTmpName = $_FILES['file']['tmp_name'];
        $fileSize = $_FILES['file']['size'];
        $fileError = $_FILES['file']['error'];
        $fileType = $_FILES['file']['type'];

        $fileExt = explode('.', $fileName);
        $fileActualExt = strtolower(end($fileExt));
        $allowed = array('jpg', 'jpeg', 'png', 'gif');
        $fileNameNew = uniqid('', true).'.'.$fileActualExt;
        $fileDestination = '../uploads/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);

        $sql = "INSERT INTO characters_gallery (owner, image) VALUES (?, ?);";
        $stmt = mysqli_stmt_init($conn);
        if (!mysqli_stmt_prepare($stmt, $sql)) {
            echo "SQL Error";
        } else {
            mysqli_stmt_bind_param($stmt, "ss", $owner, $fileNameNew);
            mysqli_stmt_execute($stmt);
        }
        $result = mysqli_query($conn, $sql);
3
  • Can you check the permissions of the uploads folder, this sometimes causes a problem Commented Jan 21, 2019 at 19:39
  • Your code looks fine, have you given proper permissions to the uploads folder? Commented Jan 21, 2019 at 19:39
  • Warning: You are wide open to SQL Injections and should really use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input, especially that which comes from the client side. Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Commented Jan 21, 2019 at 20:15

2 Answers 2

1

First of all, track the result of move_uploaded_file and if false, do not do the next steps.

Regarding why it may be fail, it cloud be:

  • permission issue - so let's check the permissions of the uploads directory that should be writable from PHP.
  • $_FILES['file'] is not a valid file - so check with is_uploaded_file($fileTmpName) and also check the variable $_FILES['file']['error']
Sign up to request clarification or add additional context in comments.

Comments

0

Try adding ../ to $fileDestination :

$fileDestination = '../uploads/'.$fileNameNew;

It looks like you are moving the photos to includes/uploads but in your notes it says uploads is located in /uploads.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.