How would I pass information from one PHP to another? - php

I need to create a landing page that's dynamic to information picked up by a form that executes a php script.
Person submits form > PHP Code sends me an email > PHP code that displays information
I have a hidden input in every form that identifies what form it is, and depending on what the value or "identification" of the form a specific code on the php is executed using a switch and I thought that maybe I could use that same identifier to execute another switch on the page after that. My problem is I don't know how to carry that value or identifier from one php to the other.
So just to reiterate, I want to know how to move or copy variables from one php to another, after mail() is executed.
Im using $request to get those variables

Keep this source form identifier and render it into your new form identifier field. It will deliver the response form with same identifier

after you do your Mail() thing, call a function that runs whatever you want.
If the classes or functions you want to run are not available you must include or require them.

I'm not 100% sure about what you are asking for, but due the comments I'll make a try to answer it.
When I create forms I usually have one page with the actual form and another page that handles the data. When the data is handled I simply redirect the user back to the form and then give them feedback.
The reasons I'm using two separate pages are the following:
I like to keep the code for the form and the handler separated.
Users can't accidently submit the form again by refreshing the page.
The same handler can be used by eventual Ajax and uphold progressive enhancement.
An extremely simplified example below.
form.php:
<?php
//Start session
session_start();
//If the session variable has been set
if($_SESSION['remember'])
{
## DISPLAY FEEDBACK ##
}
else
{
## DISPLAY FORM ##
}
//Delete the session variable
unset($_SESSION['remember']);
?>
req.form.php
<?php
//Start session
session_start();
//If a form has been submited
if(isset($_POST['submit']))
{
## HANDLE THE DATA ##
//Set a session variable
$_SESSION['remember'] = true;
//Redirect the user back to the form
header('Location: /form.php');
exit;
}
?>

Related

Is it possible for a page to know that it has been redirected to using header()?

