由于 url 启用了 SSL,因此通常需要打包附加信息并随请求一起发送 - 对于该copy
函数,有一个context
参数。context
允许您指定方法、协议等来支持请求。
$url='https://www.ilportaleofferte.it/portaleOfferte/resources/opendata/csv/offerteML/2019_1/PO_Offerte_G_MLIBERO_20190130.xml';
/* download a copy from: https://curl.haxx.se/ca/cacert.pem */
$cacert=__DIR__ . DIRECTORY_SEPARATOR . 'cacert.pem';
/* define where files are to be stored */
$dir='c:/temp/downloads/';
使用该stream_context_create()
函数为请求构建上下文并copy
实际发出请求。
$filepath=$dir . basename( $url );
$args = array(
'http' => array( 'method' => 'GET', 'protocol_version' => '1.1' ),
'ssl' => array( 'verify_peer' => true, 'verify_peer_name' => true, 'allow_self_signed' => false, 'cafile' => $cacert )
);
$ctxt = stream_context_create( $args );
$status = copy( $url, $filepath, $ctxt );
if( $status && file_exists( $filepath ) ){
printf(
'The file "%s" downloaded successfully. %sMb written to disk.',
$filepath,
round( filesize( $filepath ) / pow( 1024, 2 ),2 )
);
}
另一个也许更好的选择是 curl:
function downloadfile( $url=false, $dir=false, $cacert=false ){
if( $url && $dir ){
/* define the save path */
$filepath = $dir . basename( $url );
/* time how long the download takes */
$start=time();
/* open a file pointer for use by curl */
$fp = fopen( $filepath, 'w+' );
/* create the curl request - write file directly */
$ch = curl_init( $url );
curl_setopt($ch, CURLOPT_HEADER, 0 );
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
if( parse_url( $url, PHP_URL_SCHEME )=='https' ){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt($ch, CURLOPT_CAINFO, $cacert );
}
curl_setopt($ch, CURLOPT_ENCODING, '' );
curl_setopt($ch, CURLOPT_FILE, $fp );# write to file
/* the response */
$obj=(object)array(
'response' => curl_exec($ch),
'info' => (object)curl_getinfo($ch),
'error' => curl_error($ch),
'filepath' => $filepath
);
/* tidy up */
curl_close($ch);
fclose($fp);
/* calculate time operation took */
$obj->duration=round( time() - $start, 2 );
return $obj;
}
}
/* run the function */
$obj = downloadfile( $url, $dir, $cacert );
if( $obj->info->http_code==200 ){
printf(
'The file "%s" downloaded successfully in approximately %ss. %sMb written to disk.',
$obj->filepath,
$obj->duration,
round( filesize( $obj->filepath ) / pow( 1024, 2 ),2 )
);
} else {
printf(
'Error: A problem was encountered downloading %s. The response code is: %d and error message: "%s"',
$url,
$obj->info->http_code,
$obj->error
);
}
以上两种方法以及手动下载导致文件为3.19Mb