What are best practices for handling file uploads and sessions in PHP?
When handling file uploads in PHP, it is important to ensure that the uploaded file is valid and secure. This can be done by checking the file type, size, and ensuring proper file permissions. Additionally, when managing sessions in PHP, it is crucial to securely store session data and regenerate session IDs to prevent session hijacking.
// Handling file uploads
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$file_name = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
// Check file type
$file_type = mime_content_type($file_tmp);
if ($file_type != 'image/jpeg' && $file_type != 'image/png') {
echo 'Invalid file type.';
}
// Check file size
if ($file_size > 1048576) { // 1MB
echo 'File size is too large.';
}
// Move uploaded file to desired directory
move_uploaded_file($file_tmp, 'uploads/' . $file_name);
}
// Handling sessions
session_start();
session_regenerate_id(true);
$_SESSION['user_id'] = 123;