Search code examples
phpserverftp

Create and upload a new file via ftp in php


Is it possible to upload a new file in ftp instead of rewrite an old one? I need code for creating a new file and uploading it into the server via ftp. If I try to upload it via ftp_put(), it does not work.

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
    $ftp = ftp_connect("web");
ftp_login($ftp, "user", "pass");
echo ftp_put($ftp, "Tulassi/tulasi_test", $objPHPExcel, FTP_BINARY);
ftp_close($ftp);
    exit;

Solution

  • <?php
    $ftp_server = "";
    $ftp_user_name = "";
    $ftp_user_pass = '';
    $destination_file = "new.xls";
    $source_file = $objWriter; 
    
    // set up basic connection
    $conn_id =  ftp_connect($ftp_server);
    ftp_pasv($conn_id, true); 
    
    // login with username and password
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 
    // check connection
    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 = ftp_put($conn_id, $destination_file, $source_file, FTP_ASCII); 
    
    if (!$upload) { 
    echo "FTP upload has failed!112";
    } else {
    echo "Uploaded $source_file to $ftp_server as $destination_file";
    }  
    // close the FTP stream 
    ftp_close($conn_id);
    ?>