使用PHP通过url上传1000张图片

时间:2015-11-25 11:43:58

标签: php download uploading

我想通过网址只需点击一下即可上传1000张图片。我有1000个图像URL存储在MYSQL数据库中。

所以请任何人给我PHP代码,通过mysql数据库通过URL上传1000张图片。

目前我正在使用以下代码: - 它通过发布图像的URL ...每次点击上传一个图像。

但我希望通过从数据库

获取网址,一键上传1000张图片
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());

// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {

echo "<div>";
$oid = $row['tid'];
$th= $row['q'];

echo "</div>";

$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');

if($url){
    $file = fopen($url,"rb");
    $directory = "thumbnail/";
    $valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp"); 
    $ext = end(explode(".",strtolower(basename($url))));
    if(in_array($ext,$valid_exts)){

        $filename = "$oid.$ext";
        $newfile = fopen($directory . $filename, "wb");
        if($newfile){
            while(!feof($file)){
                fwrite($newfile,fread($file,1024 * 8),1024 * 8);
            }
            echo 'File uploaded successfully';
            echo '**$$**'.$filename;
        }
        else{
            echo 'File does not exists';
        }
    }
    else{
        echo 'Invalid URL';
    }
}
else{
    echo 'Please enter the URL';
}

}

非常感谢.... ...

1 个答案:

答案 0 :(得分:3)

您拥有的代码已经过时,而且比您需要的代码更复杂。这不是一个你获得代码的网站,因为你问,这是一个学习环境。

我将举例说明你可以继续:

// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
    $imgSource = file_get_contents($fItems['url']); // get the image
    // Check if it didn't go wrong:
    if( $imgSource!==false ){
        // Which directory to put the file in:
        $newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/"; 
        // The name of the file:
        $newFilename = basename($fItems['url'], $imgSource); 

        // Save on your server:
        file_put_content($newLocation.$newFilename);
    }
    // Update the row in the DB. If something goes wrong, you don't have to do all of them again:
    mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}

相关功能:
file_get_contents() - 获取图片的内容
file_put_contents() - 将此函数中给出的内容放在指定的文件中 basename() - 给定一个网址,它只为您提供文件名

重要提示:

  • 您正在使用mysql_query。这已被弃用(不应再使用),请改用PDO或mysqli
  • 我建议你从命令行开始这项工作,并在更新后添加一个echo,以便你可以监控进度