PHP - Proper Prg Form Handling
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? Similar TutorialsHas anyone seen a decent database class for nicely wrapping up all the PDO functions? Ideally I'm after an example to handle database errors properly, insert/update/select queries, prepared statements and transactions. I've had a crack at writing my own and it's a bit messy with error handling everywhere. Maybe I need to put that in a separate class or something. E.g. here's how I'd do a database update: $db = new Database(); // In page controller $params['type'] = $type; $params['details'] = $details; $query = 'insert into site_logs (type, details) values (:type, :details)'; $result = $db->preparedUpdate($query, $params); // returns false if error or # of rows if successful Just some examples would be great and I'll re-factor my one to make it better. Thanks! 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? 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 usually hate to post something like this as a first post...I'd like to at least do an into but I"m stumped and I think it's a totally stupid thing I"m not noticing. Anyway, this is the final step in a three step user verification; this is for a staff user to be verified. Anyway, by now they have already verified their email and entered a random code so I"m only worried about actually setting them to verified status in my database so they can start working on blogs etc. Anyway, this form is supposed to find all unverified staff members, and allow an admin to easily just click down the list (one at a time currently) and verify the user (ie. setting their database status to verified_staffUser). The username that is supposed to be verified (or declined and therefore their entry deleted) is supposed to be passed through as $_POST[vnsupUsername]. This is set each time it loops through and prints a new user. The problem is that it's only sending the final username when I click verify/decline on any user :\. I"m not sure why it's doing this. In firebug on firefox it's showing that the user name is set for each one to be properly in the form...but when I click on it (I am having on my machine) the username being worked with echoed..and it's always the last one that was entered into the database. I have no idea why this is happening ..any thoughts? Code: [Select] <?php if(isset($_GET[vnsufac]) || isset($_POST[svnsu]) || isset($_POST[dvnsu])){ // simply prints the back home button echo "<form action=\"http://localhost/~atharp1122/OGirly_Site/ogirly_staff_homepage.php\" method=\"post\">" ."<input type=\"submit\" value=\"Back to Staff Homepage\" style=\"margin-top:10px;\">"; // this will print out the form to verify/deny all new staff user requests that have been email verified $programCheckUVStaff = mysql_query("SELECT username, email, firstname, lastname FROM staffUNAP where verified_staff = '0'"); while($UVStaff = mysql_fetch_assoc($programCheckUVStaff)){ print "<div class=\"newVerifyUserContain\" >"; print "<div class=\"newVerifyUser\" >"; echo "<h3 style=\"text-align: center;\">Would you like to verify this Staff request?</h3>"; echo "<table><tr><td>" ."<img src=\"images/default_icons/di_bunny_rabbit.png\" width=\"56\" height=\"59\" />" ."<ul style=\"padding-left: 100px; padding-bottom: 20px; margin-top: -42px; list-style-type: none;\"><li>" ."{$UVStaff[username]} aka {$UVStaff[firstname]} {$UVStaff[lastname]}</li><li>" ."{$UVStaff[email]}</li></ul></td></tr><tr><td>" ."<form action=\"{$_SERVER[PHP_SELF]}\" method=\"post\">" ."<input type=\"checkbox\" name=\"isadmin\" value=\"1\" style=\"margin-left: 10px;\">Is Admin?" ."<input type=\"hidden\" name=\"vnsupUsername\" value=\"{$UVStaff['username']}\">" ."<input type=\"submit\" name=\"svnsu\" value=\"Verify Staff\" style=\"margin-left: 200px;\">" ."<input type=\"submit\" name=\"dvnsu\" value=\"Decline Request\">"; print "</table>"; print "</div></div>"; } } // verify a staff member if(isset($_POST[svnsu])){ echo "verifying a new user"; echo $_POST[vnsupUsername]; } ?> 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 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 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 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 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 topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=333815.0 Should this be the proper way of adding the getUsername() text in the query below: Code: [Select] mysql_query("UPDATE posts SET content = '$content', lastedit = ". getUsername() .":NOW() WHERE id = '$pid'") or die(mysql_error()); Say I have two areas of a website. 1 - root directory (index, sign up, sign in) 2 - folders (this would contain folders such as snippets, members, assets) Due to the nature of the folders, the links cannot be the same as they are on the pages in the root directory. Index page for example. So if I'm on members/dashboard.php, any a links linking to index.php, will have to have "../" in front of them. To solve the issue, my current set up is like this. But I understand it's not the most efficient way to do this. I was wondering if you can share your expertise for a better method. $currentPage = basename($_SERVER['PHP_SELF'], ".php"); <?php if($currentPage == 'index' || $currentPage == 'members') { ?> <!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title></title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <link rel="shortcut icon" href="images/favicon.ico.png"> <link href="css/screen.css" media="screen" rel="stylesheet" /> </head> <body> <a href="index"> <img src="images/logo.PNG" alt="logo" /> </a> </body> <?php } else { ?> <!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title></title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <link rel="shortcut icon" href="../images/favicon.ico.png"> <link href="../css/screen.css" media="screen" rel="stylesheet" /> </head> <body> <a href="../index"> <img src="../images/logo.PNG" alt="logo" /> </a> </body> <?php } else { ?>
Im having trouble with this wondering if someone could help me out please if (isset($_POST['escape'])) { || if (isset($_POST['suicide'])) { its giving me a error on the || im writing it so that one or the other has to happend. is this the correct way to use this? Hi Guys,
Total PHP Noob here. I’ve run into a brick-wall and would appreciate some words of wisdom. I can do this with a browser: http://86.60.161.24 // will echo hello World I can’t do this with my server: <?php $url = 'http://86.60.161.24'; $contents = file_get_contents($url); echo ($contents); ?> It looks like the server-side HTTP -request never “touches” my Arduino-chip. No network activity detected. Obviously there is going to be a lot more data transfer happening but I need to solve this issue first. Is there anything I can do to make this work? Any and all input greatly appreciated. Cheers!!
Just curious, what is proper programming in cases where you're just doing a simple IF statement where there really is no need for an ELSE. Should you still write out the ELSE? For example, which is proper... Code: [Select] if (x=1) { //code here to do something } or Code: [Select] if (x=1) { //code here to do something } else { } There would be nothing in the ELSE statement, so is it OK to just leave it out completely (i.e. version #1), or is it proper to still have it listed (i.e. version #2)? Hi. Currently I have code the uses both TRUE. IF statements and FALSE statements to move on. For example. Is it better to use: Code: [Select] Where B=A C=A IF A=B { IF C=B{ ECHO 'HELLO WORLD'; }ELSE ECHO 'C DOES NOT EQUAL B'; }ELSE ECHO 'A DOES NOT EQUAL B'; ' OR is it better to do it like this: Code: [Select] Where B=A C=A IF A<>B { ECHO 'C DOES NOT EQUAL B'; ELSE IF C<>B{ ECHO 'C DOES NOT EQUAL B'; ELSE ECHO 'HELLO WORLD'; '[/code $sql = "SELECT option_id, id FROM bets WHERE win_status = '1' AND updated_at BETWEEN '$today 13:00:00.000000' AND '$tmrw 08:00:00.000000'"; $result = mysqli_query($connt, $sql); foreach($result as $value) { $value[] = arary_multisort(); $oid = $value['option_id']; $gid = $value['id']; var_dump($value); //$gim = var_export($value); } foreach($result as $key => $value) { $info = array($value); } mysqli_close($connt); $fl = array($oid, $gid); print_r($fl);
array ( Either I can return 1 row and have the data sorted nicely or I can return an array but I can only seem to access the last array. Been stuck on this bit for atleast 2 hrs sadly. How can I rename the array? Some days I might have 100 results. Today we have two winners xP I really need to ctrl+z sublime cuz I tried what feels like everything. Ancy to move to the next part of this code MATH if you can kindly assist. Yall have been extremely helpful in my last two posts 2/2 going on 3. Is there a place I can properly contribute lite silver :3 Code: [Select] if (isset($select_category) || isset($most_liked)) { // ALL but NO OTHER if (((($select_category == 'All') || (!isset($select_category)))) && (!isset($most_liked))) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY contribution_date DESC"; fetch_all ($dbc, $query); // CATEGORY but NOT most_liked } elseif (isset($select_category) && !isset($most_liked)) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id AND category = '$select_category' ORDER BY contribution_date DESC"; fetch_all ($dbc, $query); // CATEGORY and MOST_LIKED } elseif (($select_category != 'All') && (isset($select_category) && isset($most_liked))) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id AND category = '$select_category' ORDER BY likes DESC"; fetch_all ($dbc, $query); // ALL or NO CATEGORY but MOST LIKED } elseif ((($select_category == 'All') || (!isset($select_category))) && (isset($most_liked))) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY likes DESC"; fetch_all ($dbc, $query); } } What I am basically trying to accomplish is, choose a category through a drop down list, select that category and then go through all the rows in the database and print the content out. As of now it is working for me, I am also using a pagination script to print out everything in a table. The problem I am having is that fetch_all function is also printing the query out together with the content. Any ideas why it does that? Did I use this function the right way? If you need more information let me know. That's right I'm pretty green when it comes to PHP. I googled it, but it looks like there are several ways to achieve this, wondering which is best.
elseif ($subcategory_id == 400)I want the code to include a number of subcategory_ids, 400, 450, 500, 760, etc. There isn't a range, so what would be the proper way to include multiple category_ids. Thank you |