Verification error (if)

Asked

Viewed 50 times

2

I am developing a system to send videos to a database, for this, too, I want to send complementary materials in mysql.

Inside the html form, you find:

<div class="form-group ml-0 pl-0 mt-4">
          <label for="exampleFormControlFile1">Enviar material complementar (opcional)</label>
          <input type="file" name="arquivo">

Where is the input to send the file.

This form sends to register video.php;

<?php
include("conexao.php");

$nome_video = $_POST['nome_video'];
$disciplina  = $_POST['disciplina'];
$link_video  = $_POST['link_video'];
$coment_video  = $_POST['coment_video'];
$arquivo = $_FILES["arquivo"];

if(!isset($arquivo['arquivo'])){

    $extensao = strtolower(substr($_FILES['arquivo']['name'], -4)); //pega a extensao do arquivo
    $novo_nome = md5(time()) . $extensao; //define o nome do arquivo
    $diretorio = "upload/"; //define o diretorio para onde enviaremos o arquivo
    move_uploaded_file($_FILES['arquivo']['tmp_name'], $diretorio.$novo_nome); //efetua o upload

    $sql_logar = "INSERT INTO video_monitor (titulo_video, disciplina, link_video, coment_video, arquivo, data) 
    VALUES('$nome_video', '$disciplina', '$link_video', '$coment_video', '$novo_nome', NOW())";
    $exe_logar = mysqli_query($conection, $sql_logar) or die (mysqli_error($conection));
  } 
  if(!empty($arquivo['arquivo'])){
$sql_logar = "INSERT INTO video_monitor (titulo_video, disciplina, link_video, coment_video, arquivo, data)
VALUES ('$nome_video', '$disciplina', '$link_video', '$coment_video', 'Nenhum arquivo', NOW())";

$exe_logar = mysqli_query($conection, $sql_logar) or die (mysqli_error($conection));
  }

?>

The error is that whether or not selecting a file, it is using if:

   if(!isset($arquivo['arquivo'])){

Being that, in case the user does not send a file it would have to go to the if:

   if(!empty($arquivo['arquivo'])){

How can I solve the problem?

1 answer

3


In the documentation PHP: Uploading files with the POST method is written:

If no file is selected in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as "None" (none).

It means that $_FILES['arquivo'] will always be initialized and when testing !isset($_FILES['arquivo']) regardless of whether the user has sent a file or not, the result will be true.

To verify that the file was sent by sending by HTTP POST use the function is_uploaded_file() with argument $_FILES['userfile']['tmp_name'] whose is the temporary name with which the uploaded file was stored on the server.

if (is_uploaded_file($_FILES['arquivo']['tmp_name'])){
  //...Aqui vai o código caso tenha sido feito o upload do arquivo
} else {
  //...Aqui vai o código caso Não tenha sido enviado um arquivo
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.