// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
<?php
$con = mysqli_connect("Localhost", "root", "", "rest_api");
if (mysqli_connect_errno())
{
echo "Connection Fail" . mysqli_connect_error();
}
header('Content-Type:application/json');
if (isset($_GET['token']))
{
$token = mysqli_real_escape_string($con, $_GET['token']);
$checkTokenRes = mysqli_query($con, "select * from api_token where token='$token'");
if (mysqli_num_rows($checkTokenRes) > 0)
{
$checkTokenRow = mysqli_fetch_assoc($checkTokenRes);
if ($checkTokenRow['status'] == 1)
{
if ($checkTokenRow['hit_limit'] <= $checkTokenRow['hit_count'])
{
$status = 'true';
$data = "Api hit limit exceed";
$code = '6';
}
else
{
mysqli_query($con, "UPDATE `api_token` SET `hit_count`= hit_count+1 WHERE `token` = '$token'");
$sql = "select * from collected_data ";
if (isset($_GET['id']) && $_GET['id'] > 0)
{
$id = mysqli_real_escape_string($con, $_GET['id']);
$sql .= " where id='$id'";
}
$sqlRes = mysqli_query($con, $sql);
if (mysqli_num_rows($sqlRes) > 0)
{
$data = [];
while ($row = mysqli_fetch_assoc($sqlRes))
{
$data[] = $row;
}
$status = 'true';
$code = '5';
}
else
{
$status = 'true';
$data = "Data not found";
$code = '4';
}
}
}
else
{
$status = 'true';
$data = "API token deactivated";
$code = '3';
}
}
else
{
$status = 'true';
$data = "Please provide valid API token";
$code = '2';
}
}
else
{
$status = 'true';
$data = "Please provide API token";
$code = '1';
}
echo json_encode(["status" => $status, "data" => $data, "code" => $code]);
?>
// simple steps
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}