开发者

Save external files by php

I have an array with urls, like:

[1] = http://site.com/1.pdf
[2] = http://site.com/234234234.png
[3] = http://site.com开发者_如何学JAVA/archive.zip
[4] = http://site.com/1f41f.anyformat
[5] = http://site.com/file.txt

How do I save them to some folder on my ftp by PHP?

Names of the files should not change.


Here's a simple example:

$urls = array('url1', 'url2');
foreach($urls as $url) {
   $data = file_get_contents($url);
   file_put_contents('/path/to/folder/'.basename($url), $data);
}


Maybe this will help you solve the question

function remote_merge($sourceurl,$targetftp){
    $ch = curl_init ($sourceurl);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $rawdata=curl_exec($ch);
    curl_close ($ch);
    $tempfile = "/path/to/temp/".basename(parse_url($sourceurl, PHP_URL_PATH));
    if(file_exists($tempfile)){
        unlink($tempfile);
    }
    $fp = fopen($tempfile,'x');
    fwrite($fp, $rawdata);
    fclose($fp);

    $ch = curl_init();  
    $fp = fopen($tempfile, "rb");

    curl_setopt($ch, CURLOPT_URL, $targetftp);
    curl_setopt($ch, CURLOPT_UPLOAD, 1);
    curl_setopt($ch, CURLOPT_INFILE, $fp);
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($tempfile));
    $error = curl_exec($ch);
    // check $error here to see if it did fine or not!
    curl_close($ch); 
}

Use this to tryout the remote_merge function

$sourceurls = array(
    "http://site.com/1.pdf",
    "http://site.com/234234234.png",
    "http://site.com/archive.zip",
    "http://site.com/1f41f.anyformat",
    "http://site.com/file.txt"
);

foreach($sourceurl as $sourceurls){
    $filename = basename(parse_url($sourceurl, PHP_URL_PATH);
    $targetftp = "ftp://${ftpuser}:${ftppasswd}@${ftpserver}${ftppath}/$filename";
    remote_merge($sourceurl,$targetftp)
}


193 questions, 3 answers... wow.

function curl($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_close ($ch);
    return curl_exec($ch);
}

$files = array();
$dir = "dir/";

foreach($files as $file){
    $name = explode("/", $file);
    $name = end($name);
    $contents = curl($file);
    file_put_contents($dir.$name, $contents);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