Keep Request when requesting same route with POST and GET? - php

I'm trying to make a simple form that is validated and errors should be shown. Also, the values of the fields should stay.
I'm using simple routing code to determine which page to show.
My problem is that the values of the form always reset when I submit it.
I googled a bit and found that when the Request changes, the form values get lost.
That's a small example that shows what I want to achieve:
$route = $_SERVER['REQUEST_URI'];
switch ($route) {
case '/kontakt':
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test">
<input type="submit">
</form><?php
break;
}
After submitting the entered value should stay in the field.
So how can I keep the Request when routing to the same route but one time with POST and one time with GET without changing the form value to use the _POST array?

Lets first grab which request we need to use to get the request arguments.
$request =& $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
It would probably be a good idea here to check it is set, if it isn't - just leave it blank.
$name = $request['name'] ?? ''; # PHP 7+
$name = isset($request['name']) ? $request['name'] : ''; # PHP 5.6 >
You can then do your routing
# switch: endswitch; for readability
switch(($route = $_SERVER['REQUEST_URI'])):
case '/kontack': ?>
<form method="POST" action="/kontakt">
<input type='text' value='<?= $name; ?>' name='name' />
....
<?php break;
endswitch;
This will then continuously insert the name back in to the value field. However, if you visit a new page and then come back - it will be gone. If you want it to stay at all times, through-out any route, you can use sessions.
session_start();
# We want to use the request name before we use the session in-case the user
# Used a different name to what we previously knew
$name = $request['name'] ?? $_SESSION['name'] ?? ''; # PHP 7
$name = isset($request['name']) ? $request['name'] : isset($_SESSION['name']) ? $_SESSION['name'] : ''; # PHP 5.6 >
# Update what we know
$_SESSION['name'] = $name;
Note: I showed both PHP 5.6> and PHP 7 examples. You only need to use one based on which PHP version you're using.

When you are getting to the route in the first time, then send a HTML-valueAttribute-variable as null. When you go back to the route after posting send the post value to the HTML-valueAttribute-variable:
When you reach the route the first time:
<?php
//Value that is sent to the view/page when accessing route without having posted a value
$testValue=null
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test"
<?php
if($testValue != null)
{
echo "value='".$testValue."'";
}
?>
>
<input type="submit">
</form>
When you use the route after have posted:
<?php
//Value that was posted is sent to view/page
$testValue=$POST['test']
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test"
<?php
if($testValue != null)
{
echo "value='".$testValue."'";
}
?>
>
<input type="submit">
</form>

Related

edit value in session

Scenario :
I have an simple php form to calculate things and calculate prices.
Now im stuck at my edit function.
I have a simple switch switch ($_GET['actie']) with cases like add , edit and delete.
This is my session : $_SESSION['data'][] = $_POST;
Edit Case :
if (isset($_POST['submitnieuw']))
$data['lengtezijde'][$_GET['key']] = $_POST['nieuw'];
Laden(0);
Edit Form:
else
echo $_GET['key'];
<form action="index.php?actie=wijzigen" method="post">
<input type="text" name="nieuw">
<input type="submit" name="submitnieuw" value="submit">
<input type="hidden" name="ky" value="$_GET['key;]">
</form>
break;>
i can see the key of the value i want to edit but it wont edit the $data['lengtezijde'] value
if some things are missing or my question is unclear let me know.
In your edit case you are using the GET value of the key, but from your form it looks like you should be using a POST value here instead. Try changing this:
$data['lengtezijde'][$_GET['key']] = $_POST['nieuw'];
To this:
$data['lengtezijde'][$_POST['ky']] = $_POST['nieuw'];

Button Value Not Changing when Text Field Isn't Empty

