Appearance
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:
- Connect to your database using PHP.
- Create a form that allows the user to select and upload a file.
- Use the
move_uploaded_filefunction to move the uploaded file to a desired location on your server. - Use the
$_FILESarray to get the file name of the uploaded file. - Use an SQL
INSERTstatement 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.