Skip to content

Instantly share code, notes, and snippets.

@grzegorz-rozycki
Created October 9, 2017 18:35
Show Gist options
  • Save grzegorz-rozycki/e2b22a3bb3c1fbada60933ed7217ca99 to your computer and use it in GitHub Desktop.
Save grzegorz-rozycki/e2b22a3bb3c1fbada60933ed7217ca99 to your computer and use it in GitHub Desktop.
<?php
const MAX_REDIRECTS = 5;
const MAX_WAIT = 30; // don't wait longer than N seconds.
const USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36';
function curl_get_fileinfo($url): array
{
$info = [];
try {
$ch = curl_init($url);
// Issue a HEAD request and follow any redirects.
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, MAX_REDIRECTS);
curl_setopt($ch, CURLOPT_USERAGENT, USER_AGENT);
curl_setopt($ch, CURLOPT_TIMEOUT, MAX_WAIT);
$data = curl_exec($ch);
$info = curl_getinfo($ch);
} finally {
@curl_close($ch);
}
print_r($info);
return [
'url' => $info['url'] ?? $url, // if there where redirects the actual URL is given
'mime' => $info['content_type'] ?? 'image/*',
'size' => $info['download_content_length'] ?? 0, // declared size in bytes
'status' => $info['http_code'] ?? 404 // this will prevent an actual download if errors occured
];
}
function curl_get_file(string $url)
{
try {
$fp = fopen(dirname(__FILE__) . '/page-banner.jpg', 'w+');
// Here is the file we are downloading, replace spaces with %20
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, MAX_REDIRECTS);
curl_setopt($ch, CURLOPT_USERAGENT, USER_AGENT);
curl_setopt($ch, CURLOPT_TIMEOUT, MAX_WAIT);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp);
// get curl response
curl_exec($ch);
} finally {
@curl_close($ch);
@fclose($fp);
}
}
$url = getenv('URL');
curl_get_fileinfo($url);
curl_get_file($url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment