Transfer Files Using FTP in PHP

Discussion in 'PHP' started by pradeep, Dec 26, 2012.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    File Transfer Protocol or popularly known as FTP has been a de facto standard for transferring files for many years, can be used in many programs / utilities like backup programs, etc. PHP is being increasingly used in writing scripts for maintenance and other purposes and the FTP extensions comes real handy in such cases.

    In this article we'll be looking at installation and usage of the FTP functions available in PHP.


    In case you are using a Debian based system like Ubuntu etc, this simple command will install it for you.

    $ sudo apt-get install php-net-ftp
    Other Linux systems, you'll need to configure PHP with --enable-ftp option.

    Luckily for Windows users, nothing needs to be done as the extension is built-in.


    I'll not be covering all possible functions available with the extension, but just the frequently used/needed ones according to me, for a full list of functions and their uses refer to Please follow the demo code below, I have commented wherever possible to help understand the usage better.

    // connect to the FTP server
    $conn ftp_connect('');

    // login with username / pass, or anonymously as required
    $login_res ftp_login$conn'pradeep''anju123' );

    // check if the connection and login were successful or not
    if($conn && $login_res) {
    "Yippee!! Connected to FTP";
    else {
    "Connection / Login failed";

    // say, we change to a different directory
    if(!ftp_chdir$conn'/home/pradeep/photos/')) {
    "Oops! could not change directory";

    // get a list of files/directories
    // this only returns the names not any details
    $basic_listing ftp_nlist$conn"." );

    var_dump$basic_listing );

    // get detailed info using raw listing
    $raw_listing ftp_rawlist$conn'.' );

    var_dump$raw_listing );

    // now we'll upload a file
    if (ftp_put$conn'server_image.jpg''local_image.jpg'FTP_BINARY)) {
    "Uploaded an image";

    // download a file
    if (ftp_get$conn'local_image.jpg''server_image.jpg'FTP_BINARY)) {
    "Downloaded an image";

    // delete a file
    if (ftp_delete$conn'server_image.jpg' )) {
    "Deleted file";

    // create a directory
    if (ftp_mkdir$conn'Vacation' )) {
    "Created new directory";

    // now let's try to set permissions for a file
    if (ftp_chmod$conn0755'') !== false) {
    "Successfully made program executable";

    // finally, close the connection
    ftp_close$conn );
    I hope the article was helpful and will enable you to FTP enable your PHP scripts.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice