上传带有类型验证的图像文件时出错并保存在文件夹中并在数据库中保存路径

问题描述:

$conn = mysqli_connect("localhost","root","","vfssite");


if (isset($_POST['submit']))
{

    $filetemp = $_FILES['file']['tmp_name'];
    $filename = $filepath . basename($_FILES["fileToUpload"]["name"]);
    $filepath = "uploads/galleryuploadwedding/".$filename;
    $uploadOk = 1;
    $imageFileType = pathinfo($filename,PATHINFO_EXTENSION);

    move_uploaded_file($filetemp, $filepath);

    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) 
    {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }

    $sql = "INSERT INTO gallerywedding (imagename) values ('$filename')";
    if ($result = mysqli_query($conn, $sql))
    {
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
    } else 
    echo "Error";
}

@Yuva Kishore here is the code which work. It is similar to your code and you can differentiate here. I have user PHP MYSQLI PREPARED STATEMENT AGAINST SQL INJECTION WHEN YOU ARE SEND DATA WITH INPUT FIELDS.

HTML CODE :

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" >
    <input type="submit" name="submit" >
</form>

PHP CODE TO UPLOAD IMAGE AND INSERT INTO DATABASE

 <?php
    $servername = "localhost";
    $username = "root";
    $password = "admin";
    $dbname = "demo";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    if(isset($_POST['submit'])){
        $file_name = $_FILES['file']['name'];
        $filename_tmp = $_FILES['file']['tmp_name'];

        $path = 'uploads/galleryuploadwedding/';
        $imageFileType = pathinfo($file_name,PATHINFO_EXTENSION);

        if($imageFileType == "jpg" || $imageFileType == "PNG" || $imageFileType == "jpeg"
        || $imageFileType == "gif") {

            //NOW MOVE UPLOADED FILE TO PATH
            if(move_uploaded_file($filename_tmp,$path.$file_name)){
                echo "Success";

                //NOW INSERT THE IMAGE NAME TO DATABASE
                //USER MYSQLI PREPARED STATEMENT AGAINST SQL INJECTION 
                $sql = $conn->stmt_init();

                $query = "INSERT INTO gallerywedding (imagename) VALUES (?)";

                if($sql->prepare($query)){
                    $sql->bind_param('s',$file_name);
                    if($sql->execute()){
                        echo "Successfuly inserted the image to database";
                    }
                }
                else
                {
                    echo "Error".$conn->error;
                }
            }
        }
        else
        {
            echo $imageFileType."<br>";
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        }
    }
?>

Feel free to ask questions comment below my post