Trying to upload a text file from WordPress website to a remote FTP with standard WordPress Filesystem_API
. The connection works fine, but could not upload files to the destination. The PHP standard ftp_put()
works fine. File upload is successful using the FileZilla client. It's a plain FTP ( Not TLS, Not SSL )
Tried WordPress Developer guide - for ftpext, ftpsockets
function remote_ftp_upload_using_standard_wp($ftp_profile) {
global $wp_filesystem;
require_once ( ABSPATH . '/wp-admin/includes/file.php' );
$connection_method = 'ftpext';
$connection_options = array(
'connection_type' => $connection_method,
'hostname' => $ftp_profile['server'],
'username' => $ftp_profile['user_name'],
'password' => $ftp_profile['password'],
'port' => $ftp_profile['port'],
);
WP_Filesystem($connection_options);
if (!class_exists("WP_Filesystem_$connection_method")) {
$abstraction_file = ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $connection_method . '.php';
if (!file_exists($abstraction_file)) {
return;
}
require_once $abstraction_file;
}
$method = "WP_Filesystem_$connection_method";
$wp_filesystem = new $method($connection_options);
$wp_filesystem->connect(); // RETURNS TRUE
//var_dump($wp_filesystem->abspath());exit;
//$wp_filesystem->touch('/test.txt');
$wp_filesystem->put_contents('/test.txt', "hello"); // RETURNS FALSE
//ftp_pasv( $wp_filesystem->link, false );
return $wp_filesystem;
}
My Answer:
> 'ftp',
> 'ssl' => false,
> 'timeout' => 60,
> 'hostname' => $ftp_profile['hostname'],
> 'username' => $ftp_profile['username'],
> 'password' => $ftp_profile['password'],
> 'port' => $ftp_profile['port'],
> );
> if ( ! WP_Filesystem($connection_options) ) {
> return false;
> }
> $file_path = '/path/to/local/file.txt';
> $remote_file_path = '/path/to/remote/file.txt';
> if ( $wp_filesystem->put_contents($remote_file_path, file_get_contents($file_path), FS_CHMOD_FILE) ) {
> return true;
> } else {
> return false;
> }
}
You can call this function with the FTP profile details like this:
php
$ftp_profile = array(
'hostname' => 'ftp.example.com',
'username' => 'ftp_username',
'password' => 'ftp_password',
'port' => 21,
);
if ( remote_ftp_upload_using_standard_wp($ftp_profile) ) {
echo 'File uploaded successfully';
} else {
echo 'Failed to upload file';
}
Make sure to replace the hostname, username, password, and file paths with your actual FTP details and file paths.
Rate this post
3 of 5 based on 6595 votesComments