How do I get this page error with this code?

Asked

Viewed 57 times

-2

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

<?php
if ($_SERVER["REQUEST_METHOD"]==="POST"){
    $file  = isset($_FILES["file"])?$_FILES["file"]:"";
}
$dir ="upload4";

if(!is_dir($dir)){
   mkdir($dir);
    echo "Pasra criada com sucesso";
}

move_uploaded_file($file["tmp_name"],$dir.DIRECTORY_SEPARATOR.$file["name"]);

inserir a descrição da imagem aqui

  • 1

    In ternary operator could put a exit if no file exists, so the code stops and shows no error

  • where Exit would be located?

3 answers

2

Put a "@" in front of the line to hide the error but it is not very recommended. The best way was to use one isset

  • but I’m already using the isset

  • Line 17: move_uploaded_file(isset($file["tmp_name"]),$dir.DIRECTORY_SEPARATOR. isset($file["name"]));

  • Line 17 Method @ (not recommended): @move_uploaded_file($file["tmp_name"],$dir.DIRECTORY_SEPARATOR. $file["name"]);

1

You can do something like this:

if ($_SERVER["REQUEST_METHOD"]==="POST" && isset($_FILES["file"])){
    //Se o método for post e houver um arquivo atribui o arquivo à variável
    $file = $_FILES["file"];
} else {
    //Se não mostra algo na tela e para o código
    echo "Método não é POST ou n]ao existe um arquivo";
    exit;
}

$dir ="upload4";

if(!is_dir($dir)){
    mkdir($dir);
    echo "Pasra criada com sucesso";
}

move_uploaded_file($file["tmp_name"],$dir.DIRECTORY_SEPARATOR.$file["name"]);

1

Try declaring your variable $file with global scope. It must be undefined because its first use happens within an if.

Also make sure your files are writable in your project directory so they can create directories at runtime. I tested it on Linux environment and it worked.

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <button type="submit">Enviar</button>
</form>
<?php
$file = "";
if ($_SERVER["REQUEST_METHOD"]==="POST"){
    $file  = isset($_FILES["file"])?$_FILES["file"]:"";
}
$dir ="upload4";

if(!is_dir($dir)){
   mkdir($dir);
    echo "Pasra criada com sucesso";
}

if (!empty($file)) {
move_uploaded_file($file["tmp_name"],$dir.DIRECTORY_SEPARATOR.$file["name"]);
}

Also put an if to check that the $file variable is empty. This prevents you from having Warning: Illegal string offset 'tmp_name'

Browser other questions tagged

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