How to avoid Page Reload Resend-Data message with PHP - php

I am relatively new to PHP, so my apologies if the answer is trivial. Lol
I wrote a simple Contact Us email form (actually a WordPress page-template file). All the code is in one file.
After the user submits the form and the email is sent, the file generates a Thank You message.
If the user reloads the Thank You page, they are prompted to "Resend the Form Data," which is why I am asking this question.
My question: How do I avoid the prompt to resend the form data and still keep all of my code (including the Thank You data) in one file?
EDIT: I've seen folks use headers( Location: ), but I don't think that will work for if I want to keep all my code in one file.

You could redirect to a different query.
header("Location: ?page=thankyou");
Then, you don't even need to check if the POST data was sent. Just display the thank you page if page is equal to thank you.

This worked for me, it can be put anywhere in html file not just beginning like header() function:
<?php
if (!empty($_POST)){
?>
<script type="text/javascript">
window.location = window.location.href;
</script>
<?php } ?>
I placed it into prevent_resend.php and then included it after the postdata processing was done.
// ... save data from $_POST to DB
include('prevent_resend.php');
// ... do some other stuff

You can use javascript to post the form and show the thank you message. This way the browser never leaves the page.

Even with a header('Location: xxx'); you can still redirect it to the same page, and either set a url parameter or a session variable to distinguish what should be shown.

