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.
Related
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.
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
There are URLs which I use only for redirecting a user after a successful operation. (e.g. a "Thank you" page after submitting feedback).
The problem is that these pages can be accessed directly.
Is there a way to prevent this?
function thank_you() {
if($this->referer() != 'some_url') {
$this->redirect('/');
}
}
in the method you don't want to be accessible directly, just check to see if the referrer valid (i.e. the "contact form" for the "thank you" page.
If the referrer isn't the "contact form", you can redirect to wherever. If it matches, output the thank you page.
You could create and store a random key upon completion of the operation, then simply verify that the key (using a combination or session, url, or db, your pick) is valid before redirecting.
Looks like Controller::flash can help you.
I'd set a session variable on the page right before the redirect. Then on the "thank you" page, the variable is tested for and unset. If it was not there when the test was made, then redirect to an error page that says "This page cannot be accessed directly."
I have never used Cake, so that's a general PHP answer, not a Cake specific one.
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: #");
I have a login form in every page of a website so the user can login from everywhere. I have a login.php file that I refer to it from the form (using 'action').
I use $_SERVER['HTTP_REFERER'] to redirect the user to the same page he logged in from when he succesfully log in or when he logs out.
But if there was a problem logging in, how can I send an error to the same page he is trying to log in?? I have tried sending the error using $_GET, like this:
// process the script only if the form has been submitted
if (array_key_exists('login', $_POST)) {
// Login code goes here...
// If there was a problem, destroy the session and prepare error message
else {
$_SESSION = array();
session_destroy();
header('Location: '.$_SERVER['HTTP_REFERER'].'?error');
exit;
}
But the problem is that a lot of pages in the website are like this details.php?mid=0172495. They already recive information from the $_GET method and for security reasons I cant use another $_GET method...
So, How can I pass the error???
Thanks...
Since you're already using sessions, after you destroy the session why not create a new one with $_SESSION['error'] or something similar set? Or alternatively simply don't delete the session at all but set the error which you can immediately check in other pages?
To add to what Chad Birch said...
In your login script where you redirect, check the HTTP_REFERER value for the character '?'. If it is present, append '&error' to the HTTP_REFERER and redirect to that. Otherwise append '?error' to the HTTP_REFERER and redirect to that.
I'm not sure what exactly you mean by "for security reasons I cant use another $_GET method", but in the case that there's already something in the query string, you just need to append another variable to it, instead of replacing it.
That is, if the address is like details.php?mid=0172495, you should be sending them to details.php?mid=0172495&error, whereas if it was just details.php, you send them to details.php?error.
Another way of doing what you need is to include your login.php file in every page that has the login form and just post to that same page. So you won't need any redirection at all.
This maybe is not a good scalable and maintainable solution, but it is simple. It all depends what kind of app you are writing. But you are saying that you are new to php so you can start like this. You can always go fancy later...