如何从网址上传文件?

时间:2018-09-04 11:57:32

标签: php codeigniter instagram

我已经开发了一个API函数,无需登录即可将某些内容发布到Instagram,问题是图像必须位于本地(在计算机中,d:\ .. e:\ ..等)。我想上传图像例如从url文件(http://example.com/images/pict1.jpg),但仅适用于本地文件,此处代码:

set_time_limit(0);
    date_default_timezone_set('UTC');
    require __DIR__.'../../../vendor/autoload.php';
    /////// CONFIG ///////
    $username = 'instagram username';
    $password = 'instagram pass';
    $debug = false;
    $truncatedDebug = false;
    //////////////////////
    /////// MEDIA ////////

    $photoFilename = '';
    $captionText = '';
    //////////////////////

    $ig = new \InstagramAPI\Instagram($debug, $truncatedDebug);
    try {
        $ig->login($username, $password);
    } catch (\Exception $e) {
        //echo 'Something went wrong: '.$e->getMessage()."\n";
        exit(0);
    }
    try {

        $photo = new \InstagramAPI\Media\Photo\InstagramPhoto($photoFilename);
        $ig->timeline->uploadPhoto($photo->getFile(), ['caption' => $captionText]);
    } catch (\Exception $e) {
        //echo 'Something went wrong: '.$e->getMessage()."\n";
    }

感谢阅读,希望对此问题有解决方案。

1 个答案:

答案 0 :(得分:1)

如果没有其他方法可以将URL图像传递到此API,则将文件下载到服务器,然后上传。

$content = file_get_contents('http://example.com/img'); // Download file from internet
file_put_contents(__DIR__.'/img.png', $content); // Save it's content to server

// Rest of magic
$photo = new \InstagramAPI\Media\Photo\InstagramPhoto(__DIR__.'/img.png');
$ig->timeline->uploadPhoto($photo->getFile(), ['caption' => $captionText]);

unlink(__DIR__.'/img.png'); // Remove file from server