Jump to content

Drongo_III

Members
  • Posts

    579
  • Joined

  • Last visited

Everything posted by Drongo_III

  1. You could set an onClick event for your buttons <a href="#" onClick="runFunctionEuro()">BUTTON</a> Then have javascript code like: <script text/javascript> function runFunctionEuro(){ self.location.href = "/yourpage.php/?currency=euro"; } </script> That would reload the page with a query string that you can grab as a GET variable when the page relaods. Something like: <?php if(isset($_GET['currency'])){ $_session['currency'] = $_GET['currency']; } ?> That's just an example and you could make the javascript bit much better by simply having one function and passing the currency as an argument but it illstrates the point. Also I wouldn't suggest directly using $_GET variables in your code without ensuring they're safe for your purpose.
  2. Thanks Req. Least it's not just me being silly then That's a real pain though- can be quite time consuming trying to look through a huge xlm output. Is there a better way to print out all of the xml file as an array? I looked at SimpleXMLIterator which might be useful. Any thoughts?
  3. Hi Guys I'm pulling an xml feed from Youtube to get some practice with traversing xml. The thing I don't quite get is that when i create an simple xml object and do print_r (to concisely see what's in the xml) it doesn't show everything that's in the actual xml file. Is that usual? And is using print_r on an xml object a stupid idea? For instance this element is missing: <media:thumbnail url="http://i.ytimg.com/vi/6reEBParHzQ/0.jpg" height="360" width="480" time="00:09:41.500"/> $xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/users/JREAMdesign/uploads'); echo "<pre>"; print_r($xml);
  4. Ok bit confused now. I thought you said nothing was getting inserted? If that query does work and you are inserting an entire row then I cant see what the issue is??
  5. Any php errors? Are you quite sure you've made a successful connection the database on $dbc?
  6. Ok are you sure all the columns you name in your query exist in the table? Do you get a "query failed" message from this code: $result_insert_user = mysqli_query($dbc, $query_insert_user); if (!$result_insert_user) { echo 'Query Failed '; }
  7. What currently happens when you run it? Do you just insert an empty row? Or does nothing insert at all?
  8. Escaping the data will make it safe. But if you want to be 100% use prepared statements - either PDO or mysqli. That should make your queries pretty sql-injection-proof by all accounts - as long you construct the query properly.
  9. Also - if you do get that script working you will want to use mysql_real_escape_string() on all of your data because inserting raw data into the query makes you ripe for sql injection. Check it out here - http://php.net/manual/en/function.mysql-real-escape-string.php
  10. Maybe this makes more sense. Give it a go <?php include ('database_connection.php'); if (isset($_POST['formsubmitted'])) { $error = array();//Declare An Array to store any error message if (empty($_POST['mobileno'])) {//if no name has been supplied $error[] = 'Please Enter a Mobile Number ';//add to array "error" } else { $mobile= $_POST['mobileno'];//else assign it a variable } if (empty($_POST['fname'])) {//if no name has been supplied $error[] = 'Please Enter a First name ';//add to array "error" } else { $fname = $_POST['fname'];//else assign it a variable } if (empty($_POST['lname'])) {//if no name has been supplied $error[] = 'Please Enter a Last name ';//add to array "error" } else { $lname = $_POST['lname'];//else assign it a variable } if (empty($_POST['email'])) { $error[] = 'Please Enter your Email '; } else { if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA- Z0-9\._-]+)+$/", $_POST['email'])) { //regular expression for email validation $email = $_POST['email']; } else { $error[] = 'Your EMail Address is invalid '; } } if (empty($_POST['passwd1'])) { $error[] = 'Please Enter Your Password '; } else { $password = $_POST['passwd1']; } if (empty($_POST['passwd2'])) { $error[] = 'Please Verify Your Password '; } else { $password = $_POST['passwd2']; } if (empty($error)) //send to Database if there's no error ' { //If everything's OK... // Make sure the mobile no is available: $query_verify_mobileno = "SELECT * FROM userdtls WHERE mobileno = '$mobileno'"; $result_verify_mobileno = mysqli_query($dbc, $query_verify_mobileno); if (!$result_verify_mobileno) {//if the Query Failed ,similar to if($result_verify_mobileno==false) echo ' Database Error Occured '; } if (mysqli_num_rows($result_verify_mobileno) == 0) { // IF no previous user is using this number . // Create a unique activation code: $activation = md5(uniqid(rand(), true)); $query_insert_user = "INSERT INTO userdtls (mobileno, pass, fname, lname, email, activation) VALUES ( '$mobile', '$password', '$fname', '$lname', '$email', '$activation')"; $result_insert_user = mysqli_query($dbc, $query_insert_user); if (!$result_insert_user) { echo 'Query Failed '; } if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull. // Send the email: $message = " To activate your account, please click on this link:\n\n"; $message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation"; mail($Email, 'Registration Confirmation', $message, 'From: rahul19dj@gmail.com'); // Flush the buffered output. // Finish the page: echo '<div class="success">Thank you for registering! A confirmation email has been sent to '.$email.' Please click on the Activation Link to Activate your account </div>'; } else { // If it did not run OK. echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>'; } } else { // The mobile number is not available. echo '<div class="errormsgbox" >That mobile number has already been registered.</div>'; } } else {//If the "error" array contains error msg , display them echo '<div class="errormsgbox"> <ol>'; foreach ($error as $key => $values) { echo ' <li>'.$values.'</li>'; } echo '</ol></div>'; } mysqli_close($dbc);//Close the DB Connection } // End of the main Submit conditional. So now you are actually assigning a value to : $mobile $fname $lname $email $password
  11. I could be wrong but it looks to me like you are overwriting the variable $name with various pieces of $_POST data and then running a query with variables that don't appear to exist anywhere. Unless I am missing something I can't really see where the majority of htese variables come from? Which would explain why nothing is getting inserted.
  12. Errm it looks a bit like you're assigning values to the same variable throughout your script: [b]$name[/b] = $_POST['mobileno'];//else assign it a variable And then in your query you appear to be referencing variables that don't exist...e.g. $lname Or is there more to the script?
  13. Do you have errors turned off? Just wondering if you're not supressing an error?
  14. Then before I wind up asking any more questions I shall now pronounce this thread SOLVED! I really feel someone ought to make some sort of speech to mark the occasion... oh well. You won't get rid of me this easily - i'll be back
  15. Thank you to everyone who has commented on this. It has really helped loads. Psycho - i totally see what you mean, especially about sending htmlentity data into the database. So to summarise with an example. If i was going to store the data from a 'name' field I would very simply have to just: [*]trim the data [*]run a regex along the lines of /^[a-zA-Z\-\.\'\s\b]{2, 25}$/ - just to ensure it's roughly along the lines of what I need and that nothing majorly bad is likely to be used in the rest of the application [*]type cast the variables where appropriate [*]Use prepared statement to store the data Then upon retrieval from the database manipulate it as is required. So if it's going to the browser ensure the data is htmlentitied. For my sanity and moral - would anyone add anything to this or is that about right and a safe way to go? In my opinion, keeping the data "pure" is keeping it EXACTLY as entered. For example, I see some people using htmlentities() on data before storing it in the database. But, htmlentities() is designed to safeguard data being displayed in an HTML page. If the data needed to be output into a text file or some other format it could be made unreadable because of the translation of the data. So, I would always advise not excluding data unless there is a need to. Only escape/cleanse the data as needed based upon the specific output/usage. Different "languages" don't have any particular issues with specific data that I am aware of - it is HOW the data is used. You can always make a determination when the other processes/languages are implemented to determine what procedures are needed to safeguard against possible data issues. Besides, the hyphen or apostrophe could *potentially* cause issues within some processes, but it wouldn't make sense to exclude those for a name field. Again, my opinion, is to only reject content when there is a legitimate business need (e.g. no letters in a phone number). Then escape/sanitize the data as appropriate based upon the usage/output. The only time I would strip out content without the user's knowledge would be something like a phone number. I would strip out the formatting characters (periods, spaces, parents, etc.) and store only the digits of the phone number. That way I could display the phone number in a consistent format during output.
  16. One other question Christian If you run a function that escapes data like that, then push it through PDO prepared statements, would you end up double escaping the data? When it comes to sending output to other systems (web browsers, shell, file systems, DB engines, etc), I always escape output. Regardless of whether or not I know of any potential manner in which to exploit it. Even if I believe it to be completely secure, there is always someone smarter or more knowledgeable than me. (See rule #0.) Once you've done this, you should be reasonably secure from attackers. As for it being presumptuous to try to validate names, I don't agree. There are certain basic patterns to names that's more or less globally available, and by following these rules you should be fairly certain you accept the vast, vast majority of names out there. This is the function I use to validate names, from a collection of validation functions, and I've yet to see anyone complain about it: /** * Validates that string contains only characters legal for names. * Optionally extra characters can be selected, as well as max length. * * @param string $String * @param string $Extra * @param mixed $MaxLength * @return mixed */ function Val_name ($String, $Extra = '', $MaxLength = '+') { if ($MaxLength == "*" && $String == '') { return ''; } if (is_int ($MaxLength)) { $MaxLength = "{1,$MaxLength}"; } elseif ($MaxLength != "*") { $MaxLength = '+'; } $OKChars = addcslashes ($Extra, '."!?\'*|$[]<>%#^/\\').'\\w\\pL \\.\\-'; if (preg_match ('/^[a-zA-Z\\pL]['.$OKChars.']'.$MaxLength.'\\z/u', $String)) { return $String; } return false; } It accepts all letters, latin and other locales, space, period and hyphen. It does not allow numbers, as no-one (to my knowledge) use actual numbers in their name. Those that have title "the Third" (or similar) writes it out like that, meaning it falls within the realm of acceptable characters. PS: Validation and stripping (washing) input are two different things, as Psycho stated above. Generally you will always want to use validation and not stripping for security testing.
  17. Thanks Christian that makes it a good bit more clear. And i think I now realise the distinction between validation and stripping. I think I possibly make this more complicated that it has to be in my own head.
  18. Hi Pyscho I definitely take your point and thanks for your answer. There's isn't a 'business' reason as such. It just seemed logical to me that it would be prefereable to end up with data in the database that is as pure as possible (though I grant you that my regex is very shortsighted). Mostly because that sql data may not exclusively be used by php or for web applications. There may be backoffice system will access the tables too. And as I don't really have much knowledge of how other programming languages deal with sql data it seemed sensible to store the data in as pure form as possible - thereby making it's use in other programs a less issue prone process. I may of course - be totally and completely off the mark :/ If you were capturing data on the web, that may be ultimately be used by any number of other languages, what would you suggest is the most sensible way is to cleanse the data? And apologies - my ignorance might be over complicating this.
  19. Thank PFM. Really appreciate the help chaps. Incidentally this is just a test form because ultimately I will be writing a class that goes directly into a backoffice sql database (not mysql). So I was planning to cleanse the data with a preg_replace so i will essentially strip everything - a pattern along the lines of: /^[^a-zA-Z\s\b\'\"]$/ Does that sound like a reasonable way to strip down the inputs? It's the first time I'm doing anything that goes directly into back office systems (i.e. something that's not mysql) - hence my sudden elevated interest in ensuring security is done to the max.
  20. Thanks Cyb I think that'll be a nice clean way to guard against it then. The data is ultimately being passed to a validation class that does strip_tags, trim and a preg_match to clean and check the data - then if it passes validation I'll use prepared statments with PDO to insert. So hopefully that ties up the latter stages of the process from a security stand point. Does that sound like fair approach? Obviously none of that guards against XSS but hopefully tweaking the forms I produce as you've suggested can guard against that.
  21. Hi Guys I'm on a bit of a security trip at the moment so adopting PDO and generally making sure I am tighter on all aspects (which seems like an endless journey). Can anyone tell me whether echoing a POST value directly back to a form (see example below) exposes any security issues? I can't really think of any reason that it would be a security issue but I would like to know that's the consensus. <form method="POST" action="#"> <label>Name:</lable> <input type="text" name="name" maxlength="25" value="<?php echo (isset($_POST['name']) ? $_POST['name'] : null);?>"/> <br/> <input type="submit" value="Submit me" /> </form> Thanks, Drongo
  22. Think I've worked out how to get last id now. Is this correct? It does return the ID but I wonder how accurate it would be if multiple inserts were happening at once? $id = $db->lastInsertId(); I was getting confused and using $sth->lastInsertedId() - rather than using the original object.
  23. Thanks for your response PFM Sorry to draw this out but trying to understand this and PDO is quite a big chunk to learn. When you say: Do you mean that this would be safe (assuming I had done nothing at all to cleanse the $_POST data): $sth = $db->prepare('INSERT INTO users (address, town) VALUES ( :address, :town)'); $sth->bindParam(':address', $_POST['address']); $sth->bindParam(':name', $_POST['town']); $sth->execute(); Also, I'm struggling to get PDO::lastInsertId() to work - the manual page for this is a bit hard to follow. Can you give an example of how to use this? And is always likely to be accurate? Thank you for your help! Drongo #2. The sql query statement can only be what was prepared (assuming you didn't put any external user supplied values into the query statement when you prepared it.) The values that are put into the query when it is executed are used as data only. By automatically escaping string data, prepared statements prevent sql errors when the data contains special sql characters. Passing an array of data via the ->execute() method has one disadvantage that I know of. All the data values are treated as string data (the same as if you bound them using PDO::PARAM_STR) and they are surrounded with single-quotes when they are placed into the query. This will cause numerical data to be treated as a string containing a number, which causes extra processing and problems if the number is a decimal data type (at least mysql converts a string containing a number to type float, then uses the resulting floating point number) and causes a sql error if the parameter being replaced is in a LIMIT clause (LIMIT 'x' is invalid syntax, it must be LIMIT x.)
  24. Also, another question on PDO. There are two ways to send data to perpared statements: 1) via an array 2) by using bindParam method In what scenario are these two options preferable? Or are they simply equivalent?
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.