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

时间:2017-05-28 10:39:51

标签: php image validation

$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";
}

1 个答案:

答案 0 :(得分:0)

@Yuva Kishore这里是有效的代码。它类似于您的代码,您可以在这里区分。当您使用输入字段发送数据时,我有用户PHP MYSQLI准备对SQL注入的声明。

HTML CODE:

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

PHP代码上传图片并插入数据库

 <?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.";
        }
    }
?>

随时在我的帖子下面提问题评论