Hi folks, This time I'm in some trouble. Please help me in this issue. My site will have forms with number of text fields, I'll store the form data in MySQL database and later those data will be fetched and populated on web pages. Now, the forms are filled up by users, so I need to escape all unwanted characters while keeping the necessary ones intact. Suppose I get a field data in the form of $_POST['field_name']. So far I was using combination of mysql_real_escape_string, htmlentities, striptags and htmlencode functions. But I guess, I'm not using them properly one after another. Can you please give me the exact function set for: 1. Inserting data into database 2. Fetching data and populating into database Like: function1(function2(function3($_POST['field_name']))) while inserting and functionX(functionY(functionZ($row['column_name']))) while showing them on webpage. Please describe, what specifically the functions are doing, so that I can keep the required special characters (like some html tags for a rich text input field) intact.
heres my little function: function clean($input) { //remove whitespace... $input = trim($input); //disable magic quotes... $input = get_magic_quotes_gpc() ? stripslashes($input) : $input; //prevent sql injection... $input = is_numeric($input) ? intval($input) : mysql_real_escape_string($input); //prevent xss... $input = htmlspecialchars($input); return $input; } PHP: Example usage: //apply the function to an array of user submitted data... $_POST = array_map('clean', $_POST); //or individually like... $message = clean($_POST['message']); PHP:
Wow! This one charmed me. Can you tell me, if it'll strip html tags also? If no, then how can I strip them? Again, If the input to the text field is <b>Hello world</b> How can I store it in database and while displaying them on page, how can I show it intact (ie. <b>Hello world</b>) instead of like this Hello wolrd
Here is a simple str_replace function. You can add to the array anything you do not want to be inputed. $banned=array("<", ">", "-", "'", "/", "[", "^", "]", "+", "{", "}", "$", "%", "(", ")", "&", "#", ";", "bad words"); FunctionXYZ(str_replace($banned,"",$_POST["field_name"]));
Thats one of the functionalities of the function , it doesnt strip html it just doesn't execute it, it will print it instead - this will prevent xss.
It's better to escape the characters, rather than delete them. If you needed to store the value "Jean-Luc Piccard" in a name field, the name would be "JeanLuc Piccard" -- this isn't acceptable. 1. How do you know it was an SQL injection? 2. How are you using mysql_real_escape_string? Post code and we can solve the real problem. mysql_real_escape_string will block all SQL injection attacks if properly used.
PHP Framworks (cakephp, CodeIgniter, Zend) have implemented such filters, so, if you are using php frameworks, you can relax add do not think about it