I'm creating a form. There is some server-side validation being executed in a php file separate from the html file containing the form. If the validation fails, I want to redirect back to the original html page with a error message saying what went wrong.
Right now, I am able to successful validate and redirect back to the html page with header(), but I'm not sure how to create and place the error message. Is it possible to check at the top of the html page with php if it's been redirected to through header()? If so, that would solve the problem...
Thanks!
there are several methods to do this i think.
1 add get parameters like:
<input type="hidden" name="formsent" value="1" />
then add method get to your <form>
when you redirect from the other page,, the get would be in the link so you could send it back
header("Location: http://localhost/yourform.php/?{$_GET['formsent']}");
or you could do the validation in the post
if (isset($_POST) && !empty($_POST)) {
do stuff here.. if all is ok go to next page otherwise show errors
}
or you could add a var into a session using $_SESSION['formsent'] = 1 after the post then u could check that also.
its up 2 u
You should set a variable using PHP sessions.
Form page
session_start();
$_SESSION["formerror"] = "Error code here";
header("Location: http://www.example.com");
Redirected to page
session_start();
$errorcode = $_SESSION["formerror"];
// Now convert the error code to something readable and print it out if needed.
IMO this is much cleaner than a GET variable.
As #Mark wrote, you can send a message in a variable by the url in your header() (I mean url + "?variable=$variable") and capture the message in your page (now php page) by $_GET. The message will depend on your validation
Of course you can check: https://stackoverflow.com/a/872522/2737474 (#Jrgns)
Different ways to pass one variable between pages.
In my opinion, you must be careful in choose one of those:
-If you would use one value for many pages (keeping in mind it would be store on server), it would be better to use SESSION.
-If you would use one value for only two pages, it would be better to use GET or POST (depending on your situation, url/form).
-If you would use one value for many pages and want to keep it between sessions (keeping in mind it would be store on client), it would be better to use COOKIE.
You can do this with using $_GET[] method
If validation is successful then redirect to url like
form.php?status=1 // 1 for success
If validation is failed then redirect to
form.php?status=0 // 0 for fail
In form.php which is your form page.
use simple if-else condition
if(isset($_GET['status']))
{
if($_GET['status']==0)
echo'something went wrong';
//else nothing
}
As many clever users wrote you have several methods how to achive this (I won't write all of these):
1st Use sessions check Daniel's answer
2nd Use GET check Sanket Shembekar's answer
3rd Use rZaaaa's answer, but you can enchant it :D
Enchant:
Page 1
header('error: true');
Page 2
print_r(headers_list()); //and find your error

PHP - Smarty Variables unset after header redirect

I have a php file (form.php) that uses a template (form.htm) to display a form. The template file's form action is form.php. If the form is incomplete when submitted, I want to redirect back to the form WITHOUT losing information that the user has already input.
I'm setting smarty variables using t->assign('varname', $_POST['var']) and setting the form values to these variables ( value="{$varname}" ), however when redirected using php's header() function, these Smarty variables are lost (which I've confirmed using Smarty {debug}).
Does anyone have any idea of how to make it so that these variables aren't unset when using a header redirect? Thanks!
Smarty is only template engine, so you cannot do here more than in PHP.
But in your case you said you want to make header redirect after sending form (to be honest I have no idea why you want to do it. In normal case you simple set action in form and in controller you simple check data and if they are valid you do what you want - for example send email and if they are not valid you simple show the form again - that's it).
However if you really need to do this that way, what you can do is to use session data and save all data from post to session, make redirection and use that from session to display in Smarty.
So in PHP you can do:
$_SESSION['post_data'] = $_POST;
// now you make redirection
And in file you handle redirection you can simple do:
$smarty->assign('post_data',$SESSION['post_data']);
unset($SESSION['post_data']);
And in template file you can then use:
{$post_data.var}
EDIT
But as I said normally you do it this way in PHP file:
$isValid = false;
if (isset($_POST['submit']) {
$isValid = validateData($_POST);
if ($isValid) {
// do something here - for example send email
}
else {
$smarty->assign('error', 'There were errors in your form. Try again');
}
}
$smarty->assign('is_valid',$isValid);
And in Smarty you do:
{if $isValid}
form was sent
{else}
{if isset($error)}{$error}{/if}
you display form here
{/if}
Don't redirect the user. Just redraw the form. In general, this HTTP workflow should be used when dealing with forms:
GET /form.php - Display the form to the user
POST /form.php - Process the form input
If the form input is invalid, send back form.php
If the form input is valid, save to the database, now redirect the user
So basically you have:
GET
POST (invalid input from the user)
POST (valid input from the user)
REDIRECT

How do I stop people manipulating URLs to submit forms in PHP?

When a user submits any form, a $_GET['variable_name'] is sent by the webpage and will give a URL like the following: www.mywebsite.com/index.php?variable_name_here='yes'.
However people can just write the URL www.mywebsite.com/index.php?variable_name='yes' into the address bar of the website and gain access to this part of the script, without actually submitting the form!
This is a problem! It's breaking specific parts of the script linked to that form submission! This is because the part of the script relating to the $_GET['variable_name'] can't get the variables that should be sent by the form as it is never submitted!
How do I stop people getting to specific parts of a script when they manipulate the URL by sending them back to www.mywebsite.com/index.php?
P.S. : This is for user submitted data through a form which is then processed (no SQL or any alike software involved)
If you are worrying about people getting in to your site without logging in or not having correct params, you should first check to see if the correct $_GET variables exist using isset(). If all paramaters you are expecting exist allow them to pass, otherwise use header('Location: /index.php'); to force a redirect.
To redirect from www.mywebsite.com/index.php?variable_name='yes' to www.mywebsite.com/index.php you would need to include the following code below before you open a HTML header! This solution will work for any $_GET variables within your whole website if you place it within an includes("filename_here"), no need to change the code.
//if there are any $_GET variable(s) set (doesn't matter what the name of the variables are)
if (! empty($_GET))
{
//if there is no record of the previous page viewed on the server
if(! isset($_SERVER['HTTP_REFERER']))
{
//get requested URL by the user
$redir = $_SERVER['PHP_SELF'];
//split parts of the URL by the ?
$redir = explode('?', $redir);
//redirect to the URL before the first ? (this removes all $_GET variables)
header("Location: $redir[0]");
}
}

Reset URL on form submit

I have a form that acts as a filter to a list of inventory.
The form works well but I have been using get in order for the user to flip through pages, for example:
Next page
<?php } ?>
I am getting my data from XML and this is the way I've found works best. However, the form to filter is POST and if a user clicks next page and tries to use the filter afterwards(bunch of drop boxes) then It also uses the get-parameters that have been passed to the URL from the link.
Is there a way, that no form submit, It will reset all the parameters?
http://www.website.com/used-cars/?pos=10&q=Model-Corolla%2C&srt=KMDfr
That would be preform submission, and once the form is submitted, it will look like this:
http://www.website.com/used-cars/
And there will be no GET variables for the page to get anymore.
Yes, after you're done with your processing, call
header("Location: /used-cars/");
die();
And it will redirect the user to the wanted page.
First of all, don't just use the default header("Location...") alone, because that would send a 302 Found (previously called: Moved Temporarily) response, which kinda "lies" about the actual behavior (as it still means "The requested resource resides temporarily under a different URI"). Worse yet: if a form uses POST (which most do), a conforming browser should even ask for permission before redirecting, according to HTTP 1.1.
So, to properly reset form URIs with a GET, use 303 See Other instead, which was specifically added for this purpose.
(It's nice to also combine it with a 201 Created response intended to ack. successful form submissions, so adding a
header("HTTP/2.0 201 Created") to the result page is a nice touch.)
But, to address your old comment "Where would I add this php code? I'm not sure where to put it, the form submission reloads the current page." (though you probably figured it out since then ;) ):
You'll have to handle not only two, but at least three, or even four cases (in conditional branches):
You send the form for displaying + submitting.
You receive the the form data, store it somewhere (i.e. "create a new resource", the idea behind 201 Created), and redirect to a clean URI.
To avoid redisplaying the form again as if nothing had happened (or redirecting forever to the same page), you must detect if you have just redirected to yourself...
But, since you've now removed all the inputs from the URI, you must use some other means to keep track of state. Some straightforward ways for that:
a) Redirect to a different URI.
b) Use a PHP session.
And, finally, if needed: reset and display the form again for new inputs.
Here's an example (with 3/b, and a kind of "faked" 4, for simplicity):
session_start();
if (isset($_GET['some_input'])) // Case 2: We got data!
{
file_put_contents("result", $_GET['some_input']);
$_SESSION['redir'] = true;
header("Location: /used-cars/", true, 303);
exit;
}
else if (isset($_SESSION['redir'])) // Case 3: We have redirected!
{
unset($_SESSION['redir']);
http_response_code(201); // Acknowledge receiving the form data.
echo "OK, we have happily processed the last submitted data: ",
file_get_contents("result"), "<br>";
echo "Reload the page to fill the form again!"; // Case 4: Reset...
}
else // Case 1: Send the form...
{
echo <<<_
<form>
<input type="text" name="some_input">
<input type="submit">
</form>
_;
}

