Загрузка изображений в MySql с использованием PHP - PullRequest
1 голос
/ 01 мая 2020

Я пытаюсь загрузить изображение через контактную форму, чтобы сервер попал в определенную папку и пора визуализировать базу данных. Когда я отправляю форму, я получаю эту ошибку:

Файл является изображением - image / jpeg. Примечание. Неопределенный индекс: fileToUpload в C: \ xampp \ htdocs \ Web \ form. php в строке 68. Примечание. form. php в строке 68 Примечание: неопределенный индекс: изображение в C: \ xampp \ htdocs \ Web \ form. php line 82

Это код: HTML :

  <div class="container-form">
     <form action="form.php" method="post" enctype="multipart/form-data">
        <div class="image">
       Прикачете ваша снимка! (максимален размер 20МБ)<br>
       <input type="file" name="image" id="image" size="40" required="true" />
    </div>
        <div class="submit">
           <input type="submit" name="submit" value="Изпращане" id="submit" />          
        </div>
     </form>
  </div>

PHP:

// Connect to MyQSL
$link = mysqli_connect("localhost", "root", "", "form");
$link->query("SET NAMES 'UTF8'");

// Check our connection
if ($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 20000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" ) {
    echo "Sorry, only JPG, JPEG and PNG files are allowed.";
    $uploadOk = 0;
}

// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$date = mysqli_real_escape_string($link, $_REQUEST['date']);
$image = mysqli_real_escape_string($link, $_REQUEST['image']);

// Insert our data
$sql = "INSERT INTO form (name, date, image) VALUES ('$name', '$date', '$image')";
// Print response from MyQSL
if (mysqli_query($link, $sql))
{
    echo "<div class='echo-complete'> <div class='echo-text'> Формата беше приета успешно. Благодарим ви.";
}
else
{
echo "<div class='echo-error'> <div class='echo-text'> ГРЕШКА: Не може да се изпълни $sql." .         
mysqli_error($link);
}

// Close our connection
mysqli_close($link);

База данных: столбец изображения имеет тип BLOB

1 Ответ

0 голосов
/ 02 мая 2020
    <div class="container-form">
        <form method="post" enctype="multipart/form-data">
           <div class="image">
               <input type="file" name="image" id="image" size="40" required="true" />
           </div>
           <div class="submit">
               <input type="submit" name="submit" value="Upload" id="submit" />          
           </div>
        </form>
    </div>

       <!--Now we will connect to the database.-->

<?php
// define file 
if (isset($_POST["submit"])) {
    $fname  = $_FILES["image"]["name"];
    $fsize  = $_FILES["image"]["size"];
    $ferror = $_FILES["image"]["error"];
    $ftype  = $_FILES["image"]["type"];
    $ftmp   = $_FILES["image"]["tmp_name"];

    // Get the extension of the file and verify if we support it
    $allowed          = array(
        "png",
        "jpeg",
        "jpg",
        "gif"
    ); //make sure it's not capital letters.
    $actual_extension = explode(".", $fname); // Get what we have after the . on the file name
    $extension        = end($actual_extension); // make sure we got the extension
    //check if the extension is supported.
    if (!in_array($extension, $allowed)) {
        echo "Sorry! We do not support this format" . "<br>";
    }

    // Now check if we have a file error, else: upload
    if ($ferror == 1) { // Check if we have an error
        echo "Something went wrong" . "<br>";
    } else {
        if ($fsize > 100000) { // check if the uploaded file matches the size we allow.
            echo "Your file is BIG" . "<br>";
        } else {
            $new_name = uniqid('', true); // we will give the uploaded file a unique id 
            $path     = "uploads/" . $new_name . "." . $extension; // Define the path and upload the file with new name+ "." + the file extension.
            if (move_uploaded_file($ftmp, $path)) {
                echo "file uploaded succesfully";
            } else {
                echo "something went wrong with the file upload";
            }
        }
    }

    $link  = mysqli_connect("localhost", "root", "", "sadik");
    $query = "INSERT INTO `table` (`image`) VALUES ($new_name) ";
    mysqli_query($link, $query);
    // ...
}
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...