Create folder and upfile during same file

Asked

Viewed 103 times

2

I want to insert a news along with the image file in a single post, the problem is that I would like to create a folder with the news ID where the image will be stored. It’s happening that the Insert is working but the upload no, some light or easier way to do this?

$imagem = $_FILES['imagem'];

$sqlInsert = "INSERT INTO noticias (titulo,categoria,conteudo) VALUES (:titulo,:categoria,:conteudo)";
$stmt = DB::prepare($sqlInsert);
$stmt->bindParam("titulo", $titulo);
$stmt->bindParam("categoria", $categoria);
$stmt->bindParam("conteudo", $conteudo);
$stmt->execute();

$ultimoid = DB::lastInsertId();
$dir = "../imagens/$ultimoid";
$pasta = mkdir("$dir", 0775);
if(is_dir("$dir")){
  if($arquivo != "none") {
    if (copy($_FILES['imagem']['tmp_name'], $dir . $_FILES['imagem']['name'])) {
    $arquivo1 = $_FILES['imagem']['name'];
    $sqlInsert = "UPDATE noticias SET imagem=:imagem WHERE idnoticia=$ultimoid";
    }
}

remembering that I made a summary of the code only with the parts that I believe is where is giving problem, any doubt put the whole code

  • On the line that has copy, do not need to use something like "joinPaths" ? the path is right ?

  • in theory whether the directory was created the path is right

1 answer

2

You have placed the attribute in the HTML: enctype="multipart/form-data", it is necessary to upload via POST.

Check here for an example:

<form method="post" action="salvar-alguma-coisa.php" enctype="multipart/form-data">
    <input type="file" name="arquivo">
    <input type="submit" value="enviar">
</form>

Jsfiddle

  • ta all cetinho the biggest problem is creating the folder with the same news ID

Browser other questions tagged

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