首页 > 解决方案 > 使用 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 下载此文件并将其存储在本地目录中?

标签: phpdownloadpassword-protectionlibssh2

解决方案


访问类似的网址时

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

您正在使用HTTP Basic Auth,它发送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);

推荐阅读