How can the use of ftp_mkdir and ftp_chmod functions be optimized for successful file uploads in PHP?

To optimize the use of ftp_mkdir and ftp_chmod functions for successful file uploads in PHP, ensure that the directory where the file will be uploaded exists and has the correct permissions set before attempting to upload the file. Use ftp_mkdir to create the directory if it does not exist, and ftp_chmod to set the appropriate permissions on the directory.

// Connect to FTP server
$ftp = ftp_connect('ftp.example.com');
ftp_login($ftp, 'username', 'password');

// Check if directory exists, create if it doesn't
$directory = '/path/to/directory';
if (!ftp_chdir($ftp, $directory)) {
    ftp_mkdir($ftp, $directory);
}

// Set permissions on the directory
ftp_chmod($ftp, 0777, $directory);

// Upload file to the directory
ftp_put($ftp, $directory . '/filename.txt', 'local_filename.txt', FTP_ASCII);

// Close FTP connection
ftp_close($ftp);