使用 PHP 下载并存储远程密码保护文件

Download and store remote password protected file with PHP

当我在任何浏览器的地址栏中输入时: https://username:password@www.example.com/Protected/Export/MyFile.zip, 文件下载正常。

现在我正在尝试对 PHP 做同样的事情:连接到远程受密码保护的文件并将其下载到本地目录(如 ./downloads/)。

我用 PHP 尝试了几种方法(ssh2_connect()、copy()、fopen()、...),但 none 都成功了。

$originalConnectionTimeout = ini_get('default_socket_timeout');
ini_set('default_socket_timeout', 3); // reduces waiting time

$connection = ssh2_connect("www.example.com");

// use $connection to download the file

ini_set('default_socket_timeout', $originalConnectionTimeout);
if($connection !== false) ssh2_disconnect($connection);

输出: "Warning: ssh2_connect(): Unable to connect to www.example.com on port 22 [..]"

如何使用 PHP 下载此文件并将其存储在本地目录中?

访问 url 赞时

https://username:password@www.example.com/Protected/Export/MyFile.zip

您正在使用 HTTP Basic Auth,它发送 Authorization HTTP header。这与 ssh 无关,因此您不能使用 ssh2_connect().

要使用 php 访问它,您可以使用 curl:

$user = 'username';
$password = 'password';
$url = 'https://www.example.com/Protected/Export/MyFile.zip';

$curl = curl_init();
// Define which url you want to access
curl_setopt($curl, CURLOPT_URL, $url);

// Add authorization header
curl_setopt($curl, CURLOPT_USERPWD, $user . ':' . $password);

// Allow curl to negotiate auth method (may be required, depending on server)
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

// Get response and possible errors
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);

// Save file
$file = fopen('/path/to/file.zip', "w+");
fputs($file, $reponse);
fclose($file);

这不是 SSH 协议。它可能类似于 Apache HTTP Authentication. You can follow and try this guide: HTTP authentication with PHP