如果需要从网站上抓取文件的话,可以通过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);