What are some best practices for user management and file uploading in PHP?
Issue: When managing users and allowing file uploads in PHP, it is important to implement proper security measures to prevent unauthorized access and potential security vulnerabilities. Code snippet:
// User management
// Ensure user authentication before allowing access to sensitive information or actions
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit();
}
// File uploading
// Validate file type and size before allowing upload
$allowed_types = array('image/jpeg', 'image/png', 'image/gif');
$max_size = 5 * 1024 * 1024; // 5MB
if (in_array($_FILES['file']['type'], $allowed_types) && $_FILES['file']['size'] <= $max_size) {
// Process file upload
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
} else {
echo 'Invalid file type or size.';
}
Related Questions
- What are the considerations for maintaining consistency in formatting and content display when extracting PHPBB forum content for use in a different application or script?
- What is the correct way to output a variable in a hidden element in PHP?
- Are special characters like %, !, ?, >, - safe to include in INSERT or UPDATE statements in PHP, and how should they be handled for security?