0

I am uploading files from a form to a folder in database using the following code. Now i want to add one text field to add some title to that file and save it database.Currently i am uploading files in upload folder but i want to save the title and path in to database table, so that i can retrieve this later from frontend.

Thanks for the help :)

<?php
$allowedExts = array("gif", "pdf", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "application/gif")
|| ($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/jpg")
|| ($_FILES["file"]["type"] == "application/ppdf")
|| ($_FILES["file"]["type"] == "application/x-png")
|| ($_FILES["file"]["type"] == "application/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Edited by pritaeas: Moved.

2
Contributors
1
Reply
14
Views
4 Years
Discussion Span
Last Post by diafol
1

This isn't effective:

$extension = end(explode(".", $_FILES["file"]["name"]));

I think you can use:

$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

Also, you may get better file headers with finfo_* functions.

However, there's no way to make absolutely certain that each file is what they purport to be. So just be aware that headers/mimes can be spoofed and extensions can be anything you want them to be of course.

With regard to your issue, then you just collect the data with regard to $_FILES and $_POST from your form and place that data into your MySQL table. Something like:

$title = $_POST['title'];
$path = $uploaddir . '/' . $filename;
$user_id = $_SESSION['login_id'];

$mysqli = new mysqli("localhost", "username", "password", "dbname");

$stmt = $mysqli->stmt_init();
if ($stmt->prepare("INSERT INTO `files` (`file_title`, `file_path`, `user_id`) VALUES (?, ?, ?)")) 
{
   $stmt->bind_param("ssd", $title, $path, $user_id);
   $stmt->execute();
   $stmt->close();
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.