how do I get this page error with this code?

-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"]);

    
asked by anonymous 16.06.2018 / 22:16

3 answers

2

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

    
16.06.2018 / 22:21
1

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

Also check that your files are writable in your project directory so they can create directories at runtime. I tested it in Linux 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 verify that the $ file variable is empty. This prevents you from having Warning: Illegal string offset 'tmp_name'

    
17.06.2018 / 04:55
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"]);
    
17.06.2018 / 04:41