Simple FTP upload with PHP
2015-06-19

2018-04-26 12:07:58 PHP,FTP,Snippets,EN

How to to upload a file to a FTP Server using PHP. There are several ways to accomplish this.

Using file_put_contents() command.

// FTP access data
$sUser     = 'developer';
$sPassword = 'secret';
$sHost     = 'ftp.example.com';

// file informations
$sFilename = 'file.txt';
$sContent  = 'Example Content. DateTime: ' . date('Y-m-d H:i:s');

// save the file
$bSuccess = (boolean) file_put_contents(

    // target FTP file 
    sprintf(
        'ftp://%s:%s@%s%s/%s', 
        $sUser, 
        $sPassword, 
        $sHost, 
        $sFilename
    ), 

    $sContent, 

    0, 

    // stream context
    stream_context_create(
        array(
            'ftp' => array(
                'overwrite' => true
            )
        )
    )
);

// true | false
var_dump($bSuccess);

Using ftp_* commands:

// FTP access data
$sUser     = 'developer';
$sPassword = 'secret';
$sHost     = 'ftp.example.com';

// file informations
$sFilename = 'file.txt';
$sContent  = 'Example Content. DateTime: ' . date('Y-m-d H:i:s');

$rConnection = ftp_connect($sHost); 
if (false !== $rConnection)
{
    if (true === ftp_login($rConnection, $sUser, $sPassword))
    {
        // upload file
        $bSuccess = ftp_put(
            $hConnection, 
            $sFilename, 
            $sContent, 
            FTP_ASCII
        )
    }
}

// close connection
ftp_close($rConnection);

Using curl:

// FTP access data
$sUser     = 'developer';
$sPassword = 'secret';
$sHost     = 'ftp.example.com';

// file informations
$sFilename = 'file.txt';

$rFopen = fopen(
    $sFilename, 
    'r'
);

$hCurl = curl_init();
curl_setopt($hCurl, CURLOPT_URL, 'ftp://' . $sHost . '/' . $sFilename);
curl_setopt($hCurl, CURLOPT_USERPWD, $sUser . ":" . $sPassword);
curl_setopt($hCurl, CURLOPT_UPLOAD, 1);
curl_setopt($hCurl, CURLOPT_INFILE, $rFopen);
curl_setopt($hCurl, CURLOPT_INFILESIZE, filesize($sFilename));
curl_exec ($hCurl);
$iError = curl_errno($hCurl);
curl_close ($hCurl);