现在的位置: 首页 > 综合 > 正文

PHP读取文件之Basic验证处理

2013年04月13日 ⁄ 综合 ⁄ 共 666字 ⁄ 字号 评论关闭

如果需要从网站上抓取文件的话,可以通过file_get_contents和fopen两个函数,但是所下载的文件,在服务器上设置有Basic验证的时候,就需要特殊处理了。

关键字:stream_context_create、base64_encode

<?php
$url = 'http://www.demo.com/img.png';

//Basic 验证处理
$login = 'usr';
$pass  = '111111';

$basicSets = array();
$basicSets['http'] = array('header' => 'Authorization: Basic ' . base64_encode("{$login}:{$pass}"));

$context = stream_context_create($basicSets);

//1.file_get_contents
$str = file_get_contents($url, false, $context);

file_put_contents('./img.png', $str);

//2.fopen
$data = '';

$handle = @fopen($url, 'rb', false, $context);

while ($handle && !feof($handle)) {
	$data .= @fread($handle, 8192);
}
@fclose($handle);

$handle = @fopen('./img.png', 'wb');
@fwrite($handle, $data);
@fclose($handle);

抱歉!评论已关闭.