When I type into any browser's address bar : https://username:password@www.example.com/Protected/Export/MyFile.zip, the file gets downloaded normally.
Now I'm trying to do the same with PHP : connect to the remote password-protected file and download it into a local directory (like ./downloads/).
I've tried several ways with PHP (ssh2_connect(), copy(), fopen(), ...) but none were successful.
$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);
Output : "Warning: ssh2_connect(): Unable to connect to www.example.com on port 22 [..]"
How can I download this file with PHP and store it on a local directory ?
When accessing an url like
https://username:password@www.example.com/Protected/Export/MyFile.zip
you're using HTTP Basic Auth, which sends the Authorization
HTTP header. This has nothing to do with ssh
, hence you cannot use ssh2_connect()
.
To access this with php, you could use 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);