Jump to content


Photo

Auto Filling Form


  • Please log in to reply
52 replies to this topic

#1 thelee

thelee

    Advanced Member

  • Members
  • PipPipPip
  • 61 posts

Posted 20 November 2012 - 05:23 PM

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">&nbsp;</p>
  <p align="center" class="style10">&nbsp;</p>
  <p align="center" class="style10">&nbsp;</p>
  <p align="center" class="style10">&nbsp;</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>&nbsp;</td>
                <td><input type="submit" name="Submit" value="Order">     <input name="Reset" type="reset" id="Reset" value="Reset"></td>
          </tr>
        </table>
  </div>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
</form>
</body>
</html>
<?php } ?>


#2 berridgeab

berridgeab

    Advanced Member

  • Members
  • PipPipPip
  • 112 posts
  • LocationBirmingham, United Kingdom

Posted 20 November 2012 - 05:31 PM

Is the address stored in the session too? Or are you trying to get the form to remember he information after it has been submitted?

Edited by berridgeab, 20 November 2012 - 05:32 PM.


#3 Love2c0de

Love2c0de

    Advanced Member

  • Members
  • PipPipPip
  • 366 posts
  • LocationThe Pleiades
  • Age:23

Posted 20 November 2012 - 06:38 PM

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

#4 play_

play_

    Advanced Member

  • Staff Alumni
  • 717 posts

Posted 20 November 2012 - 06:54 PM

You just simply echo out the variables.

It depends where you store them. Database, $_POST or $_SESSION.
regex.kat.sh --- regex library
u.kat.sh ---- url shortener
tabbit.org ---- tabbed pastebin

#5 AyKay47

AyKay47

    Sick!

  • Members
  • PipPipPip
  • 3,287 posts
  • LocationEast Coast, U.S.
  • Age:24

Posted 20 November 2012 - 06:58 PM

You answered your own question here, store the users address in a session and output it as the textarea's default value.
Hola!
I'm not going to hold your hand and write the code for you - ain't nobody got time for that!

#6 Psycho

Psycho

    Advanced Member

  • Gurus
  • 10,786 posts
  • LocationCanada

Posted 20 November 2012 - 07:26 PM

@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.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

#7 Love2c0de

Love2c0de

    Advanced Member

  • Members
  • PipPipPip
  • 366 posts
  • LocationThe Pleiades
  • Age:23

Posted 20 November 2012 - 09:35 PM

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

#8 play_

play_

    Advanced Member

  • Staff Alumni
  • 717 posts

Posted 20 November 2012 - 09:45 PM

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_, 20 November 2012 - 09:46 PM.

regex.kat.sh --- regex library
u.kat.sh ---- url shortener
tabbit.org ---- tabbed pastebin

#9 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 21 November 2012 - 04:37 AM

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

#10 Love2c0de

Love2c0de

    Advanced Member

  • Members
  • PipPipPip
  • 366 posts
  • LocationThe Pleiades
  • Age:23

Posted 21 November 2012 - 02:24 PM

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.

#11 Love2c0de

Love2c0de

    Advanced Member

  • Members
  • PipPipPip
  • 366 posts
  • LocationThe Pleiades
  • Age:23

Posted 21 November 2012 - 02:46 PM

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, 21 November 2012 - 02:55 PM.


#12 Love2c0de

Love2c0de

    Advanced Member

  • Members
  • PipPipPip
  • 366 posts
  • LocationThe Pleiades
  • Age:23

Posted 21 November 2012 - 03:29 PM

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.

#13 Psycho

Psycho

    Advanced Member

  • Gurus
  • 10,786 posts
  • LocationCanada

Posted 21 November 2012 - 03:41 PM

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.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

#14 Love2c0de

Love2c0de

    Advanced Member

  • Members
  • PipPipPip
  • 366 posts
  • LocationThe Pleiades
  • Age:23

Posted 21 November 2012 - 06:43 PM

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


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, 21 November 2012 - 06:47 PM.


#15 Psycho

Psycho

    Advanced Member

  • Gurus
  • 10,786 posts
  • LocationCanada

Posted 21 November 2012 - 07:15 PM

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
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

#16 Love2c0de

Love2c0de

    Advanced Member

  • Members
  • PipPipPip
  • 366 posts
  • LocationThe Pleiades
  • Age:23

Posted 21 November 2012 - 08:05 PM

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


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, 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, 21 November 2012 - 08:17 PM.


#17 Psycho

Psycho

    Advanced Member

  • Gurus
  • 10,786 posts
  • LocationCanada

Posted 21 November 2012 - 09:14 PM

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.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

#18 Love2c0de

Love2c0de

    Advanced Member

  • Members
  • PipPipPip
  • 366 posts
  • LocationThe Pleiades
  • Age:23

Posted 21 November 2012 - 09:24 PM

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.

#19 Psycho

Psycho

    Advanced Member

  • Gurus
  • 10,786 posts
  • LocationCanada

Posted 21 November 2012 - 11:26 PM

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
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

#20 Love2c0de

Love2c0de

    Advanced Member

  • Members
  • PipPipPip
  • 366 posts
  • LocationThe Pleiades
  • Age:23

Posted 22 November 2012 - 12:09 PM

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


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


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, 22 November 2012 - 12:10 PM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com