Having a small issue getting my submit button to change the value when the php variable isn't empty. So the way I have it set up is that when the button "GO" is pressed it will set the value of the text field to "1234567890" meaning it is no longer empty. Now when the page first loads the text field will be empty and the button should say "GO" once pressed the text field value will change and the button should now say "REFRESH" however it stays saying "GO" can anyone see where I'm going wrong here?
Thanks.
PHP
<?
if (!$HostKey){
$HostBtn = 'GO';
}
else{
$HostBtn = 'REFRESH';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['Go'])) {
$HostKey = "123567890";
}
}
}
?>
HTML
<form action="Home.php" method="post">
<p><strong>HOST:</strong>
<input name="Host" id="Host" type="text" value="<? echo $HostKey; ?>" maxlength="10" disabled>
<input name="Go" id="Go" type="submit" value="<? echo $HostBtn; ?>"></p>
</form>
Your issue is a logical one, as $HostKey isn't defined prior to you doing your check - so $HostKey is null. You define it after that. Then, because the variable is effectively null, when you apply the not-operator !, that condition is always true.
You should refactor your code to check if the form was submitted, and define the value of the variable based on that instead. All you need in PHP would be
$HostBtn = isset($_POST['Go']) ? 'REFRESH' : 'GO';
$HostKey = isset($_POST['Go']) ? 123567890 : '';
This would also fix the "Undefined variable..." notices you should have been getting if you enabled error-reporting,
error_reporting(E_ALL);
ini_set("display_errors", 1);
Which should be enabled while in development. In a live environment, you shouldn't display the actual errors though - but its fine to do that under development.
You should try something like :
<?
if (isset($_POST['Go'])) {
$HostKey = "123567890";
$HostBtn= "REFRESH";
}else{
$HostKey="";
$HostBtn="GO";
}
?>

How to run a PHP function from an HTML form?

