Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Justin Barrett
Justin Barrett
27,345 Points

Insert file from password protected remote server to WordPress Media Library

I have a CSV file on a password protected remote server that I need to get, add to the media library, and attach it to a new post in WordPress. I have tried multiple methods but nothing seems to be working. What to do once that's done I know how to do, but getting the file and adding it to the media library is proving....difficult. Here's my sample code (passwords and authentication removed):

function save() {
$un = 'username';
$p = 'pass';

$filename = 'filename-' . date("Y-m-d") . '.csv';
// set up basic connection variables
$ftp_server='ftp.server.com';
$ftp_user_name='username';
$ftp_user_pass='password';

//initiate connection
$conn_id = ftp_connect($ftp_server);


// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die ('login failed');

// get contents of the current directory
$contents = ftp_get($conn_id, $filename, 'server_file_name.csv');

// insert attachment
wp_insert_attachment( $contents, $filename );
}
add_action('admin_init', 'save');