Home > php教程 > php手册 > body text

缓存远程二维码图片到本地

WBOY
Release: 2016-06-06 20:09:13
Original
1100 people have browsed it

第一步,以下代码扔到functions.php function get_qr($url,$path,$qrpic){ set_time_limit (10); //设置十秒超时$destination_folder = $path?$path.'/':''; $localname = $destination_folder .$qrpic; $file = fopen ($url, "rb"); //fopen函数的r+模式: 读

第一步,以下代码扔到functions.php

function get_qr($url,$path,$qrpic){     
	set_time_limit (10); //设置十秒超时
	$destination_folder = $path?$path.'/':''; 
	$localname = $destination_folder .$qrpic;     
	$file = fopen ($url, "rb"); //fopen函数的r+模式: 读写方式打开 文件指针指向文件头
	if ($file) {     
		$newf = fopen ($localname, "wb"); // w+,读写方式打开 文件指针指向文件头 如果文件不存在则尝试创建之 
		if ($newf)     
			while(!feof($file)) {     
				fwrite( $newf, fread($file, 1024 * 2 ), 1024 * 2 ); //写入文件,fread控制文件最大的大小,这里是2M 
			}     
	}     
	if ($file) {     
		fclose($file);  //关闭fopen打开的文件   
	}     
	if ($newf) {     
		fclose($newf);     
	}     
} 
Copy after login

第二步,在网站根目录建立一个叫qrcode的新文件夹,确保有写入权限,

第三步,以下代码放到需要输出二维码图片的地方,如single.php

<?php $localqr =  ABSPATH .'qrcode/'.get_the_id().'.jpg';
if (!file_exists($localqr)) {//如果图片已经存在,则不会再次保存
	get_qr( "http://chart.googleapis.com/chart?cht=qr&chs=100x100&choe=UTF-8&chld=L|4&chl=".get_permalink() ,"qrcode", get_the_id().".jpg");//图片名以文章id命名
}  
?> 
<img src="<?php%20echo%20home_url(%20''%20);%20?>/qrcode/<?php%20the_id()?>.jpg"    style="max-width:90%"  style="max-width:90%" alt="QR 码">
<!--默认二维码图片大小是100*100,如果要改,需要改4个地方,已经用蓝色标注-->
Copy after login

教程已经结束了,下面是写这段代码过程中我的一些感想,
  1. 关于PHP的fopen函数

    fopen不能直接获取https打头的url

  2. 关于wordpress的the_permalinkget_permalink函数

    前者是display直接输出结果,后者是return返回值,在自定义函数中使用此类变量需要使用后者
    例如the_id和get_the_id用法也是如此

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!