PHP - Sanitizing Data For Sql Queries And Updates
I'm attempting to thoroughly sanitize my PHP app to avoid common exploits, and am working on guarding from SQL injections and such.
I'm using mysql_real_escape_string for data that comes from the user. I have a number of instances of the following: $ip = $_SERVER['REMOTE_ADDR']; $page = $_SERVER['PHP_SELF']; And then using those values to query or update SQL. Is it a best practice to also sanitize this sort of data? Similar TutorialsI have been reading this: http://www.phpro.org/tutorials/Filtering-Data-with-PHP.html#11 I am curious, how does one actually sanitize a php script? I know the site shows how to do it, but it really doesn't show in real world how to do it. Let me give you an example: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>PDI NCMR Admin Panel</title> <!--[if IE]><link rel="stylesheet" type="text/css" href="../CSS/ie.css" /><![endif]--> <!--[if !IE]> <--><link rel="stylesheet" type="text/css" href="../CSS/pdi.css" /><!--> <![endif]--></head> <body> <?php echo '<div id="admin">'; //Show the navagation menu require_once('../hf/nav.php'); echo '<hr id="line">'; echo '<h2 id="title">Latest NCMRs </h2>'; // Connect to the database require_once('../connectvars.php'); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // Retrieve the data from MySQL $query = "SELECT * FROM ncmr"; $data = mysqli_query($dbc, $query); echo '<table>'; echo '<tr><th>NCMR ID  </th><th>Part  </th><th>Date  </th><th>Actions  </th></tr>'; while ($row = mysqli_fetch_array($data)) { // Display the data echo '<tr class="ncmrdata">'; echo '<td>' . $row['NCMR_ID'] .'    </td>'; echo '<td>' . $row['Nexx_Part_Description'] .'  </td>'; echo '<td>' . date("M d,Y",strtotime($row['Added_By_Date'])) . '&  </td>'; echo '<td><a href="viewncmr.php?id=' . $row['id'] . '">Comment</a></strong>  <strong><a href="editncmr.php?id=' . $row['id'] . '">Edit</a>  <a href="printncmr.php?id=' . $row['id'] . '">Print</a>'; echo '</td></tr>'; } echo '</table>'; mysqli_close($dbc); require_once('../hf/footer.php') ?> </body> </html> How do I sanitize this? Or is it for inputs only? I'm researching ways that my server can be vulnerable. So far, I've strongly relied on regex to sanitize anything susceptible to user input/manipulation. Should I be trying other methods? Should I be changing input to html entities, even though they're bypassed w/ regex? Any recommendations on other methods to secure my server besides securing user input? What is the best way to santize a user input What covers it all without leaving the text with slashes Do i just need to escape my variables, or no i need to sanitize my queries as well? Whats the whole kitten kaboodle, anyone? In lieu of prepared statements, will this work effectively? Is it overkill? $username = mysqli_real_escape_string($conn,$_POST["username"]); $username = strip_tags(trim($username)); Can I write it this way: $username = mysqli_real_escape_string($conn,strip_tags(trim($_POST["username"]))); Are prepared statements a guarantee for defeating an injection attack? Or should they be used in conjunction with the above (or other) coding to bolster a database's defenses? Hi, I am new to PHP and mySQL. I am working on a golf site where it will need to have the user update info through text boxes. There are two things: 1) It will need to keep an average of the last 6 rounds. The user will need to be able to input the current round score and have it bump the oldest score of the database. 2) Also, i have a database of players that will populate a <select>. Is there a way to have the user be able to add/delete player names from this database? My question is what functions are needed to get this done. And how does one go about implementing them. Thanks in advance! Taylor I have a script that has a foreach loop. The script ususally runs for VERY VERY long time ( i have set_time_limit(0) Now what I need it to do is to echo some string at the end of each loop. However it doesn't. The script displays everything after its finished. That's not acceptable for me. I'm running xampp for windows. i dont know why it doesnt update the db..someone help?? $connection=mysql_connect("$server", "$username", "$password") or die("Could not establish connection"); mysql_select_db($database_name, $connection) or die ("Could not select database"); $strEditProfile = "UPDATE tblemployee SET EmployeeName='".$_POST["edit_thename"]."', Address1 = '".$_POST[edit_address1]."', Address2 = '".$_POST[edit_address2]."', DesignationID = '".$_POST[edit_des]."', Postcode = '".$_POST[edit_postcode]."', State = '".$_POST[edit_state]."', Country = '".$_POST[edit_country]."', Tel1 = '".$_POST[edit_contact]."' WHERE EEmail='".$_POST["edit_email"]."'"; $resEditProfile = mysql_query($strEditProfile); if($resEditProfile) echo "<img src=\"images/valid.jpg\" /> Profile updated!"; else echo "><img src=\"images/warning.jpg\">Error!";
So basically I am still starting off when it comes to learning PHP/MySQLi... I am looking to make a script that can do the following:
If I update say my homepage by just my normal cPanel editor plus another page named "News" but through an Admin section on my site (so basically inserting a new row into the database instead of manually doing it through my cPanel) - I would like it to display in a section on my homepage that days date along with the list of pages that were updated underneath it within that date, but with names I give the pages so instead of just saying index.php updated, I want it do say "Home Page Updated." I did have an attempt at this but just couldn't get it right. I would like to set a limit on how many different dates can be shown also.
Example:
July 12, 2014
Home Page Updated.
News Headlines Updated.
Staff Members Updated.
July 11, 2014
Home Page Updated.
July 10, 2014
Home Page Updated.
Contact Us Updated.
and so on...
Thank you to anyone who replies with some input, I have been going crazy trying to get this right and I just can't get it but badly want it.. Hi guys, I'm developing a website which allows people to connect and follow each other's activity (like Twitter, for example). To simplify everything, let's say I only have 2 tables: 1. Followers id | follower_id | id_to_follow ------------------------------------ 2. Activity id | member_id | message | time ----------------------------------------- Let's say John is following Jane and Bob. I want to create a "news" page and display the last 20 messages from Bob and Jane, chronologically. For small numbers, I'd do something like this: Select everything from the Activity table, check for every entry if the member is a friend of John's (in the Followers table) and, if so, display the message, ORDER BY `id` DESC. But, this is very inefficient, I guess, for larger numbers (I can't even think about how many queries would take to do this on a site like Twitter...). Any ideas of how to do the same thing more efficiently? Thank you. I have a form which shows products ordered from a catalog, it used to work fine when I had individual change buttons for each item, now I have to have multiple check boxes for removing items and the ability to change the quantities of multiple items with a single button. I know you have to use foreach and arrays for this but I am confusing myself trying to make the changes for it to update the correct items. Attached is a pic of what the form looks like and is how it is supposed to function here is the form part Code: [Select] <?php for ($basket_counter=0;$basket_counter<$_SESSION['ses_basket_items'];$basket_counter++) { $price=sprintf("%01.2f",$ses_basket_price[$basket_counter]); $quantity=$ses_basket_amount[$basket_counter]; $code=$ses_basket_stockcode[$basket_counter]; $itemID=$ses_basket_id[$basket_counter]; $name=$ses_basket_name[$basket_counter]; $image=$ses_basket_image[$basket_counter]; if ($country='AU') { $price=sprintf("%01.2f",($price*1.1)); $unit=sprintf("%01.2f",($price/$quantity)); } else { $unit=sprintf("%01.2f",($price/$quantity)); } ?><form method='post' action='' target="_self"> <tr> <td align='center' class='rescon' style="border-bottom:solid #330000 1px;"><input type="checkbox" name="remove[]" value="<?php echo $itemID; ?>" /></td> <td align='left' class='rescon' style="border-bottom:solid #330000 1px;"><img src="product_images/<?php echo $image; ?>" width="60" alt="<?php echo $name; ?>" title="<?php echo $name; ?>" /></td> <td align='left' class='rescon' style="border-bottom:solid #330000 1px;"><font size="+1"><?php echo $name; ?></font><br/><?php echo $code; ?></td> <td align='left' class='rescon' style="border-bottom:solid #330000 1px;"> </td> <td align='center' class='rescon' style="border-bottom:solid #330000 1px;"><input name="price" type="hidden" value="<?php echo $unit; ?>"><input type="hidden" name="pageLink" value="<?php echo $pageLink; ?>" /><input name="basket[]" type="hidden" value="<?php echo $itemID; ?>"><input name="quantity[]" style="vertical-align:middle;" type="text" value="<?php echo $quantity; ?>" size="2" maxlength="5"> </td> <td align='center' class='rescon' style="border-bottom:solid #330000 1px;">$<?php echo $unit; ?></td> <td class='rescon' align='right' bgcolor="#FFFF00" style="border-bottom:solid #330000 1px;">$<?php echo $price; ?> </td> </tr> <?php } if ($country='AU') { $totalprice=sprintf("%01.2f",array_sum($ses_basket_price)); $totalprice=sprintf("%01.2f",($totalprice*1.1)); } else { $totalprice=sprintf("%01.2f",array_sum($ses_basket_price)); } $totalitems=array_sum($ses_basket_amount); ?> <tr><td align='left' colspan='4' valign="top" class='cartbot'> </td> <td align='left' valign="top" class='cartbot'><?php echo $totalitems; ?> Items</td> <td align='right' colspan='2' class='cartbot'><?php echo "<b>Subtotal: $".$totalprice." </b>"; ?></b></td> </tr> <tr> <td align='left' colspan='5' valign="top"><input type="submit" id="change" name="change" style="vertical-align:middle;" value="Change"></td> <td align='right' colspan='2'> </td> </tr></form> and here is the processing part at the top of the page which I have sorta shagged, could use some help getting it to update the correct items for remove and quantity changes // cart application if (isset($_POST['change'])) { $basket = $_POST['basket']; // check faor AU to include GST if ($country='AU') { $itemprice = sprintf("%01.2f",(($_POST['price']/11)*10)); } else { $itemprice = $_POST['price']; } $itemqty = $_POST['quantity']; $newprice = ($itemprice*$itemqty); if (($basket!="") && (isset($_POST['change']))){ if ($_SESSION['ses_basket_items']){ // basket position $basket_position_counter=0; // double entry flag set to NO $double=0; // Check for existing basket id if ($_SESSION['ses_basket_items']>0){ foreach ($ses_basket_id as $basket_item){ if ($basket_item==$basket){ // If exist flag for update $double=1; $basket_position=$basket_position_counter; } // Add new basket position $basket_position_counter++; } } // Update basket with new quantity and price if ($double==1){ $ses_basket_amount[$basket_position]=$itemqty; $ses_basket_price[$basket_position]=$newprice; } } // Delete Item when set to 0 if ($itemqty == "0") { array_splice ($ses_basket_name, $basket_position, 1); array_splice ($ses_basket_amount, $basket_position, 1); array_splice ($ses_basket_price, $basket_position, 1); array_splice ($ses_basket_stockcode, $basket_position, 1); array_splice ($ses_basket_image, $basket_position, 1); array_splice ($ses_basket_id, $basket_position, 1); $_SESSION['ses_basket_items']--; } if (isset($remove) && ($remove!='')) { $remove = $_POST['remove']; if(count($remove) > 0){ foreach($remove AS $removed){ array_splice ($ses_basket_name, $basket_position, 1); array_splice ($ses_basket_amount, $basket_position, 1); array_splice ($ses_basket_price, $basket_position, 1); array_splice ($ses_basket_stockcode, $basket_position, 1); array_splice ($ses_basket_image, $basket_position, 1); array_splice ($ses_basket_id, $basket_position, 1); $_SESSION['ses_basket_items']--; } } } } if ($_SESSION['ses_basket_items']==0){ unset($_SESSION['ses_basket_items']); unset($_SESSION['ses_basket_name']); unset($_SESSION['ses_basket_amount']); unset($_SESSION['ses_basket_price']); unset($_SESSION['ses_basket_stockcode']); unset($_SESSION['ses_basket_image']); unset($_SESSION['ses_basket_id']); header("Location: $pageLink"); } } the array variables I have here are $basket, $remove and $quantity. Is it possible - and reasonable - to have one Form which allows Users to create a new record (i.e. do an INSERT) and which also allows Users to modify an existing record (i.e. do an UPDATE)? When a User registers at my website, not only do they create a record in the "member" table, but one of the required fields is "First Name". What that means is that when I allow Users to edit details in their Profile - most of which were not included in registration to streamline the process - I don't have to worry about doing an INSERT, because I already created a "member" record and on the "Edit Details" page the first field is "First Name" so that is a hook so to speak where they can enter more info about themselves like... Code: [Select] - Location - Date of Birth - Interests - Bio and so on... So here is my problem which I just discovered... Also in my User Profile, I allow Users to answer several open-ended questions like... Code: [Select] 1.) Why did you decide to start your own business? 2.) What advice would you share with others on what NOT to do? The problem is that these questions exist in the "bio_question" table and the answers that I am trying to get from Users will be stored in the "bio_answer" table but no record currently exists?! So do I need both an "INSERT Answers Form" *and* an "UPDATE Answers Form", or can I combine things into one form?! Hope that all makes sense?! Debbie Would there be any feasible way of combining the two Update statement below into one? The Members Table has id, username, password, and application_id The Application Table has the application id, the users application information and whether or not the application is approved. if($_GET['approved']=="update"){ $approved=$_GET['approved']; $approved=sanitize($approved); if($approved=="y"){ $id=(int)$_GET['id']; $username=$_GET['username']; $username=sanitize($username); $password=$_GET['password']; $password=sanitize($password); $approved_sql='UPDATE members SET username="$username" password="$password" application_id="$id"'; $approved_result=mysql_query($approved_sql); $approved_rows=mysql_affect_rows(); $update_approved_sql='UPDATE application SET approved="y" WHERE id="$id"'; $update_approved_result=mysql_query($update_approved_sql); $update_approved_rows=mysql_affect_rows(); if($approved_rows==1 && $update_approved_rows==1{ header("Location: ./index.php??admincp=investors&view=applications&id=1&approved=updated"); } } } I got to thinking late last night (which generally leads to trouble), so please be gentle if some educating is in order, as I suppose I will touch a few related issues. As I develop my database, I will include two seperate columns. One for the time/date that an order was placed. A second for the time/date that an order is updated (unless there's a better way, please inform me). I pressume that if a record is updated several times, it will continually overwrite the time/date to the point that I will only see the latest update. Now I was wondering if I could create a third column to keep count of the number of times a record had been updated, so if it were altered 16 times, I would know when the last update occurred, and have the count number also. Will something like this coding work? SELECT updates FROM myTable WHERE id="$id" $updates =n if n<1, n=1 }else{ n++ Hi there I'm a little bit of a newbie when it comes to PHP, and I have tried to find my answer on google and on other websites related to php development.
My question is what do I need to be researching / learning to automatically update a page with content.
For example, if I have a database field called breaking news and this text string is flashed at the bottom of the screen on a scrolling bar.
When the field changes value in MYSQL, I would like the page to automatically update the page without a need for a page refresh.
All I need is some advice on what I need to search for in order for me to learn the coding myself.
I'm thinking AJAX, but not too sure.
Thank you for reading.
Ok, i've driven myself mad trying to figure this out. While I'm new at php I really think this should work. Could someone look at this and point me in the right direction? Ok background info: I have three tables that I'm selecting from. I want to find the records in TABLE A that match these three criteria and "Join" per say. the SELECT does exactly what I want and works. My issue is when I try to LOOP through and pull certain information make adjustments in other tables Table C.. it only adjust as if it's gone through ONLY one loop. It will only do last record. I want it to loop through the records it's found and Update the field in Table C to the balance of TABLE C + TABLE B price. Then update TABLE A with a value of 1 and LOOP and do it again until all records found in the original select are done. CODE: Code: [Select] require_once ('./includes/config.inc.php'); $query = "SELECT table_a.id, table_a.table_b_id, table_a.user_id, table_a.unit_returned, table_b.id, table_b.title, table_b.price, table_b.closed, table_c.id, table_c.nick, table_c.balance FROM table_a, table_b, table_c WHERE table_a.unit_returned= 0 AND table_b.closed = 1 AND table_b.id = table_a.table_b_id AND table_c.id = table_a.user_id "; $result = mysql_query($query); $num = mysql_num_rows($result); echo "<table border='1'>"; while ($row = mysql_fetch_array($result, MYSQL_NUM)) { echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td><td>$row[4]</td><td>$row[5]</td><td>$row[6]</td><td>$row[7]</td><td>$row[8]</td><td>$row[9]</td><td>$row[10]</td></tr>"; $newbalance = $row[6]; $newbalance2 =$row[10]; $finalbalance = $newbalance+$newbalance2; $userid = $row[2]; $signid = $row[0]; echo "$newbalance". " $newbalance2" . " $finalbalance"."<br>". "$userid ". "<br>"."$signid"."<br>"; $query = "table_c SET balance=".$finalbalance." WHERE id=" .$userid ; $result = mysql_query($query); } $query = "UPDATE table_a SET unit_returned=1"; // THIS I WANT TO DO TO ALL RECORDS AS I LOOP AS WELL or at the end seeing as above should find all the records anyways. wouldn't matter to me. $result = mysql_query($query); ANY HELP WOULD BE GREATLY APPRECIATED THANKS!!!! so MUCH! Ok this has been driving me crazy for days now. I need to update my DB with multiple data parsed from an XML feed. I need some help in putting together the query. Currently I have: Code: [Select] $xml= 'test-feed.xml'; // URL for feed. try{ $feed = new SimpleXMLElement($xml, null, true); }catch(Exception $e){ echo $e->getMessage(); exit; } $sqlxml = ""; $arr = array(); foreach($feed->property as $property) { $propertyid = (string)$property->id; foreach($property->images->image as $image) { $i = 0; $url = (string)$image->url; $arr[] = "UPDATE property SET url = '$url' WHERE prop_id = '$propertyid', "; $i++; } } foreach($arr as $result) $sql .= $result; $sql = rtrim($sql, ","); echo $sql; if(!mysql_query($sql)){ echo '<h1 style="color: red;">Error</h1><p>', mysql_error(), '</p>'; } else { echo '<h1 style="color: red;">Property data successfully added to database!</h1>'; } This structures the query correctly for a single update but repeats it which then throws a MYSQL Syntax error. I am not sure of the correct syntax to use for multiple inserts?? What I get returned at the moment is: Code: [Select] UPDATE property SET url = 'ImageId=X1000245' WHERE prop_id = 'A1234', UPDATE property SET url = 'ImageId=X1000296' WHERE prop_id = 'A1234', UPDATE property SET url = 'ImageId=P3&ImgId=X1000237' WHERE prop_id = 'ABC1234', Need some intervention guys Thanks in advance GT Let's say I have 1 table and 100 rows in this table. The table is simple and only contains an Auto Increment ID field and a load_count field. Let's say I grab all the user's information from the users table. It's stored into a variable as an array: $pun_user. Now, to get access this user data, it selects all the data each refresh and sets it to $pun_user for extraction later. My idea: Create a $_SESSION['user_id'] = $pun_user['user_id'] And then when using updating stuff via ajax requests, I can just do SELECT blah from users where where user_id = $_SESSION['user_id'] instead of: calling the main query to enter all the data into $pun_user, then do that query AGAIN and do SELECT blah from users where user_id = $pun_user['user_id'] Is the $_SESSION way going to take a performance hit on the server? Or is the MYSQL way a more detrimental approach? Which way is faster, and less intrusive on the server? Edited by Monkuar, 22 January 2015 - 10:35 PM. When a post is approved I only want $details = $_POST['newstitle']; update_user_actions(8, $details); Being posted once with the corresponding news article title. Any way to achieve this? Right now it is looping through all of the titles and is posting them all. Code: [Select] foreach($posts as $post) { $displayName = ucwords("${post['firstname']} ${post['lastname']}"); if (isset($_POST['approve'])) { if(is_array($_POST['approve'])) { $keys = array_keys($_POST['approve']); $id = $keys[0]; $details = $_POST['newstitle']; update_user_actions(8, $details); $sql = "UPDATE `news` SET `newsdate` = NOW(), `approved` = 1 WHERE `id` = '$id'"; header("Location: " . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] ); } } else if (isset($_POST['deny'])) { if(is_array($_POST['deny'])) { $keys = array_keys($_POST['deny']); $id = $keys[0]; $sql = "UPDATE `news` SET `newsdate` = NOW(), `approved` = -1 WHERE `id` = '$id'"; header("Location: " . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] ); } } else if (isset($_POST['delete'])) { if(is_array($_POST['delete'])) { $keys = array_keys($_POST['delete']); $id = $keys[0]; $sql = "DELETE FROM `news` WHERE `id` = '$id'"; header("Location: " . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] ); } } if(isset($sql) && !empty($sql)) { mysql_query($sql) or die(mysql_error()); } ?> Is there any way to have a field that will update any time its row is updated?
My situation is that I will have multiple devices writing to a database, and in one case the time that is being kept track of is important. And the devices writing to the database are a bit difficult to keep accurate times on, so instead of writing the time from the devices themselves, I was hoping I could just have a field update itself. I know it can be done on INSERT, but I do not want to do an INSERT every time.
Thanks!
|