In page included comment form. With comment I want to write in mysql url from which the comment is posted.
The posted comment to php file will send with jquery, like $.post("_record_comments.php", data_to_send_ajax_post, function(result_of_record) {
To php file want to send current url (part of url)
Can create jquery variable like this
var url = '<?php echo htmlspecialchars( $_SERVER['PHP_SELF'] , ENT_QUOTES, "UTF-8"); ?>'
or
var url = '<?php echo htmlspecialchars( $_SERVER['QUERY_STRING'] , ENT_QUOTES, "UTF-8"); ?>'
but from my knowledge anyone can set for var url
any value, like var url = 'wrong-url.html'
. In such case I would send incorrect url to php file.
How can prevent users to change value of var url
and send to php correct url of current page?
To prevent random scripts from interacting with your script run all your code in your own scope:
(function () {
var url = "";
}());
Now url
is not accessible by anything else that might run in the global scope.
Note that this prevents changing of the url
variable, but there are still plenty of ways a client can shoot himself in the foot and send the wrong request, but why would they? If there are security issues make sure you implement them first and foremost on the server.
Perhaps this is also worthwhile to mention: the JavaScript security model relies on the foundation that all code is safe to run. You (and your client) is in charge of what code runs on the page. If a third party can also run code you've got a problem. This is why it's so important to always encode your input, if an attacker can inject HTML it can inject an XSS script.
The correct way to encode variables in JavaScript is to use json_encode
:
var url = <?php echo json_encode($_SERVER["PHP_SELF"]);?>;
htmlspecialchars
is an encoding function used to print to an HTML context.