What are some best practices for handling file uploads and displaying content in textareas using PHP?
When handling file uploads in PHP, it is important to validate the file type and size before storing it on the server. When displaying content in textareas, make sure to properly sanitize the input to prevent any malicious code injection. Here are some best practices for handling file uploads and displaying content in textareas using PHP: **Handling file uploads:**
<?php
if($_FILES['file']['error'] == UPLOAD_ERR_OK) {
$file_name = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$allowed_types = array('jpg', 'jpeg', 'png');
$file_type = pathinfo($file_name, PATHINFO_EXTENSION);
if(in_array($file_type, $allowed_types) && $file_size < 5000000) {
move_uploaded_file($file_tmp, 'uploads/' . $file_name);
echo 'File uploaded successfully!';
} else {
echo 'Invalid file type or size!';
}
}
?>
```
**Displaying content in textareas:**
```php
<?php
if(isset($_POST['content'])) {
$content = htmlspecialchars($_POST['content']);
echo '<textarea>' . $content . '</textarea>';
}
?>
Related questions
-
regular expressions PHP documentation
-
PHP salt password hashing
-
URL file-access security risks PHP scripts