开发者

php make posts safe

开发者 https://www.devze.com 2023-03-28 03:46 出处:网络
I am having trouble with the simplest of tasks. The html page has a single textarea tag that sends the data to a php file using $.get() with jquery

I am having trouble with the simplest of tasks. The html page has a single textarea tag that sends the data to a php file using $.get() with jquery

From there I use a variety of methods from htmlspecialchars to addslashes. But nothing seems to work the way it should, either throwing off an error because a single \ was left behind or not preserving newlines.

How can I pass a te开发者_如何学编程xtarea's value to a php file, make it injection proof and json compatible. So that when I access it with mysql and format it using $.formatJSON(). It works without any issues and preserves all the new line characters?

//php

$result = htmlspecialchars($_GET["message"]);

mysql_query("INSERT INTO table (message) VALUES ($result)");


//jquery
$.ajax({
 url:("http://websitename.com/post.php?message=" + message + "&callback=?"),
 dataType: 'JSONP',
 success:function(json){
    callback($.parseJSON(json));
 },
 error:function(){
 },
});


The recommended practice nowadays is to use prepared statements. This way SQL injections are out of the question. If this proves to be too slow after profiling the code, you should resort to using mysql_(real_)escape_string.

As another step of security you can install an Intrusion Detection System like PHPIDS to add another security layer.

Don't use addslashes or similar, they are not meant for escaping user input for SQL queries.

Also in your case you should not pass the textarea contents via GET but rather via POST as described in the jQuery documentation. Furthermore, the dataType should be 'json' and you don't need to parse it afterwards. An example for getting JSON from PHP in jQuery is given here.


Before using a value in a MySQL query, use mysql_real_escape_string. In addition, you should put single quotes around $result in ($result).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号