我没有安装curl。前面已经提到过,这段代码应该可以工作,
file_put_contents($target_path,file_get_contents($image));
,但它不适合我,它把图像与正确的名称等…但是大小为0字节。$target_path权限正确,allow_url_fopen为On
我做错了什么吗?
allow_url_fopen
不是URL上file_get_contents
可以中断的唯一条件。服务器可能被设置为处理或检测认证/用户代理等。
首先尝试将数据放入变量并将其打印出来,看看它是否能够获取内容;
$img = "";
$img = file_get_contents($image);
echo $img; //for debugging..
//for running..
if(!$img) die("no data fetched");
现在如果$img
有数据,下一步尝试将其写入文件:
$result = file_put_contents($target_path,$img);
if($result=== FALSE)
die("Error writing data into $target_path");
else
echo "$result bytes written to $target_path";
您面临的问题是,在您拥有的嵌套函数列表中存在多个故障点。虽然它很漂亮,并且将多行代码压缩成一行,但很难调试,并且在类似您所面临的情况下,您将无法轻松确定哪一段代码是有问题的代码。
试着拆分你的代码并添加一些基本的错误处理,这样你也许可以做一些事情,而不是在错误的情况下只写0字节的文件:
<?php
error_reporting(E_ALL);
$target_path = "./some_path/";
$new_img = "new_image.jpg";
if(file_exists($target_path)){
$img = file_get_contents($image);
if(strlen($img) >=1){
file_put_contents($target_path . $new_img, $img);
}else{
echo 'Error fetching $image';
}
}else{
echo '$target_path not found';
}
?>
必须检查$image
和$target_path
的内容,路径和url是正确的,$target_path
和dirname(__FILE__).'/image.jpg'
使用dirname(__FILE__)
是好的,它有助于有正确的目标路径
注意$target_path
必须使用全路径
你可以用fopen来测试这个函数,它也可以工作,但是比较慢
function Request($url,$File="",$Method='POST',$data=null, $optional_headers = null,$Debug=0){
$params = array('http' => array('method' => $Method));
$optional_headers.="Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'r'n";
$optional_headers.="Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3'r'n";
$optional_headers.="Accept-Encoding:gzip,deflate,sdch'r'n";
$optional_headers.="Accept-Language:en-US,en;q=0.8'r'n";
$optional_headers.="Cache-Control:max-age=0'r'n";
$optional_headers.="Connection:keep-alive'r'n";
$optional_headers.="User-Agent:Mozilla/5.0 AppleWebKit/536.5 (KHTML, like Gecko) SepidarBrowser/1.0.100.52 Safari/536.5'r'n";
if ($data !== null) {
$params['http']['content'] = $data;
}
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
return false;
}
$response= @stream_get_meta_data($fp);
$out['header'] = $response['wrapper_data'];
$out['body']='';
if($File!=""){
$fout = @fopen($File, 'w+');
}
while(!@feof($fp)){
$buffering=@fread($fp,1024*8);
// echo "***************'n".strlen($buffering)."'n".$buffering."'n***********************";
if($buffering==''){break;}
if($File!=""){
@fwrite($fout,$buffering);
if($Debug==1)echo strlen($buffering)."-->Download And Stored IN".$File;
}
$out['body'] .=$buffering;
}
if(trim(@$out['header']['Content-Encoding'])=='deflate'){
$out['body']=gzinflate($out['body']);
}
fclose($fp);
return $out;
}
Request($target_path,$image,'GET');