How to show 'success' message on form submit without changing URL?

I have a PHP site (with CodeIgniter) that includes a registration form. I have a page with some details, which links to the form on a separate page. The form posts to a third URL which does the processing and redirects back to the first page if it's successful (or the form page if not).
Currently I am adding a parameter for success: example.com/page?success=1 which shows a success message. The problem is that some people have been sharing this URL (and clicking the Facebook Like button) so when another user opens that URL they see a message "thanks for registering!" which they obviously haven't done yet.
I thought this was the standard way of doing forms (submitting to one URL and redirecting to another) but is there a better way? I don't want to post back to the same page because then you get the POSTDATA warning when trying to reload the page.
You have three ways to do this
The way you're using
Not actually redirecting but sending request(s) with AJAX
SESSION (or, in edge case, cookies)
If you select to use SESSION, you can just assign a session variable to true
$_SESSION['registered'] = true;
and checking it on the first page
if (isset($_SESSION['registered'])) {
unset($_SESSION['registered']);
// shot the message
}
Typically you would set your flag for success in the session to display this message when the next page loads. This is commonly referred to as a Flash Message. You would then check the value/existence of this session flag and show your message or not accordingly. In most frameworks there is built in functionality for this which includes the clean up of the flag on the next request so that the message is only displayed directly after the action generating it is taken.
From the CI Sessions Documentation:
CodeIgniter supports "flashdata", or session data that will only be
available for the next server request, and are then automatically
cleared. These can be very useful, and are typically used for
informational or status messages (for example: "record 2 deleted").
Note: Flash variables are prefaced with "flash_" so avoid this prefix
in your own session names.
To add flashdata:
$this->session->set_flashdata('item', 'value');
You can also pass an array to set_flashdata(), in the same manner as
set_userdata().
To read a flashdata variable:
$this->session->flashdata('item');
If you find that you need to preserve a flashdata variable through an
additional request, you can do so using the keep_flashdata() function.
$this->session->keep_flashdata('item');
You should have some verification checks in your code that handles the processing of the form data to make sure that the required fields are filled out. Otherwise, you should be redirecting to your first page to have the user fill out the form.
Also, this could be handled via AJAX, but that would be a second step to having the proper verification in your form-processing page
HTML:
<form method="post">
<input type="text">
<input name="submitted" type="submit">
</form>
PHP:
if($_POST['submitted']{
//post was submitted process it
if(/*whatever you're doing to the form succeeds*/){
//show success
}
}
POST will not show variables in the URL.
Several solutions here, one would be to check for the form submission and if it hasn't been submitted redirect to the page with the form on it.
ie:
<?php
if (isset($_POST['submit']))
{
// process the form
}
else
{
//redirect to the form itself
header( 'Location: http://www.yourform.com' ) ;
}
?>

Categories