PHP Code

Login and Upload Files to an FTP Server With PHP

I previously posted the code to FTP files from an ASP page. Of course it would be handy to be able to upload files from a PHP web application to an FTP server as well. This code will detect any connection errors, and you can modify the code to upload as many files as you need.

The best way to use this code would be to put it into a function, and have it accept an array of files to upload. Don't forget to change to ASCII mode when uploading text or HTML files!


$file = "test.txt";

$ftp_server = "";
$ftp_user_name = "username";
$ftp_user_pass = "password";
$destination_file = "/upload/" . $file;
$source_file = "/home/username/public_html/files/" . $file;

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

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
        echo "FTP upload has failed!";
    } else {
        echo "Uploaded $source_file to $ftp_server as $destination_file";
// close the FTP stream

In case you're looking for it, here's the code to FTP files from ASP.



  1. File Upload/Attachment:-
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] 0)
    echo "Error: " . $_FILES["file"]["error"] . "";
    echo "Upload: " . $_FILES["file"]["name"] . "";
    echo "Type: " . $_FILES["file"]["type"] . "";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    echo "Invalid file";

  2. how to get normal upload box(with browse button) on above script?

Leave a Reply

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image