I'm printing an ID from the database in the order to create a SQL statement INNER JOIN with that ID. So, the problem is that the "user" can change it from the debugging tool and easy "crack" the site.
Check it out:
<select name="brand">
<?php
# Print brands names
for ($i=0; $i < count($brandsql); $i++) {
print '<option value="' . $brandsql[$i]['brand_id'] . '">' . $brandsql[$i]['brand_name'] . '</option>';
}
?>
</select>
So... My question is: Is there a way to do this without print the ID to the HTML? Note that I'm getting the ID value with JavaScript:
$('#brand').change(function(e){
$.getJSON("q.php", {type: 1, brand: this.value})
.done(function(e){
// I print the results to the user.
});
});
Exist better way to do this?
Simple answer: You can't.
What you are describing is called SQL Injection
, a method of "cracking" a website by injecting SQLs which were never intended by the developer. This can result in horrible situations like deleting your database or getting access to the admin account.
To prevent this, your only possibility is to sanitize the input with PHP, for example with filter_var()
:
$input = filter_var($_POST['brand']);
Even though the situation isn't that terrible in your case, I'd recommend you implement security measures. Never trust user input. It's evil.
Printing an ID in a form is always a risk. The only way to prevent the user from fiddling is to add some sort of validation on the server side.
If you have some way of storing this data on the server side, you need to do it that way. Maybe linking it to a session id or something like that.
And as mentioned in the other answer(s), make sure if you do have a fields going directly into SQL that you prevent SQL injection.
What ever you send to the user is totally in his hand, you cannot prevent him from changing the values, even you cannot prevent the keys f12, ctrl+u etc buttons in the browsers using javascript, it is not allowed by the browsers.
Got same problem. Simple solution however. When you giving user form that should contain ID from DB, put that ID in $_SESSION[edit_id]. He can't fiddle with that. And right after you process given form you just do unset($_SESSION[edit_id]). This way no need for value in form, it just adds more managment to your code, but it's totally worth for elimination of this security risk.
I cant really understand exactly what you are saying when you describe your problem or what you mean by "crack the site" but basically you must validate the users input on the server and always assume they can sumit any value to your server.
So if your problem is that you only want a user to print records with a certain 'id' then you must identify the user (usually with a username/ password, but for a simple form you can just use a password or pin number etc) and store the ids that the user is allowed to print on your server. Then check that the id that is submitted is permitted for that user.