I'm building a simple CRUD API in PHP and Curl and I have an HTML form that sends ID, FName, LName.
The form is posted to create.php and then calls ApiHandler.php that set up the Curl request, then send it to read-api.php.
The json file is updated with the new user and returns the json file content as a string but $response is an empty string and doesn't contain the json content
$response = curl_exec($handle); // $response = ""
ApiHandler.php
<?php
function callAPI($method, $url, $request){
$handle = curl_init();
switch ($method){
case "GET":
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
break;
case "PUT":
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "PUT");
if ($request)
curl_setopt($handle, CURLOPT_POSTFIELDS, $request);
break;
case "POST":
curl_setopt($handle, CURLOPT_POST, 1);
if ($request)
curl_setopt($handle, CURLOPT_POSTFIELDS, $request);
break;
case "DELETE":
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "DELETE");
default:
if ($request)
$handle = sprintf("%s?%s", $url, http_build_query($request));
}
curl_setopt($handle, CURLOPT_HTTPHEADER, [
"Content-Type: application/json; charset=UTF-8",
"Access-Control-Allow-Origin: *"
]);
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($handle); // $response = ""??
$errno = curl_errno($handle);
$err = curl_error($handle);
curl_close($handle);
if ($errno) {
return "cURL Error #:" . $err;}
else {
return $response;
}
}
function getBaseUrl()
{
return "http://localhost/api/";
}
?>
This is the api that take the request and supposed to save it to a file and return the json string.
create-api.php
<?php
include('ApiHandler.php');
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$postData = file_get_contents('php://input');
$data = array();
parse_str($postData, $data);
$json = file_get_contents('employees.json');
$obj = json_decode($postData,true);
$jsonarray = json_decode($json,true);
array_push($jsonarray,$obj);
$result = json_encode($jsonarray);
$file = fopen('employees.json','w');
fwrite($file,$result);
fclose($file);
return $result;
?>
create.php
<?php
include('ApiHandler.php');
$url = getBaseUrl()."create-api.php";
$postdata = file_get_contents("php://input");
$id = $_REQUEST["id"];
$firstname = $_REQUEST["firstname"];
$lastname = $_REQUEST["lastname"];
$arrayRequest = array("id"=>$id,"firstname"=>$firstname,"lastname"=>$lastname);
$json = json_encode($arrayRequest,true);
$output = callAPI("POST", $url, $json);
var_dump($output);
echo ("<p>$output</p>");
?>
Does anyone have any idea why the response is empty?