What are some best practices for PHP developers to follow when creating a user profile system with image uploads in a community website?
Issue: When creating a user profile system with image uploads in a community website, PHP developers should follow best practices to ensure security, efficiency, and user experience. This includes properly validating and sanitizing user inputs, securely storing uploaded images, and implementing image resizing to optimize loading times.
// Validate and sanitize user inputs
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Securely store uploaded images
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile);
// Resize uploaded image
$sourceFile = $targetFile;
$targetFileResized = $targetDir . "resized_" . $_FILES["image"]["name"];
list($width, $height) = getimagesize($sourceFile);
$newWidth = 100;
$newHeight = ($height / $width) * $newWidth;
$newImage = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($sourceFile);
imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($newImage, $targetFileResized);
imagedestroy($newImage);
imagedestroy($source);