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



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

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

我已经尝试了几种PHP(ssh2_connect((,copy((,fopen((,...(的方法,但没有一种成功。

$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);

输出: "警告:ssh2_connect((: 无法连接到端口 22 上的 www.example.com [..]">

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

访问类似 url 时

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

您使用的是 HTTP 基本身份验证,它发送AuthorizationHTTP 标头。这与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。您可以按照并尝试本指南:使用 PHP 进行 HTTP 身份验证

最新更新