ecshop远程图片本地化

<?php
set_time_limit(0);
include("data/config.php");
 
$link=mysql_connect($db_host,$db_user,$db_pass)or die("connect error");
mysql_select_db($db_name,$link)or die(mysql_error());
mysql_query("set names utf8");
 
header("Content-type:text/html;charset=utf-8");
 
$id=intval($_GET['id']);
 
 
if($id==0){
 
$sql="select `goods_id`,`goods_name`,`goods_desc` from `p_goods` order by goods_id desc ";
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$aa="<span style='color:#ccc;font-size:12px;'>无远程图片</span>";
if(preg_match('/(http://)/i', $row['goods_desc'])){
    $aa="<a target='_blank' href='?id=".$row['goods_id']."'>Go Get It</a>";
}
    echo $row['goods_id']." ".$row['goods_name']." ".$aa."<br/>";
}
 
exit();
}
 
 
 
 
 
sleep(1);
 
 
$sql="select `goods_desc` from `p_goods` where `goods_id`='$id' limit 1";
$res=mysql_fetch_array(mysql_query($sql));
 
preg_match_all('/src=['|"]([^"|^']+)['|"]/i', $res[0], $picurl); 
$urlArr=$picurl[1];
/*
print_r($urlArr);
die();
$urlArr[]="http://static.oschina.net/uploads/user/129/258733_50.jpg";
$urlArr[]="http://static.oschina.net/uploads/img/201302/16195715_kPci.png";
*/
$num= isset($_GET['num']) ? $_GET['num'] : 1;
 
$all=count($urlArr);
 
 
$url=$urlArr[$num-1]; 
 
 
if(!preg_match('/(http://)/i', $url)){
    if($num >= $all) {
    exit('<br/>all done!');
    }
    echo $url."<br/> 已处理";
    echo "<script>location.href='?id={$id}&num=".($num+1)."'</script>";
    exit();
} 
 
 
 
$array=@get_headers($url,1);
 
echo $url."<br/><br/>";
 
if(preg_match('/200/',$array[0])){
 
    ob_start();    
    readfile($url);
    $img = ob_get_contents();
    ob_end_clean(); 
     $dir="images/goods_desc";
 
      if (!file_exists($dir))
      {
       mkdir($dir, 0777);
      }
 
    $filename=$dir."/".mt_rand(11111,9999999999).time().".jpg";
    $f=fopen($filename,'a');
    $fres=fwrite($f,$img);
    fclose($f);
 
    if($fres!=false){
        $goods_desc=str_replace($url,"/".$filename,$res[0]);
        $sql="update `p_goods` set  `goods_desc` = '$goods_desc' where `goods_id`='$id' limit 1 ";
        mysql_query($sql);
    }
 
}
 
echo $num."/".$all;
 
if($num >= $all) {
 
exit('<br/>all done!');
}
else{
 
echo "<script>location.href='?id={$id}&num=".($num+1)."'</script>";
}