Issue
The following function transfers a curl delete request to an API, and returns the response to PHP.
The API returns a JSON array for all requests (get, post, put and delete), and everything works fine for everything except delete requests.
The following curl function doesn't seem to be working properly:
function curl_delete($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_URL,$url);
$result = curl_exec($ch);
curl_close($ch);
return $result; // <-- Function ALWAYS returns whether this is here or not??!..
}
This is how I call the function from PHP:
// [DELETE API URL]:
$url = 'http://localhost/website/api/users/user/id/123';
$html = json_decode(curl_delete($url), true);
If you look at the function (above), whether or not I include the return statement (at the end of the function), the result of the curl call (the jsonified array) always gets dumped to the browser after the function has completed - which is not what I want.
If I then say echo count($html)
, the correct length of the returned result will print, and the $html
array is working fine, however I can't seem to prevent it from automatically dumping to the screen.
This does not happen for any of the other curl functions, which just work as expected.
QUESTION:
Is this normal behaviour? How do I prevent the json from dumping to the screen?
PS Using Codeigniter & Phil Sturgeon's REST Server
Solution
You should try Phil Sturgeon's cURL library for Codeigniter and its method simple_delete()
:
$this->load->library('curl');
$url = 'http://localhost/website/api/users/user/id/123';
$response = $this->curl->simple_delete($url);
$html = json_decode($response, TRUE);
If it does not solve your problem, maybe you will have to take a closer look at your REST server.
Answered By - Jérôme Answer Checked By - Senaida (WPSolving Volunteer)