1

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.

divinediu
  • 423
  • 1
  • 9
  • 33
TechnoPulseLabs
  • 111
  • 4
  • 15
  • possible duplicate of [PHP: How do I read a .txt file from FTP server into a variable?](http://stackoverflow.com/questions/18392321/php-how-do-i-read-a-txt-file-from-ftp-server-into-a-variable) – Mihai Iorga Apr 26 '14 at 06:14

1 Answers1

1

Ok, This solved my error.

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

Thanks.

TechnoPulseLabs
  • 111
  • 4
  • 15
  • hello, above code works fine, but what if we want to download from "ftps" and with port number , I used it like this 'ftps://username:ssword@ftps.hostname.com:2222/path/'; but it gives me error like : Warning: fopen(): connect() failed: can you please help me about this? – Kishor 6ugani May 02 '23 at 11:59