What are the best practices for handling file uploads and image manipulation in PHP, especially in relation to FTP functions?
When handling file uploads and image manipulation in PHP, it is important to validate file types, sanitize file names, and store files securely. When using FTP functions, make sure to establish a secure connection and handle errors properly. Additionally, consider using libraries like GD or Imagick for image manipulation tasks.
// Example code for handling file uploads and image manipulation in PHP
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
die('Invalid file type.');
}
// Sanitize file name
$fileName = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);
// Store file securely
$uploadPath = '/path/to/upload/directory/' . $fileName;
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}
// Example code for using FTP functions in PHP
// Connect to FTP server
$ftpConn = ftp_connect('ftp.example.com');
$ftpLogin = ftp_login($ftpConn, 'username', 'password');
// Handle errors
if (!$ftpConn || !$ftpLogin) {
die('FTP connection failed.');
}
// Upload file to FTP server
if (ftp_put($ftpConn, 'remote/path/' . $fileName, $uploadPath, FTP_BINARY)) {
echo 'File uploaded to FTP server.';
} else {
echo 'Error uploading file to FTP server.';
}
// Close FTP connection
ftp_close($ftpConn);