Jump to content

Drongo_III

Members
  • Posts

    579
  • Joined

  • Last visited

Posts 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?

     

     

     

    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

  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. 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
    
    

     

     

  5. 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')";

     

  6. 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.

  7. 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.

  8. 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.

     

     

     

  9. 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.

     

     

  10. 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.

     

     

  11. Thanks PFM!

     

     

     

    If someone made a phishing site that looked like your site and got one of your visitors to goto the phising site instead of your site, and there was a form that submitted to your site's form processing code with XSS code as part of the the actual $_POST['name'] data, that XSS code would be output to and ran in the client's browser, sending any of actual data that your site just output to the client back to the hacker.

     

    All external data ($_POST, $_GET, $_COOKIE, $_FILES, and some of the $_SERVER variables) cannot be trusted and can be anything and must be validated/filtered/escaped/type cast...

  12. 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

  13. 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.

  14. 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:

     

    #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.

     

    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

     

     

    Out of interest, why are prepared statement considered so SQL-injection-proof? Is it simply because they automatically escape the data? Or is it because they don't allow people to append new queries through user data?

     

    #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.

     

    There are two ways to send data to prepared statements:

     

    1) via an array

    2) by using bindParam method

     

    In what scenario are these two options preferable? Or are they simply equivalent?

     

    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.)

  15. 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?

     

     

     

     

     

    So the moral of the story is just use PDO then.

     

    Out of interst, why are prepared statement considered so SQL-injection-proof? Is it simply because they automatically escape the data? Or is it because they don't allow people to append new queries through user data?

×
×
  • 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.