Jump to content

Auto Filling Form


thelee

Recommended Posts

ellow. how i can auto fill the form for address and else.i just know how to auto fill the username because it is using the echo from session login username.can someone help me ? here is the code

 

<?php
error_reporting(E_ALL);
session_start(); 
if(!isset($_SESSION['MM_Username'])) {
echo "You are not logged in or registered / Click <a href='login.php'>Here</a> to login !";
} else {
?>[/background][/size][/font][/color]


[color=#464646][font='Helvetica Neue', Helvetica, Arial, sans-serif][size=3][background=rgb(244, 244, 244)]<style type="text/css">
<!--
body { background:#000; background-attachment:fixed; background-repeat:no-repeat; color:#fff; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; }
table { background:#000; border:1px solid white;}
-->
</style>
</head>[/background][/size][/font][/color]



[color=#464646][font='Helvetica Neue', Helvetica, Arial, sans-serif][size=3][background=rgb(244, 244, 244)]<body>
<p><b>Welcome <?PHP echo $_SESSION['MM_Username']; ?> !</b></p>
<form name="form1" method="post" action="order_product_process.php">
 <p align="center" class="style10"> </p>
 <p align="center" class="style10"> </p>
 <p align="center" class="style10"> </p>
 <p align="center" class="style10"> </p>
 <p align="center" class="style10">Order Form:</p>
 <div align="center">
       <table width="500" >
         <tr>
               <td width="239">Username</td>
           <td width="249">
           <input name="username" type="text" id="username" value="<?PHP echo $_SESSION['MM_Username']; ?>" readonly="true"></td> 
         </tr>
         <tr>
               <td>Address</td>
           <td><textarea name="address" id="address"></textarea></td>

         </tr>
         <tr>
               <td>Phone</td>
               <td><input name="phone" type="text" id="phone" maxlength="30"></td>
         </tr>
         <tr>
               <td>IC Number</td>
               <td><input name="ic" type="text" id="ic" maxlength="30"></td>
         </tr>
         <tr>
               <td>Product Name</td>
               <td><input name="product_name" type="text" id="product_name" maxlength="30"></td>
         </tr>
         <tr>
               <td>Quantity</td>
               <td>      <input name="quantity" type="text" id="quantity" maxlength="30"></td>
         </tr>
         <tr>
               <td> </td>
               <td><input type="submit" name="Submit" value="Order">     <input name="Reset" type="reset" id="Reset" value="Reset"></td>
         </tr>
       </table>
 </div>
 <p> </p>
 <p> </p>
 <p> </p>
 <p> </p>
 <p> </p>
 <p> </p>
 <p> </p>
 <p> </p>
 <p> </p>
 <p> </p>
 <p> </p>
 <p> </p>
</form>
</body>
</html>
<?php } ?>
Link to comment
Share on other sites

  • Replies 52
  • Created
  • Last Reply

Top Posters In This Topic

I'd really like to know how to do this aswell. I was attempting to implement a 'user profile' feature and wanted to display the information they entered previously in the form when they decide to update their profile again. I was using a DB to store the data.

 

I'll keep my eye on this topic as it will prove useful to me if the OP wants to use this feature.

 

Regards,

 

AoTB

Link to comment
Share on other sites

@AoTBuNgLe,

 

There are two things being discussed in this thread.

 

1) Auto-populating a form with previously saved values.For example, if you want to allow the user to edit their profile, you would have a form, naturally. When the user accesses the edit profile page you would run DB query to get the information they previously saved then use that information to populate the form accordingly. The manner in which you do this is different based upon the type of form field. Some, like text inputs and text areas are easy:

Address: <input type="text" name="address" value="<?php echo $addressValueFromDB">
About Yourself: <textarea name="about"><?php echo $aboutInfoFromDB; ?></textarea>

 

Others like select lists, radio buttons and checkboxes are a little more involved but not terribly complicated

 

2) Creating "sticky" fields. This is typically done when a user submits a form and there are validation errors. Instead of having the user fill in all the information again you want to repopulate the fields with the values they entered so they only have to fix what was in error. This is done in the same way as described above except you would use the POST values rather than the data from the Database.

 

Just keep in mind with both of the above to properly validate and escape the data. For output to the browser, htmlspecialchars() is usually sufficient. But, for Select lists, radio buttons and checkboxes you don't need to escape the data for output because the values shouldn't be used for output to the page but to determine whether to check the field or not. Do some googling for something like "php sticky fields" and you should be able to get started on whichever one you are wanting.

Link to comment
Share on other sites

Number 2 is what I would like to do because the current site I am working on has only 1 form which the user fills out (no registration needed). I have 2 textareas and inputs. At the moment, when they receive errors, it takes them back to the form but with blank fields. Of course, if they entered a long bit of text into the textareas, they are going to be a little annoyed at having to re-type it and will probably not bother a second time.

 

I will google that phrase though and see what I can dig out.

 

Kind regards,

 

AoTB

Link to comment
Share on other sites

Number 2 is what I would like to do because the current site I am working on has only 1 form which the user fills out (no registration needed). I have 2 textareas and inputs. At the moment, when they receive errors, it takes them back to the form but with blank fields. Of course, if they entered a long bit of text into the textareas, they are going to be a little annoyed at having to re-type it and will probably not bother a second time.

 

I will google that phrase though and see what I can dig out.

 

Kind regards,

 

AoTB

 

Right. So when they submit the form and you detect errors, filled out input fields will have a value.

So if user filled out the 'name' input field, but left out the 'email' or 'password' field, $_POST['name'] will hold a value when you redirect them to the same page.

 

 

Your HTML form fields should look like this

 

<textarea name="message" >
<?php if(isset($_POST['message'])) echo $_POST['message'];?>
</textarea>

Edited by play_
Link to comment
Share on other sites

Right. So when they submit the form and you detect errors, filled out input fields will have a value.

So if user filled out the 'name' input field, but left out the 'email' or 'password' field, $_POST['name'] will hold a value when you redirect them to the same page.

 

 

Your HTML form fields should look like this

 

<textarea name="message" >
<?php if(isset($_POST['message'])) echo $_POST['message'];?>
</textarea>

 

So for example, they submit form and I get the errors. I fill my error array full of the errors ready to display them to the user. Even AFTER I have sent them back to the form, the $_POST array STILL contains data?

 

Regards,

 

AoTB.

Link to comment
Share on other sites

You'll need to use htmlspecialchars () in that example, to avoid XSS attacks.

 

Thank you for the tip. I would have just used it straight like that.

 

Security is a big thing for me though. I always try to improve my code which already works, just to try to make it more secure and maintainable.

 

Edit: Just used the code within my textarea and it worked perfectly. Thank you both so much I have NO IDEA it was as easy as this!

 

Also, when I attempt to put the values back into the <input>'s do I have to do:

<input type="text" id="name" name="name" value="<?php (isset($_POST['name'])) ? print($_POST['name']) : ""; ?>" />

 

Regards,

 

AoTB.

Edited by AoTBuNgLe
Link to comment
Share on other sites

Ok, just worked on it and this seems to work perfect:

<?php if(isset($_POST['service_comments']) && !empty($errors)){print($_POST['service_comments']);}

 

What I'm not quite sure on is should I send the values through htmlspecialchars() in my action script, or when I print them back out to the form (the example above)??

 

regards

 

AoTB.

Link to comment
Share on other sites

Ok, just worked on it and this seems to work perfect:

<?php if(isset($_POST['service_comments']) && !empty($errors)){print($_POST['service_comments']);}

 

What I'm not quite sure on is should I send the values through htmlspecialchars() in my action script, or when I print them back out to the form (the example above)??

 

Couple things:

 

No need to check that $errors is empty in my opinion. Do you have a scenario where you expect that the POST variable will have a value and you don't want to repopulate the form with that value?

 

As to your specific question, htmlspecialchars() is a function to escape content for display to an HTML page. You do NOT want to escape content using that for other purposes - such as using in a DB query. For that you want to use mysql_real_escape_string() or whatever function/method is appropriate based upon what you are using. I sometimes see people run data through htmlspecialchars() and then mysql_real_escape_string() based upon the premise that they will be extracting the data from the database later to display on the page anyway. But, that will really limit you if you ever need the data for something else. I think it is better to store data in as "pure" a form as possible and only escape/transform the data as needed based upon the context of how it is used.

Link to comment
Share on other sites

Couple things:

 

No need to check that $errors is empty in my opinion. Do you have a scenario where you expect that the POST variable will have a value and you don't want to repopulate the form with that value?

 

The reason I need to check if the errors array contains anything is because when the user enters ALL valid data, I don't want to re-display what they entered, as I think IMO that would encourage people to just keep submitting the data over and over. When I didn't check to see if the errors array was not empty, it was re-displaying their data even after a successful submit.

 

As to your specific question' date=' htmlspecialchars() is a function to escape content for display to an HTML page. You do NOT want to escape content using that for other purposes - such as using in a DB query. For that you want to use mysql_real_escape_string() or whatever function/method is appropriate based upon what you are using. I sometimes see people run data through htmlspecialchars() and then mysql_real_escape_string() based upon the premise that they will be extracting the data from the database later to display on the page anyway. But, that will really limit you if you ever need the data for something else. I think it is better to store data in as "pure" a form as possible and only escape/transform the data as needed based upon the context of how it is used.

[/quote']

 

I am using a prepared insert statement and was advised not to use mysqli_real_escape_string() as there is no need because, and I quote, "The actual data doesn't get nowhere near the query so you do not need to use mysqli_real_escape_string() when using PREPARED STATEMENTS".

 

I'm not sure if there is any risk, if for example, the user entered some special characters in the form and it is re-displayed to them. I presumed that's why Christian told me to use the htmlspecialchars() function when re-displaying?

 

Let's say the entered:

<input type="submit" name="submit" value="submit" />

into one of my textareas, when re-displaying that to them, will it display another submit button?

 

Regards,

 

AoTB.

Edited by AoTBuNgLe
Link to comment
Share on other sites

The reason I need to check if the errors array contains anything is because when the user enters ALL valid data, I don't want to re-display what they entered, as I think IMO that would encourage people to just keep submitting the data over and over. When I didn't check to see if the errors array was not empty, it was re-displaying their data even after a successful submit.

 

So, if there are no errors you are processing the POST data and displaying the form again? Is this form for the purpose of the user to enter many records? If not, then I would suggest NOT displaying the form again if the data was valid and you have processed it. Instead, do a header() to redirect the user to a confirmation page. That will clear the POST data so a refresh will not send the data again

 

I am using a prepared insert statement and was advised not to use mysqli_real_escape_string() as there is no need because, and I quote, "The actual data doesn't get nowhere near the query so you do not need to use mysqli_real_escape_string() when using PREPARED STATEMENTS".

Right, so you already have a method to escape the data for use in a query as I said "or whatever function/method is appropriate based upon what you are using"

 

I'm not sure if there is any risk, if for example, the user entered some special characters in the form and it is re-displayed to them. I presumed that's why Christian told me to use the htmlspecialchars() function when re-displaying?

 

Let's say the entered:

<input type="submit" name="submit" value="submit" />

into one of my textareas, when re-displaying that to them, will it display another submit button?

 

No, not exactly. But that would mess up the form field where that content was output. Let's say the user entered ""><script type="javascript">alert('hello')</script>" and your form field looked like this

<input type="text" name="field" value="<?php echo $stickyValue; ?>">

 

The result will be:

<input type="text" name="field" value=""><script type="javascript">alert('hello')</script>">

 

That's not too bad, but there are some pretty bad things a malicious user could do. Look up XSS attacks

Link to comment
Share on other sites

So, if there are no errors you are processing the POST data and displaying the form again?

That's correct, with a success message.

 

Is this form for the purpose of the user to enter many records? If not' date=' then I would suggest NOT displaying the form again if the data was valid and you have processed it. Instead, do a header() to redirect the user to a confirmation page. That will clear the POST data so a refresh will not send the data again[/quote']

 

It isn't no. Basically, i'm creating a site for my local business. Purpose of the form is to allow the user to query/order a product from me. They do this by entering their personal details (as a way for me to contact them back) and if they wish to fill out the 'products' or 'services' sections of the form, then they can also be a bit more specific on the product or service they want.......You know I thought about a header() redirect to take them to the homepage after successful submission but I display my success/error messages back on the form page. I suppose I could just send them back to the form page should there be errors and if not, then as you said, redirect them to another page. I think that would be pretty simple to do considering my code.

 

I subconsciously knew that the $_POST values didn't get 'reset' after being sent back to the form page because I kept just pressing F5 for a hard refresh and it kept asking me to resend data. Never really thought much into that though.

 

No' date=' not exactly. But that would mess up the form field where that content was output. Let's say the user entered ""><script type="javascript">alert('hello')</script>" and your form field looked like this

<input type="text" name="field" value="<?php echo $stickyValue; ?>">

 

The result will be:

<input type="text" name="field" value=""><script type="javascript">alert('hello')</script>">

 

That's not too bad, but there are some pretty bad things a malicious user could do. Look up XSS attacks

 

Ah I see, so for instance, they could maybe create an infinite loop which keeps executing certain code to make your site break? I will definitely look up XSS attacks. I've heard quite a bit about them but never read up on them. Still getting to grips with basic php.

 

Edit: Just had a brief look at one of the first sites which came up on google....is it safe to say I should be using strip_tags() on ALL input to make sure any html characters are stripped??

 

Regards,

 

AoTB.

Edited by AoTBuNgLe
Link to comment
Share on other sites

Edit: Just had a brief look at one of the first sites which came up on google....is it safe to say I should be using strip_tags() on ALL input to make sure any html characters are stripped??

 

Um, yes. Or no. It all depends on what you decide. But, I find it very bad to ever modify the user input without their knowledge. For all you know having something like "<apt g>" is perfectly valid in an address. As long as you properly escape data based on how it is used there is no risk. If there are characters you don't want to allow then consider them a validation error. Removing any data without the users knowledge is risking removing data that is actually valid.

Link to comment
Share on other sites

Ah right, so for example in the 'name' field I am looking for just alphabetical characters so I use the preg_replace function like:

 

$value = preg_replace("/[^a-zA-Z ]/","",$value);

 

In this case, it would be ok to use this function because a name should not contain anything but alphabetical characters? I allow the space to let them enter spaces in the name field. I was using !ctype_alpha() before but as you can guess it didn't allow them to enter a space (which allows the surname). So if they did enter special characters, it's ok to edit their input in this case or not?

 

BUT

 

In the case of say an email address, we wouldn't want to strip any tags because some characters are allowed in email addresses? (not sure of the exact characters which are allowed in an email address).

 

for the email I use:

filter_var($value,FILTER_VALIDATE_EMAIL);

 

This seems to work on every eventuality.

 

I've always struggled with understanding when to use certain functions. Usually the ones which deal with input and database storage/retrieval.

 

Kind regards,

 

AoTB.

Link to comment
Share on other sites

Ah right, so for example in the 'name' field I am looking for just alphabetical characters so I use the preg_replace function like:

 

$value = preg_replace("/[^a-zA-Z ]/","",$value);

 

In this case, it would be ok to use this function because a name should not contain anything but alphabetical characters? I allow the space to let them enter spaces in the name field. I was using !ctype_alpha() before but as you can guess it didn't allow them to enter a space (which allows the surname). So if they did enter special characters, it's ok to edit their input in this case or not?

 

Names only contain "normal" letters and spaces? What about the hyphen which is commonly used for women that retain their maiden name and append their husband's last name. What about the apostrophe for names such as D'Angelo. And then, what about people that have names with accented characters such as González? That is exactly the problem I was alluding to. Do NOT try to over validate. And never (IMO) strip out content without having a very good reason for doing so. Do you have a business reason or requirement that prevents you from allowing any name a person wants to provide?

 

Priority #1 is to ensure the data is safe when you use it. There is nothing inherently unsafe about any input - it is how you use it that could make it unsafe. So, whenever using any input from the user think about how you are using it and determine what transformation, escaping, etc, you need to do to make it safe.

 

Secondly, you would consider validation. For that, have a reason why you do not want to allow certain inputs for a specific value. If the value is an email address that you will be sending a confirmation email to then you definitely want to validate that it is a properly formatted email. But, be careful of over validating. I have encountered many sites that would not accept valid email addresses with the plus symbol. I would almost never bother with name validation except to ensure it isn't empty (after trimming the value of course) - unless there is a specific reason. Phone numbers could be validated to make sure they contain at least 10 numbers. That is one example of a value that I might strip out characters that the user provided. So, if the user enters 123-46-7890 or 123.456.7890 or (132) 546-7890, I might strip out all non-numeric characters, verify that it is 10 digits and then save just that to the DB. But, if you plan to support users outside North America, you might have to do some more research into an appropriate technique

Link to comment
Share on other sites

Names only contain "normal" letters and spaces? What about the hyphen which is commonly used for women that retain their maiden name and append their husband's last name. What about the apostrophe for names such as D'Angelo. And then, what about people that have names with accented characters such as González? That is exactly the problem I was alluding to. Do NOT try to over validate. And never (IMO) strip out content without having a very good reason for doing so. Do you have a business reason or requirement that prevents you from allowing any name a person wants to provide?

 

You know, considering my surname uses a hyphen, you would have thought I would have realized. I need to stop sitting up so late! There is no business reason why they cannot enter such characters. To be honest, I'm shocked I haven't picked up on this, speechless infact. Thanks for the help.

 

Priority #1 is to ensure the data is safe when you use it. There is nothing inherently unsafe about any input - it is how you use it that could make it unsafe. So' date=' whenever using any input from the user think about how you are using it and determine what transformation, escaping, etc, you need to do to make it safe.

 

Secondly, you would consider validation. For that, have a reason why you do not want to allow certain inputs for a specific value. If the value is an email address that you will be sending a confirmation email to then you definitely want to validate that it is a properly formatted email. But, be careful of over validating. I have encountered many sites that would not accept valid email addresses with the plus symbol. I would almost never bother with name validation except to ensure it isn't empty (after trimming the value of course) - unless there is a specific reason.[/quote']

 

So does using filter_var($value,FILTER_VALIDATE_EMAIL) cover all eventualities or is there further validation to do to make sure it is a valid email?? Also with the name field, you're saying to just check it isn't empty after trimming, but what if they enter characters which clearly are not part of a name like @ or # or () or %. You allow that to pass validation? Or would you send them back saying those certain characters cannot be entered as a name?

 

Phone numbers could be validated to make sure they contain at least 10 numbers. That is one example of a value that I might strip out characters that the user provided. So' date=' if the user enters 123-46-7890 or 123.456.7890 or (132) 546-7890, I might strip out all non-numeric characters, verify that it is 10 digits and then save just that to the DB. But, if you plan to support users outside North America, you might have to do some more research into an appropriate technique

[/quote']

 

Funny you should say that because I think I got that part of my validation spot on.

 

I am using preg_replace again like so:

$value = preg_replace("/\D/","",$value);

 

This is to strip out any characters which are not numbers and then I use:

if($value == ""){ $errors[] = "You did not enter a phone number."; break;}

 

I check this because if they entered no digits, preg_replace will return empty string then when I check my next bit of validation, it will return an undefined index. I also break out of the switch early if this if statement executes because we know my next if statement will return a syntax error:

if($value[0] != "0" || strlen($value) != 10 || strlen($value) != 11){	 $errors[] = "You did not enter a valid phone number.";	 }

 

Plus just to note, I am from the UK and I did a bit of research and found out mobile/cell numbers are always 11 digits long, and landline numbers range from 10 - 11 so this is the reason I only check for these amounts. Also I check for the '0' as being the first character as all full code numbers in UK start with 0.

 

Thanks for your advice, I will start implementing it to my site.

 

Kind regards,

 

AoTB.

Edited by AoTBuNgLe
Link to comment
Share on other sites

Sorry to post another but it wouldn't let me Edit for some reason....

 

Just to clarify, the only data that will possibly be displayed from the database is their Name and any products or services they enquired about.

 

Their name because I want to greet them by name in the confirmation email.

 

Their product/service enquiry just so I can confirm what they have wrote actually has been received my end (this would only be sent on successful insert).

Edited by AoTBuNgLe
Link to comment
Share on other sites

So does using filter_var($value,FILTER_VALIDATE_EMAIL) cover all eventualities or is there further validation to do to make sure it is a valid email??

Yes, it should be fine for validating that the value is a properly formatted email.

 

Also with the name field, you're saying to just check it isn't empty after trimming, but what if they enter characters which clearly are not part of a name like @ or # or () or %. You allow that to pass validation? Or would you send them back saying those certain characters cannot be entered as a name?

It all depends. If this is for a site such as this - a public forum - who cares. Let them put in whatever they want. If this is for something like a site for business professionals then maybe not. But, is you are not going to allow some characters, how far do you take it? What about ♣, or ╨ or ║ or anything else that probably won't be in a name? Either you have to have a white list that contains only the characters you allow, which will potentially restrict someone from entering a valid name, or you have to have a black list of disallowed characters that probably won't be comprehensive anyway. And, how do you know someone has not legally changed their name to include characters such as # or @?

 

 

I am using preg_replace again like so:

$value = preg_replace("/\D/","",$value);

 

This is to strip out any characters which are not numbers and then I use:

if($value == ""){ $errors[] = "You did not enter a phone number."; break;}

 

I check this because if they entered no digits, preg_replace will return empty string then when I check my next bit of validation, it will return an undefined index. I also break out of the switch early if this if statement executes because we know my next if statement will return a syntax error:

if($value[0] != "0" || strlen($value) != 10 || strlen($value) != 11){	 $errors[] = "You did not enter a valid phone number.";	 }

 

Plus just to note, I am from the UK and I did a bit of research and found out mobile/cell numbers are always 11 digits long, and landline numbers range from 10 - 11 so this is the reason I only check for these amounts. Also I check for the '0' as being the first character as all full code numbers in UK start with 0.

 

Why not:

$value = preg_replace("/\D/","",$value);
if($value=='')
{
   $errors[] = "You did not enter a phone number.";
}
elseif(substr($value, 0, 1) != "0" || strlen($value) != 10 || strlen($value) != 11)
{
   $errors[] = "You did not enter a valid phone number.";
}

Link to comment
Share on other sites

Yes, it should be fine for validating that the value is a properly formatted email.

Thanks very much for clarification.

 

It all depends. If this is for a site such as this - a public forum - who cares. Let them put in whatever they want. If this is for something like a site for business professionals then maybe not. But' date=' is you are not going to allow some characters, how far do you take it? What about ♣, or ╨ or ║ or anything else that probably won't be in a name? Either you have to have a white list that contains only the characters you allow, which will potentially restrict someone from entering a valid name, or you have to have a black list of disallowed characters that probably won't be comprehensive anyway. And, how do you know someone has not legally changed their name to include characters such as # or @?[/quote']

 

I think someone changing their name to use such characters would be the rarest eventuality but I see what you're saying, I could take this way too far as the list of possible characters not allowed are extensive.. and also, they could just enter 'NULL' into the form field which also isn't a proper name but I wouldn't validate that. I will take your advice and just check to see if it actually contains a value.

There is no reason why they cannot enter such characters, I just wanted a way to prevent them from entering a name such as: '>abc@!po&j' for example, I wanted it to resemble a real name as much as possible.

 

Why not:

$value = preg_replace("/\D/","",$value);
if($value=='')
{
$errors[] = "You did not enter a phone number.";
}
elseif(substr($value, 0, 1) != "0" || strlen($value) != 10 || strlen($value) != 11)
{
$errors[] = "You did not enter a valid phone number.";
}

 

Yup that seems a lot more logical to use an if and ifelse rather than breaking out of the switch prematurely (which i'm not sure is 'proper' practice)?

 

Thanks for all your tips and guidance, I will keep going through the topic digesting what you've told me.

 

Regards,

 

AoTB.

Link to comment
Share on other sites

For validating names I, personally, use the following RegExp:

$NameRegExp = '/^[a-zA-Z\\pL][\\w\\pL \\.\\-]'.$Length.'\\z/u';

This should allow all variants of legal names, including international ones. It only validates the characters used though, and that it starts with a letter. Trying to establish a legit pattern for names beyond that is, well.. Challenging, to put it mildly. :P

 

When it comes to your validation of the phone number, I think you'll need to re-examine the logic of it. As it stands now you'll show the error message if the phone number is not 10 or if it's not 11 characters. Since it can't be 10 and 11 characters long at the same time, the logic will always return "true" and thus show the error.

In this case I'd recommend using a RegExp for it as well, which would look like this:

$PhoneRegExp = '/^\\d{10,11}\\z/';

Run a preg_match () with it, and if it fails then you know that the phone number is invalid; The RegExp only accepts a 10 or 11 digit number, after all.

 

Other than that I'm afraid I don't quite agree with the statement that there's nothing inherently unsafe with any input, or at least the sentiment of it. The only way to ensure that you're relatively safe, is to assume just the opposite: That all input is unsafe and potentially dangerous, so limiting it to only what you know to be safe/required is a necessity.

The book Innocent Code, by Sverre H. Huseby, explains the reasoning behind this in a very good manner. Showing the common pitfalls and mistakes made by web-developers, professionals as well as amateurs, plus how to prevent them. It is a highly recommended read!

Edited by Christian F.
Link to comment
Share on other sites

For validating names I, personally, use the following RegExp:

$NameRegExp = '/^[a-zA-Z\\pL][\\w\\pL \\.\\-]'.$Length.'\\z/u';

This should allow all variants of legal names, including international ones. It only validates the characters used though, and that it starts with a letter. Trying to establish a legit pattern for names beyond that is, well.. Challenging, to put it mildly. :P

 

Wow that is a very complicated looking expression :P Seems there is a lot more to it than first expected.

 

When it comes to your validation of the phone number' date=' I think you'll need to re-examine the logic of it. As it stands now you'll show the error message if the phone number is not 10 [i']or[/i] if it's not 11 characters. Since it can't be 10 and 11 characters long at the same time, the logic will always return "true" and thus show the error.

In this case I'd recommend using a RegExp for it as well, which would look like this:

$PhoneRegExp = '/^\\d{10,11}\\z/';

Run a preg_match () with it, and if it fails then you know that the phone number is invalid; The RegExp only accepts a 10 or 11 digit number, after all.

 

You know, that's the reason I came back here to post again lol. The logic doesn't work right as you stated as one of those OR statements will ALWAYS return true which is what I just found out after implementing that code! That regular expression looks quite simple though, thank you for the code. Very helpful indeed.

 

Other than that I'm afraid I don't quite agree with the statement that there's nothing inherently unsafe with any input' date=' or at least the sentiment of it. The only way to ensure that you're relatively safe, is to assume just the opposite: That all input is unsafe and potentially dangerous, so limiting it to only what you know to be safe/required is a necessity.

The book Innocent Code, by Sverre H. Huseby, explains the reasoning behind this in a very good manner. Showing the common pitfalls and mistakes made by web-developers, professionals as well as amateurs, plus how to prevent them. It is a highly recommended read!

 

I'll definitely give that a read! That's one of my most common pitfalls is user data. Don't seem to know how to use it for the correct purposes, as you've realized if you've been following this thread :P

 

Kind regards

 

AoTB.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


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