简体   繁体   中英

Get file contents from FTP server - WordPress

I'm trying to get a file from an FTP server, in a WordPress shortcode.

Before starting to create a WP shortcode, I wrote and tested my code in a 'blank', non-WP environment, and it was working fine.

Then, I moved the code into a WP shortcode. And now I've got problems.

First, I learned that you can't use file_get_contents() in WordPress....

...So, I replaced that function with wp_remote_get(). But, this function doesn't accept a URL beginning with 'ftp://'.

Here is my code, any ideas on what needs to change to get it working in WordPress?:

$stuff = array();    

$conn_id = ftp_connect($ftp_server) or die("Error: Cannot connect to FTP Server.");

// try to login
if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "";
} else {
    echo "Error: Cannot connect to FTP Server.";
}

if (($response_xml_data = file_get_contents('ftp://username:password@ftp.example.co.uk/file.xml'))===false){
    echo "Error: Failed to fetch file.<br/>";
} else {
    libxml_use_internal_errors(true);
    print_r($response_xml_data);
    $data = simplexml_load_string($response_xml_data);
    if (!$data) {
        echo "Error loading XML\n";
        foreach(libxml_get_errors() as $error) {
            echo "\t", $error->message;
        }
    } else {
        $stuff = $data;
    }
}

// close the connection
ftp_close($conn_id);

When I replace file_get_contents() with wp_remote_get(), $response_xml_data equals:

WP_Error Object ( [errors] => Array ( [http_request_failed] => Array ( [0] => A valid URL was not provided. ) ) [error_data] => Array ( ) )

Scratch that... The problem isn't in the code, it's a server thing. 'allow_url_fopen' setting in php.ini must be set to '1'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM