Question

I am trying ftp connections for file read.

All I want to do is

  • read particular ftp dir
  • list all its text files
  • and read them one by one

I am successful in listing files in given directory.

For eg: below code returns $emailfiles array with TEST.txt as one value.

But when I try to open/read the same file content using fopen/file_get_contents , it is giving the error: " Failed to open Stream "

I am able to access a file from another ftp : .38, which is public ftp. The ftp I want to actually use is .94, for which I have full privileges, as I am able to access files from browser with same link. I'm also able to write/paste files from windows explorer.

But I am unable to read the same file from php code.

Below is my code for ftp connection and testing.

    $ftp_server = "10.96.5.94";
$ftp_serverpath = "ftp://".$ftp_server;
$ftp_user_name = "myusername";
$ftp_user_pass = "mypassword";
$email_dir = "ebill";
try {
$con = ftp_connect($ftp_server);
if (false === $con) {
    throw new Exception('Unable to connect');
}

$loggedIn = ftp_login($con,  $ftp_user_name,  $ftp_user_pass);
if (true === $loggedIn) {
    echo 'Success!';
} else {
    throw new Exception('Unable to log in');
}

ftp_pasv($con, true);
$emailfiles = ftp_nlist($con, $email_dir);
print_r($emailfiles);


//$filename = "ftp://10.16.0.38/ebill/TEST.txt";
$filename = "ftp://10.96.5.94/ebill/TEST.txt";
$pr = file_exists($filename);
// OR
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));

Any help is greatly appreciated, Thank you.

Was it helpful?

Solution

Ok, This solved my error.

$filename = "ftp://username:pa‌​ssword@hostname/path/to/file";

Thanks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top