-
Posts
579 -
Joined
-
Last visited
Posts posted by Drongo_III
-
-
Sorry dipping into this thread so excuse me if the answer is wrong.
But it sounds like you're assuming the form for currency is posting directly to a session variable, which doesn't happen.
So it sounds like you need a middle step:
//Check is the user has submitted a new currency if(isset($_POST['currency'])){ $_session['currency'] = $_POST['currency']; } //If the user hasn't changed the currency check if the currency isset, if not, use default value of gbp else if(!isset($_session['currency'])){ $_session['currency'] = "GBP"; }
Typing this directly into the browser so apologies if anything is typoed!
Also, and you probably know this, make sure you have session start at the top of each subsequent page to preserve and make accessible the session across pages.
-
Thanks for the help
-
Nah it was more just a case of getting some advice on dealing with big xml files as i was using print_r on the object but that, as you pointed out, is bugged. :/
Maybe i just need to polish my eyes
-
Thanks ChristianF - looks like i've invented resonseJson then
The reason I thought a library might be preferable was because then you wouldn't rely on the browser to decode - instead the library would ensure that the decoding would work. But I could be wrong on this. Does that make sense as an approach to ensure legacy browsers still work?
- [*]As far as I'm aware there is no
http.responceJSON
attribute, onlyhttp.responseText
, when working outside of any frameworks.So decoding the string with a JSON parser is indeed the correct approach.
[*]A browser either supports JSON parsing, or it doesn't. If it doesn't then you get a catchable exception, in which case you can use a failsafe method. Libraries doesn't really enter into the equation ant this point, except for the fact that they tend to handle the error caused by a missing JSON parser.
Relying on a library, or not, is a decision which requires considerations of a lot more points that just JSON parsing. That said, it is generally recommended to use one (like jQuery) if you need to do a lot of DOM manipulation and AJAX calling. Simply because it lessens the workload on you, mostly due to the fact that most/all of the browser incompatibilities are handled automatically.
If you need only a few simple AJAX calls, or some other trivial functionality, then it can be advisable to forgo the library. It's all a judgement call, really.
-
Well in this instance I am just playing around with pulling in a YouTube feed. It was more just to practice with a large, and fairly complicated, xml file.
What would you consider is a good alternative to using simpleXML?
-
HI Guys
Couple of questions:
1) When working with ajax in 'raw' javaScript (i.e. not jquery), if the response from the server is going to be in Json format do you need to make the onreadystate response:
http.responseJson
Or since the json is essentially a string do you just do get request 'responseText' and then decode the string using json parser.
Which brings me to question two!
2) Is it ok to rely on native browser support to decode jason - i.e. using:
var myObject = JSON.parse(myJSONtext);
Or is this a bad idea if someone is using an older browser? And is it therefore better to rely on a library instead?
Many thanks
Drongo!
-
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.
-
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?
I think it's a known and reported bug that print_r() doesn't show everything, and especially namespaced stuff. Saw it last week or so.
If it's there in the XML then you can access it.
$xml->path->to->parent->children("media", true)->thumbnail
-
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);
-
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??
yes as the row gets inserted with valid fields but just one row .
-
Any php errors?
Are you quite sure you've made a successful connection the database on $dbc?
-
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 '; }
-
What currently happens when you run it? Do you just insert an empty row? Or does nothing insert at all?
-
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.
-
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
-
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: [email protected]'); // 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
-
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.
VALUES ( '$mobileno', '$passwd1', '$fname', '$lname', '$email', '$activation')";
-
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?
-
Do you have errors turned off? Just wondering if you're not supressing an error?
-
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
-
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?
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?
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.
-
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?
I always validate all user input, without exceptions. As the first thing I do, after I've validated that the user has sent input. Anything less, and I've potentially opened the doors for an attacker.
Rule 0: Never underestimate the dark side.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.
-
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.
-
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.
Setting session variable when clicking an image
in PHP Coding Help
Posted
As far as my logic extends (which on most days isn't that far haha) i believe that snippet of code checks to see if your currency is set in the post array, if not, it will check to see if the currency is session variable is set. If it's not set it will apply the default value of gbp - otherwise it assumes the currency session is set and therefore does nothing.
If you think your forms aren't posting try doing:
at the top of your page. This will display everyting in the post array (again, sorry if i am telling you anything you know). I just tested your form though and it worked perfectly for me.