What are best practices for handling file uploads and storing file names in a database using PHP to ensure efficient and secure image management on a website?
When handling file uploads and storing file names in a database using PHP, it is important to sanitize user input to prevent SQL injection attacks and validate file types to prevent malicious uploads. Additionally, it is recommended to store files in a secure directory outside the web root to prevent direct access. Finally, generate unique file names to prevent overwriting existing files and ensure efficient image management.
// Handle file upload
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$file_name = uniqid() . '_' . $_FILES['file']['name'];
$upload_path = '/path/to/secure/directory/' . $file_name;
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)) {
// Store file name in database
$stmt = $pdo->prepare("INSERT INTO files (file_name) VALUES (?)");
$stmt->execute([$file_name]);
echo "File uploaded successfully!";
} else {
echo "Failed to upload file.";
}
} else {
echo "Error uploading file.";
}
Related Questions
- What is the correct syntax for applying chmod to a newly created file in PHP?
- What steps can be taken to ensure that a table can be modified without encountering access restriction issues in PHPMyAdmin?
- What PHP functions or libraries can be utilized to manipulate images and add text or codes to them dynamically for download?