Henrik Petterson
Henrik Petterson

Reputation: 7094

Get file in PHP which is generated when visiting URL

In PHP, how do I get a file that is generated when you visit a URL. To explain this, if you visit this Google Drive URL:

https://docs.google.com/document/d/1ZUqkdVQZqpHhE25m-5wxhN1uzK7EvoZ81bmrwiwk3CY/export?format=doc

Download will start. How do I grab that download file in PHP?

Upvotes: 1

Views: 100

Answers (2)

E_p
E_p

Reputation: 3144

Though in theory file_get_contents should have worked for this situation it did not for me. I'm behind proxy.

To get more control I had to use curl

I left proxy configuration as a part of code but commented it out.

<?php

    $url = "https://docs.google.com/document/d/1ZUqkdVQZqpHhE25m-5wxhN1uzK7EvoZ81bmrwiwk3CY/export?format=doc";
    $fileToSave = dirname(__FILE__) . '/localfile.doc';
    // $proxy = "127.0.0.1:8080";

    set_time_limit(0);

    //This is the file where we save the    information
    $fp = fopen ($fileToSave, 'w+');

    //Here is the file we are downloading.
    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_TIMEOUT, 50);

    // write curl response to file
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    // Proxy stuff if you need it
    // curl_setopt($ch, CURLOPT_PROXY, $proxy);

    // ssl config here
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);

    // get curl response
    if(curl_exec($ch) === false) {
        echo 'Curl error: ' . curl_error($ch);
    } else {
        echo 'Done';
    }

    curl_close($ch);
    fclose($fp);

Upvotes: 2

Ali Niaz
Ali Niaz

Reputation: 312

$data=file_get_contents("https://docs.google.com/document/d/1ZUqkdVQZqpHhE25m-5wxhN1uzK7EvoZ81bmrwiwk3CY/export?format=doc") ;

Use this method to get the file content, I have used this method on a url that returned a CSV file upon hitting.

Upvotes: 0

Related Questions