PHP - Form Errror Handling Strategy
Hi guys,
What techniques do you use to process, validate, and then show errors on your forms. Do you set an "action" to the same form and then handle errors somewhere? Do you use a separate script to process validation? What standards do you apply for the position of the error messages? Do you alter the "look" of any fields in errors (make them red for example)? Do you have a good standard strategy that can be applied for all forms in a re-usable fashion? Perhaps using functions? I am looking for a robust, user friendly (and coder friendly come to that) solution to this frequently encountered situation. Many thanks for any help. S Similar Tutorialshey guys m using STDIN as input stream in php command line my problem is that some time i get this error Warning: fgets(): supplied argument is not a valid stream resource in D:\myquery \test.php on line 16 $number=fgets(STDIN); anyone knows solution I am trying to use CURL on a site., to send SMS/TXT messages. HERE IS THE CODE Code: [Select] $name = $_POST['name']; $emsg = $_POST['emsg']; $ch = curl_init("https://www.smsfun.com.au/api/login.php?mobile=emma&password=123456&send_to=$name&message=$emsg&send=1"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); Then i use my form like this Code: [Select] <form method="post" action="" value ""> <p align="center"><strong><font color="#0000FF" size="5" face="Courier New, Courier, mono">MOBILE NO<br> <input name="name" type="text"> </font></strong></p> <p align="center"><strong><font color="#0000FF" size="5" face="Courier New, Courier, mono">message</font><font color="#0000FF" size="5" face="Courier New, Courier, mono"><br> <textarea name="emsg" value "$emsg" rows="5" wrap="VIRTUAL"></textarea> </font></strong><br> <input type="submit" name="submit" value="SEND"> </p> </form> This all works fine but if the user needs to put a space after a word i.e "hello this is a test" this wont work only "hellothisisatest" will. Am i missing somtink here? I tryed googleing etc cannot find the answer. Please help Thanks g-netUK A form needs to get answers of math quiz, returning numbers, up to 2 digits after the point. In all form examples I noticed the usage of: Code: [Select] ...<input type="text" name="name" /... Cant it be a number? floating or integer? why "text" ? Also, can I limit the form to accept numerical input only or would I need to learn Ajax for that? Once I have the answer, I need to compare it to the correct answer. The method I have in mind is to multiply the answer and the correct one by 100 and compare the integer part. Is there a pre-made function that can do the same? Hello everyone, I've recently asked a question about forms and Requinix mentioned PRG method of processing forms. The PRG idea solves my refresh and back button document expired problems but i notice something new: when i refresh a page or use the browser back button - then return to the PRG process - repeat a refresh or back button action - i notice that i can traverse the cache history as many times as my prg approach redirects me. I feel like i am not implementing this PRG method correctly, or is this correct? Here is the form process if it helps solve the problem: i have a login form which contains a CSRF token. when i submit the form i specify an action as /prg/ which submits the data to index.php in the prg folder. After processing the data, prg index.php redirects to the root (because you are logged in). One problem is that i have a logo on the login page that allows you to return to the root (localhost index page). When the form is not submitted or it contaiuns incorrect login data or the logo is clicked to return to homepage, then the history seems to repeat itself. I've read that people recommend to use a header 303 See Other but the result is the same. Basiclly, if i am implementing a prg correctly, then the question becomes how can i instruct a browser to ignore the redirect as if the cache contains only the index page? i cannot find prg examples that involve a csrf token and other links on the protected page (prg/index.php protected because you need a form submission with a csrf token and it only processes data then redirects.) I don't see this happening in professional sites like Google or Microsoft etc. what am i doing wrong? Not sure why the PHP variables in the code below aren't interpreting the values that they should be receiving from the HTML form. HTML form Code: [Select] <form action="handle_form.php" method="post"> <fieldset><legend>Enter your information in the form below</legend> <p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p> <p><b>Email Address:</b> <input type="text" name="email" size="40" maxlength="60" /></p> <p><b>Gender:</b> <input type="radio" name="gender" value="M" /> Male <input type="radio" name="gender" value="F" /> Female</p> <p><b>Age:</b> <select name="age"> <option value="0-29">Under 30</option> <option value="30-60">Between 30 and 60</option> <option value="60+">Over 60</option> </select> </p> <p><b>Comments:</b> <textarea name="comments" rows="3" cols="40"></textarea></p> </fieldset> <div align="center"><input type="submit" name="submit" value="Sumbit My Information" /></div> </form> PHP handle_form <?php #Script 2.2 handle_form.php $name = $_REQUEST['name']; $email = $_REQUEST['email']; $comments = $_REQUEST['comments']; echo "<p>Thank you, <b>$name</b>, for the following comments:<br /> <tt>$comments</tt></p> <p> We will reply to you at <i>$email</i>.</p>"; ?> Hi Guys, Can someone please tell me why no echo statements work after my heredoc :? Here's the code: Code: [Select] <?php switch($_POST['options']){ case '1': $selected1 = 'selected'; break; case '2': $selected2 = 'selected'; break; case '3': $selected3 = 'selected'; break; case '4': $selected4 = 'selected'; break; default: $selected1 = $selected2 = $selected3 = $selected4 = ''; } echo <<<END <html> <head> <script type="text/javascript"> function show_alert() { alert("I am an alert box!"); } function formSubmit() { document.getElementById("frm1").submit(); } </script> </head> <body> <form id="frm1" method="post" action="search.php" /> <select onclick="formSubmit()" name="options" size="1"> <option $selected1 value="1">date</option> <option $selected2 value="2">year</option> <option $selected3 value="3">country</option> <option $selected4 value="4">language</option> </ select> </body> </html> </form> END; if(isset($_POST['options'])){ echo "item chosen"; } It works when I put the 'isset' if clause before the heredoc and even weirder, if i add a submit input type in the form as the last field it works as is? ex: Code: [Select] <?php switch($_POST['options']){ case '1': $selected1 = 'selected'; break; case '2': $selected2 = 'selected'; break; case '3': $selected3 = 'selected'; break; case '4': $selected4 = 'selected'; break; default: $selected1 = $selected2 = $selected3 = $selected4 = ''; } echo <<<END <html> <head> <script type="text/javascript"> function show_alert() { alert("I am an alert box!"); } function formSubmit() { document.getElementById("frm1").submit(); } </script> </head> <body> <form id="frm1" method="post" action="search.php" /> <select onclick="formSubmit()" name="options" size="1"> <option $selected1 value="1">date</option> <option $selected2 value="2">year</option> <option $selected3 value="3">country</option> <option $selected4 value="4">language</option> <input type="submit"> </ select> </body> </html> </form> END; if(isset($_POST['options'])){ echo "item chosen"; } Any help would be greatly appreciated! Cheers D I am totally newbie, doing my first project, after reading a PHP book. The page I am trying to build is like a quiz: displays a simple form, get answers and display "Good/bad answer". This is easy, but the form needs to continue based on the first answers, something like 5-6 more steps. Each step depends on the data from the previous steps. Can I still use the approach like the example below? What happens to the variables when the PHP script is re-visited? can I assume their values are still valid? // The example I thought I will use: <?php // if form not yet submitted, display form if (!isset($_POST['submit'])) { ?> <form ................................................. . </form> <?php // if form submitted // process form input } else { ..... $num = $_POST['num']; .......... } else { echo ' my message ............................ } ?> This is a tough one to summarize - especially in the Subject?! I need to insert a Comment which consists of: * article_id * member_id * body * status * created_on * approved_on * updated_on Only the "body" field is gathered from my "Add a Comment" form, and everything else either comes from the $_SESSION or from NOW() I am wondering if it would be easier to do Error-Handling and what-not if I created an Input for at least the first 4 fields above and populated the "Value" of those fields that already have values (e.g. "member_id")?? Then when the user clicks "Add a Comment", I can check all of the values in $_POST and handle everything in a uniform way, if you follow my new thinking?! Debbie Hello All, I am building a web based data entry project for my University Recycling Department 1) In the first level the user will enter the number of "rows" that he has to enter it can be any number form 4- 10 . Each row will contain "Vendor Name","Date","Net Recycled Weight" 2) Depending on the number of rows entered by the user I am generating a table structure that has 2.1) A <select> containing vendor names(I am querying for this and then storing the result in an Associative Array and then parsing it for select in every way) 2.2) A text box for the date 2.3) A text box for the Net Recycled Weight ------------------------------------------------ Here is the logic I have implemented so far <html> <head></head> <body> <form name = "form1" method = "post"> <select>HERE THE USER CAN SELECT THE NUMBER OF ROWS HE WANTS TO ENTER</select> <input type = "submit" value = "submit1" name = "submit1"> </form> <body> </html> <?php if(submit1 has been clicked ) { //HERE I AM GENERATING A DYNAMIC FORM BASED ON THE NUMBER OF ROWS COUNT <form name = "form2" method = "post"> echo <table> echo <tr> echo<td>VENDOR</td> echo<td>DATE</td> echo<td>NET RECYCLED WEIGHT</td> echo </tr> for(IT ITERATES TILL I GENERATE THE NUMBER OF ROWS THAT HAS TO BE ENTERED) { I AM GENERATING ROWS HERE } echo <input type = "submit" name = "submit2" value = "submit2"> echo</table> </form> HOW CAN I ACCESS THE POST METHOD OF FORM 2 } ?> MY PROBLEM --------------- I WANT TO KNOW THE FOLLOWING 1) It this the correct way to do it 2) how can I access the data entered in each dynamic row as I have to validate it and then enter the data in MySql 3) I am not sure how I will access the submit button event of the dynamically generated form I hope I can get some help Thanks, Marisha I am learning how to use PHP to handle input in a Contact Form on my website. Using PHP I can send the form data to my email client. However I cannot achieve the outcome of sending a copy to the email address of the submitter. I have searched the Internet particularly Stack Overflow and have found code that I am told will achieve this outcome Here is the code: <?php if(isset($_POST['submit'])){ $to = "email@example.com"; // this is your Email address $from = $_POST['email']; // this is the sender's Email address $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $subject = "Form submission"; $subject2 = "Copy of your form submission"; $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message']; $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message']; $headers = "From:" . $from; $headers2 = "From:" . $to; mail($to,$subject,$message,$headers); mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender // echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly."; OR // You can also use header('Location: thank_you.php'); to redirect to another page. } ?> Adjusting it for my own circumstances and settings it will still send the information in the form to me but will not send the information to the submitter's email address. What is particularly confusing is, if I modify the code by taking out this line of code mail($to,$subject,$message,$headers); Which includes my email address ($to), it still works and the information including ($subject) is still sent to my email address. I would appreciate any assistance that anyone would offer This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=333815.0 Hello,
I'm starting using class and have a question for you guys :
Let's consider a class "customer". I want to code a search tool. Where should I put my search function ? Within the customer class ? In another "search" class ? Other solution ?
Thanks for help !
am currently building the cart system of a product, now there is this part wherein, the non-logged-in OR logged-in user should also be able to see the items that he/she viewed, how to do that?., am not asking for code snippets , just give me some ideas/hints/strategies/tips that may help me get the big picture on how to do this thing and proceed coding. Hi, I was asked to create an app, wherein, the user may enter the email addresses of people manually, and it auto generates a random key. now this key will be used access such pages e.g proposal.test.com/ppc proposal.test.com/seo proposal.test.com/design so using the key for example => Sa22asdf it should appear like this proposal.test.com/ppc/Sa22asdf proposal.test.com/seo/Sa22asdf proposal.test.com/design/Sa22asdf without the unique key generated during the input of email address, the URL mentioned shouldn't be accessed by anyone.. now my question is, how to approach this thing in PHP ? I have done the input for email address and generation of random keys., but i don't know yet what to do or how to do the securing of pages using those keys ? This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=350418.0 I am wondering if there is an easier / better way to keep my development and test databases in synch.
When I develop, I may add tables or fields to existing tables. When I upload from the development server to the test server I can check and make sure that I include all of the programs that I have edited by using the filesystems last modified date. However, I keep track of new and changed tables in MYSQL manually. Is there an easy way, that I am just missing, to see last modified dates for tables within a db? Is there some other strategy I should be using. I hate missing a table and having the test server give errors on code I debugged once on the development server.
Hello, I'm working on a very simple strategy based game site (mainly to expand my knowledge). What I basically want it to do is, you send a solider to an area which takes, say 20 seconds. After 20 seconds, he battles for 30 seconds, and then arrived back home which takes another 20 seconds. All the user is going to be seeing is a 'status' echo'ed text saying "Arriving in 00:??", "Battle Over in 00:??", and "Home in 00:??". So its just using a time counter. But what makes it more complicated, is that I want the time progress to be saved (datebase), so say I have to wait 50 seconds, I can sign off, go on another computer, sign in and still see my timer going down according to the time that has just passed. So, what I've done so far is, have 4 variables: $realTime - Holds the actual time in seconds. $waitingTime - Holds how long I need to wait. (this is stored in my DB) $differenceTime - Difference between real time and my waiting time. (loaded from my DB) $soliderProgress - Progress of the solider, so: Arriving, Battle ... (stored on DB) Code: [Select] $realTime = date("s"); //soliderProgress is 'Starting' by default if(soliderProgress == "Starting"){ //solider is moving to area $differenceTime = $realTime + $waitingTime; $SQL = ("UPDATE users SET differenceTime='$differenceTime' WHERE username='$username'"); soliderProgress = "Arriving"; $SQL = ("UPDATE users SET soliderProgress='$soliderProgress' WHERE username='$username'"); } if(soliderProgress == "Arriving"){ echo "Arriving to area"; if($realTime >= $differenceTime){ //timer is complete soliderProgress = "Battle"; $SQL = ("UPDATE users SET soliderProgress='$soliderProgress' WHERE username='$username'"); } } This kind of works, but sometimes my $differenceTime is higher than 60 which messes it up, and also the timer isn't live ... so I have to keep refreshing the page I am refactoring entire collective scattered SQL from my legacy codebase, and into separate classes, and looking for some structure to put it into. Right now I have folders effectively called `DataFromDB` - contains classes that accepts whatever parameters are given, and returns pure data back to the user `DAO` - Data Access Object, which takes that raw data from DB and makes sense out of it and prepares it for consumption by the model/business logic layer objects. That is: - src (folder) |- DAO (folder) | - ProductADAO (classes - take data in, return consumable objects out) | - ProductBDAO | - ... | - ProductZDAO |- DataFromDB (folder) | - ProductAData (classes - contain methods to query pure result sets from DB) | - ProductBData | - ... | - ProductZDataWhenever I need to make a new SQL or refactor an old one I do this: What is this SQL doing? Is it operating on `SomeObjectX`? If yes, find/create class called `ObjectX`, and add a method to it, extracting pure data from DB, put it into `DataFromDB` folder. Write the `DAO` object if needed to transform data into a consumable object. Use the object as is in my code. Does this look like a good strategy? Is there a better one? My problem with this one is that before (now) all the SQL is tightly coupled and is included into the multiple business classes. Using the above strategy will mean I am to be creating many many classes, a lot of classes, most likely one for every few SQL statements. The pros is that it seems like I will achieve a level of code modularity that I wanted. This doesn't work. Based off what I have seen online, it is suppose to. Basically, this is what I tried, and the quote is what was returned. I have no idea how to get this to work. It should have been pretty standard based off of the PHP documentation. The Xpath idea I got from someone else. Either way if I try to use find element by id or tag name it still returns an empty array, no matter what. Any advice on what I am doing wrong is appreciated. It doesn't matter what URL I try, none of them seem to work. Code: [Select] <?php $school_data = file_get_contents('http://www.infotechnologist.biz'); $doc = new DOMDocument(); $doc->validateOnParse = true; $doc->loadHTML($school_data); $xpath = new DOMXPath($doc); $tags = $xpath->query('div'); echo '<pre>'; print_r($tags); echo '</pre>'; ?> Quote DOMNodeList Object ( ) I am inserting last names into the database using mysql_real_escape_string(), and outputting the data into a textbox using addslashes(). When I try to display O'Brian "O\" is displayed in the text box. The name is saved corretly as O'Brian in the database. I am printing the string like this: Code: [Select] echo "<input type='text' value='" . addslashes($customer['lName']) . "' blah blah..."; anybody have any ideas? |