Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

PHP: How do I read a .txt file from FTP server into a variable?

I have two servers. I already have a .txt file in the one I'm connecting to.

I need to get the .txt file contents and put them into a $ variable. Here is my code that doesnt work:

$ftp_server = $_POST["site"];
$path = $_POST["path"];
$ftp_user_name = $_POST["username"];
$ftp_user_pass = $_POST["pass"];

// set up basic connection
$conn_id = ftp_connect($ftp_server);

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

ftp_get($conn_id, $content,"/" . $_POST["path"] . "/" . "#" . $result["id"]
. " - " .    $result["LastName"] . ", " . $result["FirstName"] . "/" . $_POST["title"] . ".txt", FTP_ASCII);

This code connects to the FTP and I used the ftp_get to copy from one text file to a variable called $content. I know a variable doesnt belong in this parameter, but I'm sold right now. I have no idea how to read this .txt file.

Is there a way to do this with the PHP FTP functions?

Thanks

Now, when I try this:

$fileContents = file_get_contents('ftp://username:pa??ssword@hostname/path/to/file');

It gives a 550 error saying that the .txt file is not a regular file. Why am I getting this error?

Thanks again

Here is the official error I'm getting:

Warning: fopen(ftp://[email protected]/101Notebook Backup: 22-08-2013/#11 - Cappucci, Ryan/queen.txt) [function.fopen]: failed to open stream: FTP server reports 550 /101Notebook Backup: 22-08-2013/: not a regular file in /home/content/34/11614434/html/adminpdo.php on line 269

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The file_get_contents is the easiest solution:

$contents = file_get_contents('ftp://username:pa??ssword@hostname/path/to/file');

If it does not work, it's probably because you do not have URL wrappers enabled in PHP.


If you need greater control over the reading (transfer mode, passive mode, offset, reading limit, etc), use the ftp_fget with a handle to the php://temp (or the php://memory) stream:

$conn_id = ftp_connect('hostname');

ftp_login($conn_id, 'username', 'password');

ftp_pasv($conn_id, true);

$h = fopen('php://temp', 'r+');

ftp_fget($conn_id, $h, '/path/to/file', FTP_BINARY, 0);

$fstats = fstat($h);
fseek($h, 0);
$contents = fread($h, $fstats['size']); 

fclose($h);
ftp_close($conn_id);

(add error handling)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...