I'm absolute beginner in web technologies. I know that my question is very simple, but I don't know how to do it.
For example I have a function:
function addNumbers($firstNumber, $secondNumber)
{
echo $firstNumber + $secondNumber;
}
And I have a form:
<form action="" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<p><input type="submit"/></p>
How can I input variables on my text fields and call my function by button pressing with arguments that I've wrote into text fields?
For example I write 5 - first textfield, 10 - second textfield, then I click button and I get the result 15 on the same page.
EDITED
I've tried to do it so:
$num1 = $POST['number1'];
$num2 = $POST['number2'];
addNumbers($num1, $num2);
But it doesn't work, the answer is 0 always.
The "function" you have is server-side. Server-side code runs before and only before data is returned to your browser (typically, displayed as a page, but also could be an ajax request).
The form you have is client-side. This form is rendered by your browser and is not "connected" to your server, but can submit data to the server for processing.
Therefore, to run the function, the following flow has to happen:
Server outputs the page with the form. No server-side processing needs to happen.
Browser loads that page and displays the form.
User types data into the form.
User presses submit button, an HTTP request is made to your server with the data.
The page handling the request (could be the same as the first request) takes the data from the request, runs your function, and outputs the result into an HTML page.
Here is a sample PHP script which does all of this:
<?php
function addNumbers($firstNumber, $secondNumber) {
return $firstNumber + $secondNumber;
}
if (isset($_POST['number1']) && isset($_POST['number2'])) {
$result = addNumbers(intval($_POST['number1']), intval($_POST['number2']));
}
?>
<html>
<body>
<?php if (isset($result)) { ?>
<h1> Result: <?php echo $result ?></h1>
<?php } ?>
<form action="" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<p><input type="submit"/></p>
</body>
</html>
Please note:
Even though this "page" contains both PHP and HTML code, your browser never knows what the PHP code was. All it sees is the HTML output that resulted. Everything inside <?php ... ?> is executed by the server (and in this case, echo creates the only output from this execution), while everything outside the PHP tags — specifically, the HTML code — is output to the HTTP Response directly.
You'll notice that the <h1>Result:... HTML code is inside a PHP if statement. This means that this line will not be output on the first pass, because there is no $result.
Because the form action has no value, the form submits to the same page (URL) that the browser is already on.
Try This.
<?php
function addNumbers($firstNumber, $secondNumber)
{
if (isset($_POST['number1']) && isset($_POST['number2']))
{
$firstNumber = $_POST['number1'];
$secondNumber = $_POST['number2'];
$result = $firstNumber + $secondNumber;
echo $result;
}
}
?>
<form action="urphpfilename.php" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<?php addNumbers($firstNumber, $secondNumber);?>
<p><?php echo $result; ?></p>
<p><input type="submit"/></p>
You need to gather the values from the $_POST variable and pass them into the function.
if ($_POST) {
$number_1 = (int) $_POST['number1'];
$number_2 = (int) $_POST['number2'];
echo addNumbers($number_1, $number_2);
}
Be advised, however, that you shouldn't trust user input and thus need to validate and sanitize your input.
The variables will be in the $_POST variable.
To parse it to the function you need to do this:
addNumbers($_POST['number1'],$_POST['number2']);
Be sure you check the input, users can add whatever they want in it. For example use is_numeric() function
$number1 = is_numeric($_POST['number1']) ? $_POST['number1'] : 0;
Also, don't echo inside a function, better return it:
function addNumbers($firstNumber, $secondNumber)
{
return $firstNumber + $secondNumber;
}
// check if $_POST is set
if (isset($_POST['number1']) && isset($_POST['number2']))
{
$number1 = is_numeric($_POST['number1']) ? $_POST['number1'] : 0;
$number2 = is_numeric($_POST['number2']) ? $_POST['number2'] : 0;
echo addNumbers($_POST['number1'],$_POST['number2']);
}
You are missing the underscores in
$_POST['number1']
That's all.
maybe it's a little late
but could you set a parameter in the url of the php file to post example:
In the html :
...
<form action="Controllers/set_data.php?post=login" method="post" >
...
In the php :
...
$post_select = $_GET['post'];
switch ($post_select) {
case 'setup':
set_data_setup();
break;
...
You can always use this trick. But keep in mind that if the referrer is hidden it doesn't work.
header("Location: " . $_SERVER["HTTP_REFERER"]);
Just add to your PHP page at the point where there is no more code to be executed, but is still executed.

Retaining values in forms fields when validation of data fails

I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>

Passing Information Between PHP Pages

How do I pass information between PHP pages?
For example, I have a PHP script to process login input from a form, and then a separate PHP script to process further input for the user. However, I want the second PHP file to receive the input from the login form. In essence, I do not want the same script being run twice for the login.
You are looking for POST and GET variables, it's done in the method parameter of your HTML form:
login.php
<form name="myform" action="secondpage.php" method="post">
<div>Username: <input type="text" name="username" value="" /></div>
<div>Password: <input type="password" name="password" value="" /></div>
</form>
Then in this other page:
secondpage.php
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
if ($username != '') {
// do your validations here
}
Explanation
When you use the GET method, the parameters are visible in the URL, so let's say we change the method="GET" in login.php, you'll end up with something like secondpage.php?username=jsmith&password=1234. And then you could get the values using $_GET['username'].
Using POST makes it possible to send larger quantity of data (there is a vague limit to the size of a URL) and it's not visible in the URL. You should note though that it's still sent in clear text, so it does not means it's secure.
POST and GET were made for different purposes. GET should be use to extract information that you could want to extract again in the future, information that is not special to this very instant. It's useful to have mypage.php?product=123 because you'll potentially want to send this URL to a friend. A POST should be used when you'll modify the state of data: updating a product, creating a new user, deleting an article and so on. It's something you want to happen once.
Structure
In conclusion, I just want to add that normally you wouldn't necessarily want to use another PHP script just to avoid some code to run or not. So without knowing the specifics of your project, I can nevertheless say that you would probably want to do something like that to benefit from the same code (such as the form's HTML).
Please note it's simplified code.
login.php
<?php
$error = false;
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
// if, and only if something was posted... so not on first display
if ($username != '') {
// do your validations here
if ($properlyLogged) {
session_start();
$_SESSION['loggedAt'] = time();
header('Location: http://localhost/secondpage.php');
exit();
} else {
$error = true;
}
}
?>
<?php if($error): ?>Login failed. Please try again.<?php endif; ?>
<form name="myform" action="login.php" method="post">
<div>Username: <input type="text" name="username" value="<?php echo($username) ?>" /></div>
<div>Password: <input type="password" name="password" value="" /></div>
</form>
secondpage.php
<?php
session_start();
if (!isset($_SESSION['loggedAt'])) {
// if not properly logged in, return user to login
header('Location: http://localhost/login.php');
exit();
}
?>
You are now logged in!
Hope that's what you were looking for!
You can pass information between pages using GET or POST methods. GET would append the information you wish to pass as a querystring on the url such as:
loginprocess.php?id=JSmith&pword=HelloThere (this isn't exactly recommended for private information)
The other method is to send the information via POST so that it is hidden from the querystring.
More examples can be seen here: http://www.tizag.com/phpT/postget.php
If the data isn't that large you could redirect the user to the 2nd page with the data passed via the URL (GET variables). Otherwise, just run the seconds method in the same page, and use a function to do the final parsing of the data which can be included as the above user suggests.
Just a small extra to what was written before: the limit on the GET (parametrize URL) is a full URL, which means 1024 characters. If you need more than that, you have to use post.
You can take advantage of PHP sessions to share data amongst your PHP scripts. Basic example below, read more here.
login.php:
<?php
// initializes the session //
session_start();
// save user name and password to session //
$_SESSION["username"] = 'someuser';
$_SESSION["password"] = 'somepassword';
$_sESSION["valid"] = true;
?>
secondpage.php:
<?php
// start session handler //
session_start();
// check for a valid session //
if (!isset($_SESSION["valid"])) header("Location: login.php\n\n");
// continue page code here //
?>

Categories