I'm trying to get two forms into a single script.
The script would allow you to click on a login button and have a form populate, fill out the form and then create cookies. The 2 forms work really well separately but I'm having issues combining them.
The script is about 180 lines so I'm not going to include all of it.
I'll include the main lines though:
<?php
if (!isset($_COOKIE['email']) || !isset($_COOKIE['password'])) {
if (!isset($_POST["login"])) {
// create form buttons here
} elseif (isset($_POST["login"])) {
if (isset($_POST["submit"])) {
// create form
// php code and create cookies if correct
} elseif (isset($_COOKIE['email']) || isset($_COOKIE['password'])) {
echo "hello $name";
}
}
}
That's pretty much the jist of it..
The attempt at combining the two is located at:
http://protein.guru/testlogin.phtml
the separate scripts are located at:
http://protein.guru/signin.phtml
http://protein.guru/login.php
My only 2 questions are:
Is it possible to do so with my current format using php?
If it is not possible with the format I'm using, does anyone have an idea of a format that would work?
I am using the email: tester3651#outlook.com
Password is: meatloaf
Use <button></button> with the same name and different value attribute. Your PHP would be something like:
<?php
$submit = $_POST['submitButtonName'];
if ($submit == 'value1') {
// do stuff here
} else if ($submit == 'value2') {
// do other stuff here.
};
You may use a switch case, you may use more ifs. Although I can't see the benefit of using the same PHP script to different forms. If they have different fields and values and have a whole differente behave, there should be two scripts, one for each form.
Related
I have a html form and php file as its action. When I click submit button it runs the php code but also load a blank page and the url changes.
How can I make just run code and stay on the same html page?
It sounds like you may need to develop beyond the "one page = one script" paradigm. Now, there are a number of possible approaches to "not leaving the page", such as:
Include your form processing code in the form page itself. Pros: Really simple and rudimentary. Cons: Code not reusable.
Submit the form via javascript (AJAX/Fetch). Pros: "Modern" and elegant when properly done. Cons: Relatively complicated. Requires both PHP and Javascript.
The simplest "elegant" approach: Separate your form-processing logic and include/call from the page when a form is submitted. Basic example:
<?php /* form.php */
if(!empty($_POST)) { // if form was submitted ("post")
include 'form_processor.php';
$result = process_form($_POST);
echo 'Form Process Result: ' . $result;
}
?>
<form action="form.php" method="post">
... your HTML form here ...
</form>
<?php /* form_processor.php */
function process_form($post, $args = []) {
$errors = [];
// do stuff with the post data: validate, store, etc.
if(count($errors) > 0) {
$result = 'Errors: ' . implode(', ', $errors);
} else {
$result = 'Okay';
}
return $result;
}
You will need to put some thought into crafting a form processor that's reusable in multiple contexts, e.g. by passing arguments that define case-specific validation and data processing. Probably turn it into a class, or at least into multiple functions with clear separation of tasks (validating, storing, e-mailing, etc.). The above should give you a basic path forward.
I am tying to refine how my application handles drawing forms and validating their inputs. In particular, I want the option of testing ALL inputs for validation instead of just returning on the first error I find! I'd like to accomplish a structure like this...
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (check_field($_POST['name']))
{
$form_errors['name'] = 'Name is invalid';
}
if (check_field($_POST['email']))
{
$form_errors['email'] = 'E-mail is invalid';
}
if (count($form_errors) == 0)
{
// All validations succeeded
// Continue processing the form
// Show confirmation for user
// DO NOT REDRAW THE FORM!!!
}
else
{
// Somehow jump to the SHOW_FORM below
}
}
elseif (SHOW_FORM)
{
// Show ALL errors we have collected, if any
print_r($form_errors);
/*
* A block of code that draws the form!
* A block of code that draws the form!
* A block of code that draws the form!
*/
}
else
{
// Show a list of records to edit
}
I have been accomplishing this with functions up until now. I have 1.) a function that draws the form and prints the contents of the $form_errors array if any and 2.) a function that validates the form inputs on submission. If the validation function returns false (which it does if any errors are found), the user lands back on the form with all of their errors on display.
Writing a pair of functions for every new form has become cumbersome and leads to a lot of repeat code. If possible, I'd like to abandon this practice and just have my parent page validate form inputs, but default to simply drawing the form. I would like assistance in structuring the page in this way.
Here's some ideas:
Put your forms into their own files with nothing but the html & code to display errors only (this is called a View).
Post to a page that handles the post (this is called a Controller).
In the page that handles the post, only validate using re-usable functions that you have included from another file. For example the validation function might look like this: validate_email($_POST['email']); or validate($_POST['email'], 'email');, or validate($_POST, ['email' => 'email']);
In a project of mine I am working with a sequence of pages that each give information that is used in the next, with POST and session variables. Simple example:
Page 1: enter name -> page 2 display name; ask birth date -> page 3 display name and birth date.
If a user goes directly to page 3 I want to display a message that s/he has not entered a name and/or birth date and should try again. Currently I am still doing it like so. On page 2:
if (isset($_POST['name'])) $_SESSION['name'] = $_POST['name'];
and page 3:
if (isset($_SESSION['name'])) $name = $_SESSION['name'];
if (isset($_POST['bday'])) $_SESSION['bday'] = $_POST['bday'];
as declarations and in the body an if-clause like
if (isset($name) && isset($_SESSION['bday'])) {
// do main stuff
else {
// display error message
}
The example is simple enough, but in the real world my code has a lot more variables and data from the forms, and putting all this first in variable assignments and then in an if-clause is tiring and seems not efficient to me. Is there a better, more straightforward way to check things like this? Or is what I posted the best, most-used way to go?
You can use one call to isset to check several variables.
isset($_SESSION['name'], $_SESSION['bday'], ...)
Or you can write your own function like
if (variablesFilled(['name', 'bday', ...])) { }
function variablesFilled($array) {
foreach ($array as $entry) {
if (!isset($_SESSION[$entry])) {
return false;
}
}
return true;
}
I believe you just need to write some helper methods. One to rewrite $_POST data to $_SESSION, dumb as this:
function copyPostToSession(array $fields) {
foreach($fields as $field) {
if(isset($_POST[$field])) {
$_SESSION[$field] = $_POST[$field];
}
}
}
so instead of if forest, you do:
copyPostToSession(array('name','bday'));
(additionally you can count how many fields were present and return true or false if there's mismatch) and the other (pretty similar) to check if you got all the required data in $_SESSION.
PHP's isset() function is a variadric function.
You can put as many arguments as you want:
isset($a, $b, $c)
...which translates to:
isset($a) && isset($b) && isset($c)
Hope it helped!
Seperate functions tend to differ a bit on a per server case. You could try calculating the time to perform a function a large number of times and compare which is faster.
But, yeah, that looks like fairly fast code there.
Might be worth trying a switch case statement as an alternative perhaps?
In Yahoo or Google and in many websites when you fill up a form and if your form has any errors it gets redirected to the same page.
Note that the data in the form remains as it is. I mean the data in the text fields remains the same.
I tried ‹form action="(same page here)" method="post or get"›. It gets redirected to the page, but the contents of the form gets cleared.
I want the data to be displayed.
You know how tiresome it will be for the user if he has to fill up the entire form once again if he just forgets to check the accept terms and conditions checkbox.
Need help!
You need to do this yourself. When the page gets posted you'll have access to all the form values the user entered via $POST['...']. You can then re-populate the form fields with this data.
Here is a modified version of what I use for very simple websites where I don't want/need an entire framework to get the job done.
function input($name, $options = array()) {
if(!isset($options['type'])) $options['type'] = 'text';
$options['name'] = $name;
if(isset($_POST[$name]) && $options['type'] != 'password') {
$options['value'] = htmlspecialchars($_POST[$name]);
}
$opts = array();
foreach($options as $key => $value) {
$opts[] = $key . '="' . $value . '"';
}
return '<input ' . implode(' ', $opts) . '/>';
}
(I have a few similar functions for <select> and <textarea> and so on)
When you're building fields you can do something like:
First Name: <?=input('first_name')?>
Last Name: <?=input('last_name')?>
Password: <?=input('password', array('type' => 'password'))?>
If you process your forms in the same page as the form itself, they will get auto filled if there are any errors. Most frameworks, though, do all of this for you (and in a much better way than the code above), I personally suggest CakePHP or CodeIgniter.
This is not done automatically. They get values from post / get and then assign the values the user typed to the template. What you see is html that was generated from the script that handled user values.
If you put your form and the form data processing in the same script, you can easily print out the data that has already been entered in the form, e.g.:
$valid = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['name']) && $_POST['name'] == 'Hugo') {
$valid = true;
} else {
echo '<p>Seriously, you have to enter "Hugo"!</p>';
}
// more data processing
if ($valid) {
echo '<p>Everything’s fine!</p>';
}
}
if (!$valid) {
echo '<form action="" method="post">';
echo '<p>Please enter "Hugo": <input type="text" name="name" value="', (isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''), '"></p>';
echo '<p><input type="submit"></p>';
echo '</form>';
}
Well this is not nice example but that’s how it works.
a lot of frameworks do this job for you, so dont waste your time doing this manually
You'll have to check the data within the same file, and if it is correct, then you redirect to the correct location. Then you can use the $_POST or $_GET information the user posted and he can fix the error(s).
You can use two approachs (they're not mutually exclusive):
Use JavaScript to help the user before he submits the form. That way, you save a roundtrip to the server.
What you asked for:
In the form, fill the value attributes of the fields with the data sent back from the server. For example: you send a field name, which you get as $_POST['name'] in PHP (assuming you used method='post'. If you send back the data and modify that field adding value='<?php $_POST['name']; ?> you should get your data back.
If you're using a template or framework system (I've incorporated the Smarty engine into several projects of mine), you can usually tweak the templates so they automatically fill fields with values if they detect that the $_POST[$variable] value corresponding to their field is set.
As for the passwords, as far as I understand it (I could be wrong): it's a convention that minimizes the amount of time that password is being sent over the wire, hence shrinking the window for anyone who may be sniffing to pick up on the text. It's just good practice to leave password fields blank, is all.
I've got a submission page in php with an html form that points back to the same page. I'd like to be able to check if the required fields in the form aren't filled so I can inform the user. I'd like to know how to do that with php and javascript each. However, I imagine this is a common issue so any other answers are welcome.
Do the check in posting part of your php
if(isset($_POST['save']))
{
$fields=array();
$fields['Nimi'] = $_POST['name'];
$fields['Kool'] = $_POST['school'];
$fields['Aadress'] = $_POST['address'];
$fields['Telefon'] = $_POST['phone'];
$fields['Email'] = $_POST['email'];
foreach ($fields as $key => $val)
{ if(trim($val)=='')
{ $errmsg=$key." is not filled!";
break;
}
}
}
if($errmsg == '')
{ //do your saving here
exit();
}
if(!isset($_POST['save']) || $errmsg != '')
{ //show your form here
// and make it to return to the same page on submit
//<input name="save" type="submit" value="Save" onclick="return true;">
}
For extra credit, once you know how to do it in PHP and JavaScript from Riho and annakata's answers, then build a way of defining a field constraint in a single form that can both be rendered as JavaScript for client-side validation and run on the server.
Since you need both (client-side for user convenience, server-side because we're really very much past trusting the client at this point), it seems like quite a decent idea to support both from a single infrastructure.
As far as JS goes you have to check before you submit. Generally this involves binding some validation function to the onsubmit event trigger of the form, and that validation function will consist of some tests for each field you're interested.
Most JS libraries have validation implementations that will do most of the work for you, which sounds like it might be a good idea for you. Googling "client side validation" will yield infinite results, but this (I'm library agnostic, read and choose for yourself) should get you started*:
http://blog.jquery.com/2007/07/04/about-client-side-form-validation-and-frameworks/
http://tetlaw.id.au/view/blog/really-easy-field-validation-with-prototype/
http://dojotoolkit.org/book/dojo-book-0-4/part-4-more-widgets/forms/validation
*this is on the teaching you to fish plan
The LiveValidation library would help you out a lot:
http://www.livevalidation.com/