Я создаю простой CRUD API в PHP и Curl, и у меня есть форма HTML, которая отправляет ID, FName, LName. Форма отправляется для создания. php, а затем вызывает ApiHandler. php, который устанавливает запрос Curl, а затем отправляет ее в read-api. php. Файл json обновляется новым пользователем и возвращает содержимое файла json в виде строки, но $ response является пустой строкой и не содержит 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/";
}
?>
Это API, который принимает запрос и должен сохранить его в файл и вернуть строку json.
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>");
?>
Кто-нибудь есть идеи, почему ответ пуст?