One way to have a back button, is to add a hidden input to your form (seeing that is what you are using in a contact page), and using $_SERVER['REQUEST_URI']
as a value and assigning a session array to it and using sessions. Cookies could also be used, but I've used sessions in my example.
First start the session:
<?php
session_start();
// you can uncomment it to destroy previously set sessions
// session_destroy();
$_SESSION['back'] = $_SERVER['REQUEST_URI'];
?>
<form action="page2.php" method="post">
<input type="hidden" name="goback" value="<?php echo $_SERVER['REQUEST_URI'] ?>">
...
</form>
Then on the second page: page2.php
<?php
session_start();
// Your POST information for your contact code goes here
echo "<a href=\"$_SESSION[back]\">Go back</a>";
?>
Or, to have the full http
call:
$link = "http://" . $_SERVER['SERVER_NAME'].$_SESSION['back'];
echo "<a href=\"$link\">Go back</a>";
Sidenote: As I stated in comments,
The only way I know to go back 2 pages is with javascript:window.history.go(-2)
which you could implement that in PHP with an echo.
Another way would be to use a breadcrumb method, but that would require some fancy work.
You could also use a header to redirect, but make sure you're not outputting before header.
Ref:
References:
Footnotes:
What I need is the page that the user visited just before getting to that contact.php page.
If there wasn't a referer to the page, then there is no way for a user to go back, because there is nothing to go back to, unless they use their browser's back arrow button.
- A referer is a link that a person would have clicked from, either from your site or another.
If there was no referer, you can use javascript:window.history.go(-1)
.