How to upload file via ftp in laravel?

by elise_daugherty , in category: PHP Frameworks , 2 months ago

How to upload file via ftp in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 2 months ago

@elise_daugherty 

To upload a file via FTP in Laravel, you can use the PHP FTP functions provided by PHP itself. Here is a step-by-step guide on how to upload a file via FTP in Laravel:

  1. First, make sure that the FTP PHP extension is enabled on your server. You can check if it's enabled by running the following command in your Laravel project directory:
1
php -m | grep ftp


If you don't see 'ftp' in the output, you may need to enable the FTP extension in your PHP configuration file.

  1. Next, you need to create a function to upload a file using FTP. You can create this function in a controller or a service:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use IlluminateSupportFacadesStorage;

public function uploadFileViaFTP()
{
    $server = 'ftp.example.com';  // FTP server address
    $username = 'ftp_username';  // FTP username
    $password = 'ftp_password';  // FTP password
    $remoteFilePath = '/path/to/remote/file/' . 'filename.ext';  // Remote file path

    $localFilePath = storage_path('app/public/filename.ext');  // Local file path

    $conn = ftp_connect($server);
    $login = ftp_login($conn, $username, $password);

    if ($conn && $login) {
        if (ftp_put($conn, $remoteFilePath, $localFilePath, FTP_BINARY)) {
            echo "Successfully uploaded $localFilePath
";
        } else {
            echo "Error uploading $localFilePath
";
        }

        ftp_close($conn);
    } else {
        echo "FTP connection failed
";
    }
}


  1. Finally, you can call this function in your controller or route to upload a file via FTP:
1
2
3
4
5
6
public function uploadFile()
{
    $this->uploadFileViaFTP();

    return response()->json(['message' => 'File uploaded via FTP']);
}


That's it! Now you can upload a file via FTP in Laravel using the PHP FTP functions. Make sure to replace the FTP server details, username, password, and file paths with your own.