php - 使用 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 下载此文件并将其存储在本地目录中?
解决方案
访问类似的网址时
https://username:password@www.example.com/Protected/Export/MyFile.zip
您正在使用HTTP Basic Auth,它发送Authorization
HTTP 标头。这与 无关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);
推荐阅读
- python - SQLite将具有不同列值的多行合并到一个条目中
- c - 如何解决ncurses菜单边框错位
- reactjs - 获取错误类型 any 不能分配给类型 never
- angular - 当 http 客户端请求完成时,Angular 决定跳出它的区域。为什么?
- elasticsearch - aggregation_execution_exception : 聚合顺序路径无效,子路径指向非单桶聚合
- flutter - Flutter:如何将文本字段与列的底部中心对齐?
- sql - 如果条件为真,如果有多个数据连接到一个 ID,是否可以停止 CASE?
- python - 使用python函数或方法制作命令行实用程序的最佳方法?
- java - Tomcat上多模块项目的Spring Boot外部配置
- c# - 使用多个连接和多个选择字段从 linq 获取最大日期