[PHP] Requesty i zdalne pobieranie plików

Cel (założenia)

Stworzenie klasy „pomagającej” w wykonywaniu zapytań do innego serwera (GET, POST), pobieranie plików.

Implementacja

W najprostszej formie to może wyglądać tak:

class curl
{
    function getFile($url, $postArray =null , $referer = null)
    {
        // jeżeli nie podamy referera, wstawiany jest pobierany adres URL
        $referer = !empty($referer) ? $referer : $url;

        // jeżeli podaliśmy parametry do POST-a, posklejajmy je
        if(isset($postArray))
        {
            foreach ($postArray as $key => $value) {
                $postArray[$key] = urlencode($key) . '=' . urlencode($value);
            }
        }

        // inicjalizacja biblioteki curl
        $ch = curl_init( $url );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        // timeout na 30 sekund
        curl_setopt( $ch, CURLOPT_TIMEOUT, 30);
        // dodaj referer
        curl_setopt( $ch, CURLOPT_REFERER, $referer);

        // podaj POST-a
        if(isset($postArray))
        {
            curl_setopt($ch, CURLOPT_POSTFIELDS, implode('&', $postArray));
        }

        // rezultat
        $result->url        = $url;
        $result->referer  = $referer;
        $result->post     = $postArray;
        $result->data     = curl_exec( $ch );

        curl_close($ch);
        return $result;
 }
}

Metoda getFile przyjmuje trzy parametry:

  • $url, gdzie podajemy adres url dowolnej strony
  • $postArray, gdzie podajemy opcjonalne parametry do metody POST (jeżeli nie są podane dane wysyłane są GET-em)
  • $referer, adres url strony z której przyszliśmy

Przykłady użycia

$data = curl::getFile('http://adres_url');
print_r($data);

…wyświetli nam obiekt:

stdClass Object
(
    [url] => http://adres_url
    [referer] => http://adres_url
    [post] =>
    [data] => (...zawartość strony...)
)

W ten sposób możemy wykonywać już zapytania metodami GET i POST do innych serwerów. Rezultat ($result->data) możemy oczywiście zapisać do pliku.

Tags: ,