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.
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.
A lot of people think they need to be able to do this, but it's not possible.
That's the answer to your question: It's not possible to reliably and securely only allow trusted clients to connect over a public network (i.e. the Internet) to your publicly accessible server. Any mechanism you attempt to create to stop unauthorized clients can be defeated by reverse engineers.
Your time is better spent ensuring that your server-side code runs correctly even if the client-side software is malicious.