Sanghun Yang
Sanghun Yang

Reputation: 59

How to resolve call to undefined curl_init()?

There is a fatal error when I use curl from Laravel but a curl that exists in another file is working.

Why do these errors occur?

fatal error: call to undefined function App\Http\Controllers\curl_init()

App\Http\Controller\FcmController:

class FcmController extends Controller
{
    public function index()
    {
        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch,CURLOPT_POST, true);
        curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));

        $result = curl_exec($ch);
        dd($result);

        curl_close($ch);

App\Http\Controller\CurlContoller (It works):

class CurlController extends Controller
{
    public static function getCurl($url, $params)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url . $params);        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);;
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type:application/json; charset=utf-8"));

        $response = curl_exec($ch);
        curl_close($ch); 

        return json_encode($response);
    }

enter image description here

Upvotes: 0

Views: 794

Answers (1)

Leon Vismer
Leon Vismer

Reputation: 5105

Does it work if you prefix the function to a top level namespace \curl_init. For the statically called function inside CurlController it won't be needed.

Also, not specifically answering your question but if you are running Laravel 7 and above you could actually use the built in http-client implementation from Laravel. It is more expressive than curl.

Upvotes: 3

Related Questions