Skip to content

How to store file name in database, with other info while uploading image to server using PHP?

To store the file name in a database along with other information while uploading an image to a server using PHP, you can follow these steps:

  1. Connect to your database using PHP.
  2. Create a form that allows the user to select and upload a file.
  3. Use the move_uploaded_file function to move the uploaded file to a desired location on your server.
  4. Use the $_FILES array to get the file name of the uploaded file.
  5. Use an SQL INSERT statement to insert the file name and other relevant information into the database.

Here is an example of how this could be done:

Example of storing file name in database, with other info while uploading image to server using PHP

php
<?php
// Connect to the database (use environment variables or a config file in production)
$db = mysqli_connect('hostname', 'username', 'password', 'database_name');

// Check if the form has been submitted
if (isset($_POST['submit'])) {
  // Check for upload errors
  if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    die('Upload failed.');
  }

  // Validate file type and size
  $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
  $max_size = 5 * 1024 * 1024; // 5MB

  if (!in_array($_FILES['file']['type'], $allowed_types)) {
    die('Invalid file type.');
  }
  if ($_FILES['file']['size'] > $max_size) {
    die('File too large.');
  }

  // Get the file name and other information from the form
  $file_name = basename($_FILES['file']['name']);
  $file_type = $_FILES['file']['type'];
  $file_size = $_FILES['file']['size'];
  $other_info = $_POST['other_info'];

  // Ensure the uploads directory exists and is writable
  if (!is_dir('uploads')) {
    mkdir('uploads', 0755, true);
  }

  // Move the uploaded file to a desired location
  $upload_path = "uploads/" . $file_name;
  if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)) {
    die('Failed to move uploaded file.');
  }

  // Insert the file name and other information into the database using prepared statements
  $stmt = mysqli_prepare($db, "INSERT INTO table_name (file_name, file_type, file_size, other_info) VALUES (?, ?, ?, ?)");
  mysqli_stmt_bind_param($stmt, "ssis", $file_name, $file_type, $file_size, $other_info);
  mysqli_stmt_execute($stmt);
  mysqli_stmt_close($stmt);
}

// Display the form
echo '
<form action="upload.php" method="post" enctype="multipart/form-data">
  Select file: <input type="file" name="file"><br>
  Other information: <input type="text" name="other_info"><br>
  <input type="submit" name="submit" value="Upload">
</form>
';
?>

This code assumes that you have a database table with columns for file_name, file_type, file_size, and other_info. You can adjust the column names and the form fields as needed for your specific application.

Dual-run preview — compare with live Symfony routes.