Home > Enterprise >  PHP. I want to allow user to add file to form, from any folder
PHP. I want to allow user to add file to form, from any folder

Time:04-03

Here is my form enter image description here

It gets the url of the image, and save it in the database. But it can show only files saved in folder "uploads", so I want to allow user to add file from any place of the PC. Help please Maybe I can do smth in the store.php?

Create.php

<form style="width: 25em; text-align: center; align-items: center;" action="store.php" method="POST">
     
  <div >
    <label for="exampleInputEmail1" >Name</label>
    <input type="text" name="name"  id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Name">
   
  </div>
  <div >
    <label for="exampleInputPassword1" >Surname</label>
    <input type="text" name="surname"  id="exampleInputPassword1" placeholder="Surname">
  </div>

 <div >
    <label for="inputPatronym" >Patronym:</label>
    <input type="text" name="patronym" placeholder="Patronym">
  </div>

                         

  <div >
    <label for="inputPatronym" >Biography:</label>
    <input type="text" name="description" placeholder="Biography">
  </div>


<div >
  <label for="formFile" >Image</label>
  <input  name="userfile" type="file" id="formFile" accept=".img,.png,.jpeg,.jpg,.bmp">
</div>

<div >
    

  <button type="submit"  >Save</button>


  </div>
     <a  href="/postati.php" role="button">Return</a>
</form>
</body>
</html>

Store .php

<?php 
    require_once __DIR__ . "/database/pdo.php";

    $Name = $_POST['name'];
    $Surname = $_POST['surname'];
    $Patronym = $_POST['patronym'];
    $Description = $_POST['description'];
    $userfile = $_POST['userfile'];
    
   
    $sql = "INSERT INTO `peoples` (`Name`, `Surname`, `Patronym`, `Description`, `userfile`) VALUES (:name, :surname, :patronym, :description, :userfile)";

    $params = [
        "name" => $Name,
        "surname" => $Surname,
        "patronym" => $Patronym,
        "description" => $Description,
        "userfile" => $userfile,
    ];

    $prepare = $pdo->prepare($sql);
    $prepare->execute($params);

    $pdo->lastInsertId();
    $lastInsertId=$pdo->lastInsertId();


header("Location: /postati.php")
    
?>

View


<div >
  <img src="uploads/<?=$people['userfile']?>" width="250px" height="350px" >
</div>

I tried to move the file with move_uploaded_file, but then the other variables are not saving.

CodePudding user response:

You are missing the enctype="multipart/form-data" declaration in your form. You need this if you want a file upload form.

<form enctype="multipart/form-data" action="store.php" method="POST">
  • Related