1

I have the class below, in order to analyze a URL

<?php
class URLFetcher {
    private $ch;
    private $url = '';

    public function __construct(string $url) {
        $this->url = $url;
    }

    public function fetch(): URLFetcher {
        $headers = [];
        $this->ch = curl_init($this->url);
        curl_setopt_array($this->ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',
            CURLOPT_HEADERFUNCTION => function($curl, $header) use (&$headers) {
                var_dump($header);
                $header2 = trim($header);
                if($header2 !== '') $headers[] = $header2;
                return strlen($header);
            }
        ]);
        exit(var_dump($headers));
        return $this;
    }
}
?>

I use var_dump in the closure in order to see the headers, as they come from CURL, and at the end, I use var_dump again in order to see all headers.

The problem is that there are no headers printed in the function and at the end, the $headers is printing the empty array.

If I do this without the class, everything works correctly. My question is what am I missing and the code does not work? I hypothesize that it has to do with the closure.

1 Answer 1

1

You simply forgot curl_exec($this->ch); at the end of the method.

public function fetch(): URLFetcher {
    $headers = [];
    $this->ch = curl_init($this->url);
    curl_setopt_array($this->ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',
        CURLOPT_HEADERFUNCTION => function($curl, $header) use (&$headers) {
            $header2 = trim($header);
            if($header2 !== '') $headers[] = $header2;
            return strlen($header);
        }
    ]);

    curl_exec($this->ch);

    exit(var_dump($headers));
    return $this;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh mon dieu!!! Damn copy paste. I feel a little embarassed, suppose I should :) Thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.