Home » Php » Accessing an FTP directory listing with PHP

Accessing an FTP directory listing with PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I need to download data from the Bureau of Labor Statistics’ public FTP server for analysis. I’m attempting to use PHP to retrieve a listing, but I’m not sure how to do it with a public FTP server – using no ftp_login results in “false” being returned, and attempting to login as anonymous hangs the script.

My code:

<?php
// set up basic connection
$ftp = ftp_connect("ftp.bls.gov");
       ftp_login($ftp, "anonymous", "");
             ftp_pasv($ftp, true);
var_dump(ftp_rawlist($ftp, "/pub/time.series/la/"));
?>
How to&Answers:

Your script works for me (see output), I get a nice directory listing. Please contact the system administration of the server your PHP script is running and ask for support. It looks like that this is a network configuration issue to me.

Additionally always check function return values for errors before you continue:

// connect
$ftp = ftp_connect("ftp.bls.gov");
if (!$ftp) die('could not connect.');

// login
$r = ftp_login($ftp, "anonymous", "");
if (!$r) die('could not login.');

// enter passive mode
$r = ftp_pasv($ftp, true);
if (!$r) die('could not enable passive mode.');

// get listing
$r = ftp_rawlist($ftp, "/pub/time.series/la/");
var_dump($r);

What is Anonymous FTP?

Anonymous FTP is a means by which archive sites allow general access
to their archives of information. These sites create a special
account called “anonymous”. User “anonymous” has limited access
rights to the archive host, as well as some operating restrictions.
In fact, the only operations allowed are logging in using FTP,
listing the contents of a limited set of directories, and retrieving
files. Some sites limit the contents of a directory listing an
anonymous user can see as well. Note that “anonymous” users are not
usually allowed to transfer files TO the archive site, but can only
retrieve files from such a site.

Traditionally, this special anonymous user account accepts any string
as a password, although it is common to use either the password
“guest” or one’s electronic mail (e-mail) address. Some archive
sites now explicitly ask for the user’s e-mail address and will not
allow login with the “guest” password. Providing an e-mail address
is a courtesy that allows archive site operators to get some idea of
who is using their services.

Excerpt from: How to Use Anonymous FTP (RFC 1635)

Answer:

Try this Php code. Hope it’ll be helpful:

<?php
$connect = ftp_connect("ftp.hostname.com"); 
$result = ftp_login($connect, "username", "password");
$a = ftp_nlist($connect, "code22");

foreach($a as $value){
    echo $value,"<BR>";
}
?>