PHP – How to read a file from another server using FTP credentials?

I had a task to read file from another server. Obvious you would suggest file_get_contents or cURL for same. But those files was not accessible through URL. I have to read it using FTP server credentials, Initially I was trying with ftp_get and some other FTP functions. But it was download all files to my local server.

But finally I got the solution, here its….

<?php
    $filename = 'ftp://username:password@hostname/files/path/and/name.txt';
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    echo $contents;
 ?>

I hope this would help you….

Uploads file to FTP server programmatically using PHP script

PHP it self provide us the FTP functions library which allow to implement client access to files servers (FTP). This library providing a wide range of control to executing script including read or write file to FTP server. This post will particularly post show you how to Send Files to send file using php script. Here is the  script which allow you to upload file to FTP server,

<?php
    // Connect to server
    $conn = ftp_connect("ftp.yourserver.com") or die("Could not connect");

    ftp_login($conn,"username","password") or die("invelid username or password");

    // move to path where you need to upload file
    ftp_chdir($conn, "/upload/") or die("could not find dir");

    // upload file to particular path
    $upload = ftp_put($conn,"allproduct.xml","allproduct.xml",FTP_BINARY);

    if (!$upload) { echo 'FTP upload failed!'; }

    ftp_close($conn);
?>

Some time you need to create dir dynamically on server, in that case you can use bellow code instead of change dir,

if(!ftp_chdir($conn, $folder_path))
{
    $create_folder = ftp_mkdir($conn, $folder_path);
    ftp_chmod($conn, 0777, $folder_path);
    ftp_chdir($conn, $folder_path);
}

Above part of script will check for particular dir. If it could not find, it will create that dir and moved to particular dir path. Then you can continue to upload part.