Error on upload imagem with php and mysqli

32 views Asked by At

I'm trying to upload a image to my database with PHP, I've checked multiple aspects and nothing works and I don't know what is wrong. I generate a string to give a random to the image and I've check and $target_file = "../uploads/dsfjnsklsdlkfmsd.png".

From the print_r($_FILES); below I get the following:

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

I'll leave my code here:

<?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);
    }
}

On the statement of move_uploaded_file() goes to the else.

0

There are 0 answers