Reputation: 85
Javascript is a client-side language, so scripts can be read and copied.
Now consider this example.
<html>
<head>
<title>title</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$('#user').blur(function () {
var dataString = 'user=' + user;
$.ajax({
type: "POST",
url: "insertUser.php",
data: dataString
}
}
}
</script>
<label for='user' >User:</label>
<input id="user" type="text" />
</body>
insertUser.php :
<?php
$user = filter_input(INPUT_POST, 'user');
if (isset($user)) {
require_once("class.Database.php");
$db = Database::getInstance();
$mysqli = $db->getConnection();
$stmt = $mysqli->prepare("INSERT INTO Users (User) VALUES (?)");
$stmt->bind_param("s", $user);
$stmt->execute();
}
Could someone write a script in his localhost for inserting his own data using the path to insertUser.php? Anyway to solve this?
Upvotes: 0
Views: 61
Reputation: 1244
Could someone write a script in his localhost for inserting his own data using the path to insertUser.php?
Yes, anyone can post its own data using the path to insertUser.php
Anyway to solve this?
1. Check if request is of type Ajax and comming from your domain
if(($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') && ($_SERVER['HTTP_REFERER']=="http://yourdomain/url")) {
//Is ajax call
}
2. Cross-origin policy; that is denying post from other domains.
3. Generating tokens and validating the token on server side.
Upvotes: 0
Reputation: 593
There are many ways to stop user supplied malicious data inserting into database.
Regarding your situation, you can do the following steps:
Thanks, I hope this will surely help you to understand the security.
Upvotes: 0
Reputation: 637
Yes, anyone can send any data to your insertUser.php
About protection, that depend on use-case. Chceck who is sending data, authorize any request that should be authorized etc.
Best practice is to treat any data from outside (no matter where they came from) as if they were the most dangerous and malicious.
Upvotes: 1