search
Homephp教程php手册缓存远程二维码图片到本地

第一步,以下代码扔到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);     
	}     
} 

第二步,在网站根目录建立一个叫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个地方,已经用蓝色标注-->

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

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

  2. 关于wordpress的the_permalinkget_permalink函数

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

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools