分类目录归档:PHP

file_get_contents failed to open stream

[Wed Apr 02 09:31:57 2014] [error] [client 218.5.79.46] PHP Warning:  file_get_contents(http://www.2mysite.net/attachments/month_0906/2009061610202025710_39.jpg): failed to open stream: no suitable wrapper could be found in /path/to/wp-content/plugins/dx-auto-save-images/dx-auto-save-images.php on line 51, referer: http://517sou.net/wp-admin/post.php?post=221&action=edit

经查,是主机提供商限制allow_url_fopen,因此,只能自己修改一下代码,替换dx-auto-save-images.php页面函数save_images中的相关代码:

//save exterior images
function save_images($image_url,$post_id,$i){
//allow_url_fopen = On
//$file=file_get_contents($image_url);

//allow_url_fopen = Off
// create a new cURL resource
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $image_url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file = curl_exec($ch);
curl_close($ch);

$filename=basename($image_url);
$options = get_option( 'dx-auto-save-images-options' );
if( $options['chinese']=='yes' ){
preg_match( '/(.*?)(\.\w+)$/', $filename, $match );
$im_name = md5($match[1]).$match[2];
}
else $im_name = $filename;
$res=wp_upload_bits($im_name,'',$file);
$attach_id = $this->insert_attachment($res['file'],$post_id);
if( $options['post-tmb']=='yes' && $i==1 ){
set_post_thumbnail( $post_id, $attach_id );
}

return $res;
}

或者

	//save exterior images
	function save_images($image_url,$post_id,$i){
		//allow_url_fopen = On
		//$file=file_get_contents($image_url);
		//allow_url_fopen = Off
		$file=$this->file_get_contents_curl($image_url);

		$filename=basename($image_url);
		$options = get_option( 'dx-auto-save-images-options' );
		if( $options['chinese']=='yes' ){
		  preg_match( '/(.*?)(\.\w+)$/', $filename, $match );
		  $im_name = md5($match[1]).$match[2];		
		}
		else $im_name = $filename;
		$res=wp_upload_bits($im_name,'',$file);
		$attach_id = $this->insert_attachment($res['file'],$post_id);
		if( $options['post-tmb']=='yes' && $i==1 ){
			set_post_thumbnail( $post_id, $attach_id );
		}
		
		return $res;
	}
	 
	// Replace file_get_contents when disabled
	function file_get_contents_curl($url) {
		$timeout = 5; 
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL, $url); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
		//curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}