网站在添加内容时可以通过PHP程序下载内容中的远程图片到本地服务器,最近更新内容时发现如果图片众多会导致更新数据库 *_content_text 数据表发生错误,因为PHP下载远程图片花费太多时间导致#MySQL#链接超时更新数据表失败。
解决办法:限制单次PHP程序下载远程图片的数量,这样就可以保证PHP程序更快完成下载工作及时更新MySQL中的数据。
下面是【爱玩电脑】下载远程图片的PHP代码片断:
//本地化远程图片
function remote($text)
{
$basehost = $_SERVER["HTTP_HOST"];
$basehost2 = str_replace('http://', '', SAESTOR_URL);//SaeStorage
$img_array = array();
preg_match_all("/src=[\"|'|\s]{0,}(http:\/\/([^>]*)\.(gif|jpg|jpeg|png|bmp))/isU", $text, $img_array);
$img_array = array_unique($img_array[1]);
$attached = loader('attached');
$i = 0;
$max = 5;
foreach ($img_array as $url)
{
if ($i > $max)
break;//指定下载的远程图片数量
if (preg_match("/{$basehost}/i", $url) || preg_match("/{$basehost2}/i", $url))
continue;
$do = $attached->download($url);
if (!$do['error'])
{
$text = str_replace($url, $do['message'], $text);
$i++;
}
}
return $text;
}