使用php和mysqli上传图像时出错

时间:2020-01-08 17:34:35

标签: php file-upload

我正在尝试使用PHP将图像上传到我的数据库,我已经检查了多个方面,但没有任何效果,而且我不知道出了什么问题。我生成了一个字符串,为图像提供了随机性,并检查了$target_file = "../uploads/dsfjnsklsdlkfmsd.png"

从下面的print_r($_FILES);中,我得到以下信息:

Array ( [imagem_capa] => Array ( [name] => filexpto.png [type] => image/png [tmp_name] => C:\Windows\Temp\php25C3.tmp [error] => 0 [size] => 11229 ) )

我将代码留在这里:

<?php

include_once "../connection/connection.php";

//random string
function generateRandomString($length = 10)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

//connection
$link = new_db_connection();
$stmt = mysqli_stmt_init($link);

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

$file_name = generateRandomString() . "." . $imageFileType;
$target_file = $target_dir . $file_name;

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

if (file_exists($target_file)) {
    echo "Desculpa, essa imagem já existe.";
    $uploadOk = 0;
    return;
}

if ($_FILES["imagem_capa"]["size"] > 500000) {
    echo "A imagem é demasiado grande";
    $uploadOk = 0;
    return;
}

if (
    $imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif"
) {
    echo "Carrega uma imagem jpg, jpeg, png ou gif, por favor.";
    $uploadOk = 0;
    return;
}

if ($uploadOk == 0) {
    header("Location: ../main.php?erro=2");
} else {        
    if (move_uploaded_file($_FILES["imagem_capa"]["tmp_name"], $target_file)) {
        //does insert

    } else {
        print_r($_FILES);
    }
}

move_uploaded_file()上转到其他。

0 个答案:

没有答案