Although I question your requirement to have all the code in one file (why couldn't you separate it, and use require_once to include shared library code?), the header('Location:') technique is still completely valid. Simply do:
header('Location: http://www.example.com/path/to/my-one-file-of-code.php?thankyou=1');
Then, in your file, you can have:
if (isset($_GET['thankyou']) && $_GET['thankyou']) {
// Do whatever it is you do to thank the visitor.
}

This worked for me:
header("Location: #");

Related

Check if cookies are enabled without redirect

I need on each page check if cookies are enabled.And use this code.
<?php
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
if(!isset($_COOKIE['COOK_CHK'])){
echo"Cookies are disabled!";
exit;
}
session_start();
?>
However on the first check it gives me false until i don't refresh the page.I include this code in each page so can not redirect every time i load the page as it reduces performance.However i want to use it even if javascript is disabled.Any suggestions?
Can you use javascript? If so, all it takes is a check at the navigator.cookieEnabled variable.
It works in most modern browsers. You can read more about it here: http://www.w3schools.com/jsref/prop_nav_cookieenabled.asp
It's not possible because Cookies are in the browser, and PHP send them when the page has render, so will be available just in the second page.
A possible way to fix this is using javascript.
If you really should do it in PHP, for some crazy reason, send all your request to a main controller and save the state using other method, for example, write a var into a file, then redirect and in the next redirections you'll know if the cookies are enabled without needed any other redirection. Example:
$file = 'cookie_fake_'.$userIP;
if( !isset($_COOKIE['COOK_CHK']) && !file_exists($file) ){
file_put_contents($file, 'dummy');
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
header('Location:/');
exit;
}
if(!isset($_COOKIE['COOK_CHK'])){
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
echo"Cookies are disabled!";
exit;
}
Then you should write something to clean old files every hour or so, of course you can use a cache layer or a database or anything like that instead of writing a file.
Edit: The previous code will be really f** up if the user enables cookies and refresh the page, now I've fixed so it works at the second time it refresh. Not perfect but... You really should do this using javascript.
Cheers.

redirection without reloading the whole page

I have a framework and I think I'm following something like the MVC pattern: A framework (the model) an index page that controls the input (the controller) and the views pages (that are included inside main.php/the main html)
I read a lot about structure and logics, to write a good application. I read many comments like "Why are you outputting anything if all you are going to do is try and redirect the user to another page?". Well the answer is, the most common case: redirect after the user successfully logged in. Do I need to print something? Of course, the whole main page with a login form/post. How I'm supposed to do that redirection??
So I'm a bit confused about logics and structure of the application. How do you store all the output and do the header redirection without printing anything?
I was thinking about using javascript to do the redirection but I also read comments saying; "if you write good code (following a good logic/structre), you won't need to use hacks like javascript redirection". How is that even possible?
Because the php output_buffering should not be enabled.
I have the output_buffering enabled, and I can use header (after output) without any problem. If I use the javascript redirection the whole page reloads, but using header it just loads the content (the views content that are included in main.php).
So how do you do this without output_buffering?
If you want to redirect to a success page AND pass messages - say, after a successful login - an easy solution is to use "flash" sessions, where you store a message in a SESSION and then, as soon as it's used, you discard it. You don't need to sore anything in the output buffer for this.
This is a very basic example, but should give you the gist of it.
login.php
if($login_successful) {
// put your message in the session
$_SESSION['message'] = 'Login Successful';
// redirect to the success page
header('location: success.php');
}
success.php
<?php
session_start();
// check if $_SESSION['message'] exists
if(isset($_SESSION['message'])) {
// print the message
echo $_SESSION['message'];
// clear the session
$_SESSION['message'] = null;
}
Looks like you are mixing up some things here. What you are talking about are actually two different requests. Either the user wants to view the main page, or he wants to log in using that form on your main page. In your index.php you would have something like this (pseudocode):
if (isLoginRequest) {
// user wants to log in
if( validateLogin($loginFormData) ) {
redirect('successful');
} else {
displayLoginError();
}
} else {
// user wants to view main page
echo main.html
}
Update to answer the question in the comments: The better alternative would be to leave your form validation stuff in login.php and refer to that in your login form <form action="login.php" .... Then in your login.php you would have something like this:
if (loginSuccessful) {
redirect('success.php');
// no need to call die() or whatever
} else {
setFlashMessage('Login failed'); // set a flash message like timgavin described
redirect('index.php')
// also no die() or whatever
}
index.php then is responsible to display your main page and, if set, rendering the flash message from a failed login attempt.
Simple solution: Move the login post script from login.php to another file (login_post.php). The same for other scripts using header() after dom output. (no need to change the form action="")
In index.php:
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
//some more security checks like esc_url() (non-php function)
if ($url == '/login') {
include('header_pages/login_post.php');
}
// all these includes before including main.php
// where views pages are included and the DOM output starts
Since header() is inside the post script, no more headers already sent errors (And output_buffering off, of course).
Same for logout page that is currently being included inside main.php
Thanks to the other answers, they helped me finding this solution.

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

How to go to new Html page from PHP script?

After the php script is over, how do I go to another html page?
Why would you want to do that? When the page is over (which I understand as the script ended execution), it is usually sent to the client and then it can be viewed by the user. So, basically, what you are trying to do is to redirect the user after the script stopped executing.
If so, you have two solutions available:
Do not output anything, and after your script stopped executing, use the header() PHP function:
header('Location: http://example.com/some/url');
where you should replace the example URL with your own.
If you are outputting the HTML page and sending it gradually to the user, you can just put JavaScript redirection script at the end of the page (so after everything has been sent):
<script>
window.location = 'http://example.com/some/url';
</script>
Does any of these solutions work for you?
header('Location: /page.html');
Make sure you don't output anything else, then simply
header('Location: http://www.example.com/');

Display message only for the first page load

I would like to display thank you message after adding comment only for the first page load... The comment form is processed using an external php file and than redirected back to the page. I would like to display some message after the redirection only... What would be the best way to do this using php?
Assuming you have access to the external php file that processes the file you could do something similar to the following on the processing file:
$_SESSION['flashMessage'] = 'Thank you for posting.';
header("Location: your-page.php');
And then add the following to the redirect page:
if ($_SESSION['flashMessage']) {
echo $_SESSION['flashMessage'];
$_SESSION['flashMessage'] = NULL;
}
Save the mesage into a session. Display it, and after just unset the session variable.
On the page where the comment is processed:
if($success)
{
$_SESSION['userMsg'] = "<p>Your comment has been added. Thank you.</p>";
}
In any/all pages (but mainly the one you're redirecting to):
if($_SESSION['userMsg'] != '')
{
print $_SESSION['userMsg'];
unset($_SESSION['userMsg'];
}
This is assuming you're using Sessions and have therefore previously called the session_start() function
When you redirect send via $_GET array a variable something like this:
header("LOCATION: index.php?msg=1" );
On index check if $_GET['msg']==1 then display your message
You may want to apply PRG pattern.
Basically you post the comment and the server replies to the client to perform a redirection to your page with additional info in Query string as Vadim argued.
"Elegant", sessionless and functional.

Categories