In PHP, how can developers dynamically set the file name for uploaded files based on form input without compromising security?
When allowing users to upload files and dynamically set the file name based on form input, it is important to sanitize the input to prevent any malicious code injection. One way to do this is by using a combination of functions like `htmlspecialchars()` and `uniqid()` to generate a unique file name that is safe for storage on the server.
// Sanitize the input for the file name
$filename = htmlspecialchars($_POST['filename']);
// Generate a unique file name
$unique_filename = uniqid() . '_' . $filename;
// Move the uploaded file to the desired location with the unique file name
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $unique_filename);
Keywords
Related Questions
- What are the challenges of accessing and displaying the source code of a page after logging in using PHP?
- What are the best practices for using indexes in MySQL databases to improve the performance of queries in PHP?
- How can PHP developers efficiently extract specific parts of a string based on a delimiter?