PHP: How to Read Text Files from FTP Server into a Variable
Problem Overview
You are trying to read a text file from an FTP server into a PHP variable. However, the code you provided using ftp_get is incorrect, and file_get_contents is resulting in an error.
Method 1: Using file_get_contents
The easiest solution is to enable URL wrappers in PHP and use file_get_contents as follows:
<code class="php">$contents = file_get_contents('ftp://username:password@hostname/path/to/file');</code>
Method 2: Using ftp_fget
If you need more control over the reading process, you can use ftp_fget. Here's an example:
<code class="php">$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);</code>
Addressing FTP Error
The error you are receiving when using file_get_contents indicates that the file you are trying to read is not a regular file. Make sure that the file path is correct, that the file exists, and that you have permissions to read it.
Conclusion
By utilizing either file_get_contents or ftp_fget, you can successfully read text files from an FTP server into a PHP variable. The choice of method depends on your specific requirements.
The above is the detailed content of How to Read Text Files from an FTP Server into a PHP Variable: file_get_contents vs. ftp_fget?. For more information, please follow other related articles on the PHP Chinese website!