简体   繁体   中英

How can I have a public function to run all my PHP cURL requests?

I have a basic RESTful API setup using cURL for all my requests.

At the moment, I am attempting to split out all my functions to have one function that runs all my requests.

For example, I have the following which can be called from localhost/api/getUserData

private function getUserData() {
     $url = 'localhost/api/users/';
     runApiCall($url);
}

That function then goes on to pass the URL to runApiCall() , which is the following:

function runApiCall($url) {

     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);
     $result = curl_exec($ch);
     curl_close($ch);

     $this->response($result, 200);
}

Although, I keep getting an error in my console of http://localhost/api/getUserData 500 (Internal Server Error)

The API was working perfectly fine before I split it out.

EDIT:

If I simply change my getUserData() function to the following, it works perfectly fine:

private function getUserData() {
     $url = 'localhost/api/users/';

     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
     curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);

     $result = curl_exec($ch);
     $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     curl_close($ch);
     $this->response($this->json($result), $status);
}

You have an issue with scope as you are inside a class.

private function getUserData() {
     $url = 'localhost/api/users/';
     $this->runApiCall($url); // call $this object's runAppCall() function
}

If you had error handling enabled, you'd see an error thrown by PHP telling you that it could not find the method runApiCall() . This is because you are inside a class and must explicitly tell PHP to run the method on the class.

You can do this by:

private function getUserData() {
     $url = 'localhost/api/users/';

     // EITHER
     $this->runApiCall($url); 

     // OR
     self::runApiCall($url);
}

In future, I'd recommend adding this line at the route of your application when you are developing, then set it to false in production:

ini_set('display_errors', 1);

This will now log any PHP errors to the browser, making it much easier for you to debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM