I am trying to make a simple REST API with PHP and i have got this so far:
$mysqli = new mysqli("localhost", "root", "root", "db");
$method = $_SERVER["REQUEST_METHOD"];
$request = explode("/", trim($mysqli->real_escape_string($_SERVER["PATH_INFO"]),"/"));
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}
switch ($method) {
case "GET":
if ($stmt = $mysqli->prepare("SELECT * FROM ".$request[0]." WHERE id=?")) {
$stmt->bind_param("i", $request[1]);
$stmt->execute();
$res = $stmt->get_result();
echo json_encode($res->fetch_object());
$stmt->close();
}
else echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
break;
}
$mysqli->close();
It works like a charm, but i need to be able to only accept requests from the clients i want, in other words, i need it to be able to deny conexions from unauthorized clients.
After some thinking i thought about implementing something similar to salt hashes with passwords but it probably is not the best approach and i would not know how to make that.
Other idea was sending with the ajax request some kind of preset phrase, but it could be easily "stolen" with some kind of network analyzer like Wireshark.
Those are the ideas i have got so far and i would really appreciate some help.
Edit: Right now i have no problem sending plane data or with security issues, all i want is beeing able to receive data only from the clients i want.