php 根据url自动生成缩略图并处理高并发问题
php  /  管理员 发布于 7年前   239
require(WWW_PATH.'/PicThumb.class.php'); // include PicThumb.class.php
require(WWW_PATH.'/ThumbConfig.php'); // include ThumbConfig.php
$logfile = WWW_PATH.'/createthumb.log'; // 日志文件
$source_path = WWW_PATH.'/upload/'; // 原路径
$dest_path = WWW_PATH.'/supload/'; // 目标路径
$path = isset($_GET['path'])? $_GET['path'] : ''; // 访问的图片URL
// 检查path
if(!$path){
exit();
}
// 获取图片URI
$relative_url = str_replace($dest_path, '', WWW_PATH.$path);
// 获取type
$type = substr($relative_url, 0, strpos($relative_url, '/'));
// 获取config
$config = isset($thumb_config[$type])? $thumb_config[$type] : '';
// 检查config
if(!$config || !isset($config['fromdir'])){
exit();
}
// 原图文件
$source = str_replace('/'.$type.'/', '/'.$config['fromdir'].'/', $source_path.$relative_url);
// 目标文件
$dest = $dest_path.$relative_url;
if(!file_exists($source)){ // 原图不存在
exit();
}
// 高并发处理
$processing_flag = '/tmp/thumb_'.md5($dest); // 用于判断文件是否处理中
$is_wait = 0; // 是否需要等待
$wait_timeout = 5; // 等待超时时间
if(!file_exists($processing_flag)){
file_put_contents($processing_flag, 1, true);
}else{
$is_wait = 1;
}
if($is_wait){ // 需要等待生成
while(file_exists($processing_flag)){
if(time()-$starttime>$wait_timeout){ // 超时
exit();
}
usleep(300000); // sleep 300 ms
}
if(file_exists($dest)){ // 图片生成成功
ob_clean();
header('content-type:'.mime_content_type($dest));
exit(file_get_contents($dest));
}else{
exit(); // 生成失败退出
}
}
// 创建缩略图
$obj = new PicThumb($logfile);
$obj->set_config($config);
$create_flag = $obj->create_thumb($source, $dest);
unlink($processing_flag); // 删除处理中标记文件
if($create_flag){ // 判断是否生成成功
ob_clean();
header('content-type:'.mime_content_type($dest));
exit(file_get_contents($dest));
}
?>
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号