I'm trying to redirect people to a PDF after they've submitted the form correctly, before I do this I do some checking of the form fields to make they've been filled out correctly, now I was trying to use header() to do my re-direct, but because I've echoed a number of times before I get an error. Here's my code below, what can I do?
<?php
if(isset($_POST['submit'])) {
if($valid_fname == "Y") {
if($valid_sname == "Y") {
if($valid_company == "Y") {
if($valid_email == "Y") {
}
else {
echo "<p class=\"secText\">Please enter a valid email address</p>\n";
}
}
else{
echo "<p class=\"secText\">Please enter the company you work for</p>\n";
}
}
else {
echo "<p class=\"secText\">Please enter your surname</p>\n";
}
}
else {
echo "<p class=\"secText\">Please enter your first name</p>\n";
}
if(($valid_fname == "Y")&&($valid_sname == "Y")&&($valid_company == "Y")&&($valid_email == "Y")) {
echo "<p class=\"secText\">Thank you for confirming your details, you will be re-directed to \"The Personal Touch\" Whitepaper shortly.</p>\n";
header('Location: http://www.sefasinnovation.co.uk/personal_touch.pdf');
exit();
}
}
?>
EDIT Ok I got it to work with a bit of javascript in the end
if(($valid_fname == "Y")&&($valid_sname == "Y")&&($valid_company == "Y")&&($valid_email == "Y")) {
echo "<p class=\"secText\">Thank you for confirming your details, you will be re-directed to \"The Personal Touch\" Whitepaper shortly.</p>\n";
echo "<script type=\"text/javascript\">\n";
echo " <!--\n";
echo " setTimeout(\"window.location = 'http://www.sefasinnovation.co.uk/personal_touch.pdf';\",5000);\n";
echo "//-->\n";
echo "</script>\n";
}
You could use output buffering to send content only after the headers have been sent.
if(($valid_fname == "Y")&&($valid_sname == "Y")&&($valid_company == "Y")&&($valid_email == "Y")) {
ob_start();
echo "<p class=\"secText\">Thank you for confirming your details, you will be re-directed to \"The Personal Touch\" Whitepaper shortly.</p>\n";
header('Location: http://www.sefasinnovation.co.uk/personal_touch.pdf');
ob_end_flush();
exit();
}
However since there is practically no time to display the message before the redirection is done this approach would be useless.
Your best approach here would probably be to redirect your page to a small HTML page which will trigger a JavaScript redirect after a certain amount of time has passed. Here is the general idea. You should sort the details out.
PHP
if(($valid_fname == "Y")&&($valid_sname == "Y")&&($valid_company == "Y")&&($valid_email == "Y")) {
header('Location: http://www.sefasinnovation.co.uk/notification.html');
exit();
// You could also avoid redirection to an HTML file and output the code directly
echo <<<HTML
<html>
<head>
<title>Enter desired title</title>
<script type="text/javascript">
setTimeout(function(){
window.location = "http://www.sefasinnovation.co.uk/personal_touch.pdf";
}, 5000);
</script>
</head>
<body>
<p class="secText">Thank you for confirming your details, you will be re-directed to "The Personal Touch" Whitepaper shortly.</p>
<p>If this page isn't redirected in 5 seconds please click here.</p>
</body>
</html>
HTML;
}
notification.html (the PHP code above could also spit this code out but only if there was not output on the page previously)
<html>
<head>
<title>Enter desired title</title>
<script type="text/javascript">
setTimeout(function(){
window.location = "http://www.sefasinnovation.co.uk/personal_touch.pdf";
}, 5000);
</script>
</head>
<body>
<p class="secText">Thank you for confirming your details, you will be re-directed to "The Personal Touch" Whitepaper shortly.</p>
<p>If this page isn't redirected in 5 seconds please click here.</p>
</body>
</html>
The additional link in notification.html should allow users to do a manual redirection in case JavaScript is disabled.
try to make a link to redirect the user to the pdf page so the link contains the pdf page url
Thank you for confirming your details
or you can use the meta tag to redirect the user after 2 second
<meta http-equiv="refresh" content="2; url=http://www.sefasinnovation.co.uk/personal_touch.pdf" />
Your problem is here:
if(($valid_fname == "Y")&&($valid_sname == "Y")&&($valid_company == "Y")&&($valid_email == "Y")) {
echo "<p class=\"secText\">Thank you for confirming your details, you will be re-directed to \"The Personal Touch\" Whitepaper shortly.</p>\n";
header('Location: http://www.sefasinnovation.co.uk/personal_touch.pdf');
exit();
}
You can't output anything to the page if you want to send redirection headers. Remove that echo statement and try the page again.
Alternatively, you can write a HTML page with a redirection <meta> tag (you can make it delay like 5 seconds and then redirect. Your message will then work).
Look it up on Google for a tutorial.
Related
I'm trying to get a page refresh once after a set amount of seconds only on a set page.
So something like
if is_page('test.php') {
refresh page 5000(once);
} else
continue
You can do this by jQuery
like
window.setTimeout(function() {location.href="URL of test.php"}, 5000);
in PHP you can:
if(is_page('test.php') && !isset($_GET['r'])){
header("Refresh: 5;url='http://zasite.com/test.php?r=1'");
}
NOTE: This can only be done if the headers have not already been sent http://php.net/manual/ro/function.headers-sent.php otherwise you will end up with a warning and the refresh will not work. A workaround would be:
if(is_page('test.php') && !isset($_GET['r'])){
if(!headers_sent()){
header("Refresh: 5;url='http://zasite.com/test.php?r=1'");
} else {
echo '<meta http-equiv="refresh" content="5" ; url=http://zasite.com/test.php?r=1>';
}
}
OR - PHP with Gyandeep Sharma's JS answer
if(is_page('test.php') && !isset($_GET['r'])){
if(!headers_sent()){
header("Refresh: 5;url='http://zasite.com/test.php?r=1'");
} else {
echo '<script>window.setTimeout(function () {location.href="http://zasite.com/test.php?r=1";}, 5000);</script>';
}
}
I need a little help here. I have a page profile.php and a option to delete the accound :
// DELETE THE ACCOUNT !!
$_SESSION["delacc"] = FALSE;
if (isset ($_POST ['deleteaccount'])) {
$deleteaccount = $_POST['deleteaccount'];
$delacc="DELETE FROM users WHERE username='$username'";
$resdelacc = mysqli_query($con,$delacc);
if ($resdelacc) {
header('Location: index.php');
$_SESSION["delacc"] = TRUE;
unset($_SESSION['username']);
} else {
echo "ERROR !!! Something were wrong !!";
}
}
the problem is in if ($resdelacc). If this is true, result that the account was deleted, unset session username (logout) and after this I want to redirect the page to index.php where I have the code :
if(isset($_SESSION["delacc"])) {
if($_SESSION["delacc"] == TRUE) {
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
$_SESSION['delacc'] = FALSE;
}
}
My only problem is that this line " header('Location: index.php');" (from profile.php) don't run in any case. When the user click the button "DELETE ACCOUNT", the page remain profil.php, then, if do refresh or access another page, is redirected and appear as guest.
Very easy .. The reason is after in the resulted output page you can't redirect. so you've prepare it to be redirected after some seconds enough for user to read the result message.
Like this:
if($_SESSION["delacc"] == TRUE) {
$_SESSION['delacc'] = FALSE;
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="7;url=http://'.$_SERVER['HTTP_HOST'].'/index.html"/>';
echo "</head><body>";
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
}
that change will redirect to the index.html after 7 seconds.
PS. The Generated HTML result page make it starts by this code after the POST handling direct. (before any echo) because echo will start generating the results page and the only logical place to redirect is inside the HEADER before any BODY elements
<meta http-equiv="refresh" content="0";url="/index.php"/>
The redirect (url) don't run for index.php because I have another redirect before :
if(isset($_SESSION['username'])==FALSE) {
header('Location: login.php');
}
but is ok, I put the message "DELETED SUCCESFULLY" in login.php and deleted from index.php . I set content=0, because after deleted, the user will be restricted for page profile.php and need to change immediatelly to another. Due of the verification of SESSION['username'] which can return profile.php, I can not redirect to another page ... is a conflict. I need a little to think better this code with redirects, I know can solve it better :D thanks for explanations and help
i have a multi step form and want to condition users on specific sites on my web .
This mean i want that only after submitting my form a client in my case can see the redirected page ,
And that with a kinda tim-out for that page to . this redirected page need to show only to those people who fill the form first even when users copy the link and give that link to somebody else the link should not work or should direction in a error. i have archived the last part partly
Here is all my code :
On the form.php i have this :
<?php
session_start(); $_SESSION['form_finished'] = true;
?>
On the proces.php i have this :
$emotion = $_POST['emotion'];
if($emotion == 'Basic Pack') {
session_start();
$_SESSION['form_finished'] = true;
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
and destination site in this case basicc.php' this :
<?php
session_start();
if(!$_SESSION['form_finished']) {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
This code is working partly because if the user on the form.php site if he just copy the basicc.php link on the address bar he can see the basic.php site imadtitly without having to fill the form , and i want that to condition him to do that and than the page to show up .
I hope i was clear thanks in advance
If proces.php is where submitting the form redirects then remove $_SESSION['form_finished'] = true; from form.php and keep it in proces.php only.
ETA: For the timer:
<script>
var remainingSeconds = 600; // how many second before redirect
function counter() {
if (remainingSeconds == 0) { clearInterval(countdownTimer); window.open('form.php', '_SELF'); // return to form page
} else { remainingSeconds--; }
}
var countdownTimer = setInterval('counter()', 1000); // 1000 is the interval for counting down, in this case 1 second
</script>
In this case, you will have to add back the statement in form.php but set it to false $_SESSION['form_finished'] = false;
ETA2: Forgot to mention that you should also add $_SESSION['form_finished'] = false; in basicc.php.
Yes you could just use a simple session for this case. Example:
If in your form action, if the form processing is in process.php. You could initialize there the session.
session_start();
$emotion = $_POST['emotion'];
$_SESSION['form_finished'] = true; // set session
// then your other process etc. etc.
if($emotion == 'Basic Pack') {
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
And then on the destination files: /new/basicc.php and others, check that session existence:
/new/basicc.php and others:
if(isset($_SESSION['form_finished'])) { // so after redirection check this
//
// hello, i came from process.php
unset($_SESSION['form_finished']); // and then UNSET it! this is important
} else {
echo 'not allowed'; // if this is not set, the page is directly accessed, not allowed
exit;
}
I think the best solution is that you should only use one page, no need for sessions ;)
Try to have a particular variable set to false, send your form to the server using a POST method <form method=post> and on your server, change this variable to true and render the same page again.
In the example below, I'm checking if the user has entered his name in the form. ;)
<!-- In form.php -->
<?php
$formSubmitted = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["name"])) {
//Do what you need to do with form data, for example:
$name = filter_var($_POST["name"],FILTER_SANITIZE_STRING);
//Maybe do some checks on the data (or add to database) and when successful:
if($name != '')
{
$formSubmitted = true; // Set variable to true
}
}
?>
<?php if($formSubmitted): ?>
Hello <?php echo $name; ?>! <!-- Show all other HTML things you want to show -->
<p> This is a message only for people who submitted the form! </p>
<?php else: ?>
<form action='form.php' method='POST'>
<input name='name' type='text'>
</form>
<?php endif; ?>
I hope it'll be useful and hopefully a different way to look at the problem. For multi-step, this could easily accommodate more variables to see which step the user is on ;)
Good luck :)
I got a little problem. When I got my PHP script without header it's fine, I am getting javascript alert box. But when I use header before alert it's not working. It's redirecting me like it should, but it's not showing any box. Could someone help me?
if ( $pkt < 1 OR $user_id == 0) {
header("Location: http://dunno.com/file.php");
$message = 'This is a message.';
echo "<SCRIPT> //not showing me this
alert('$message');
</SCRIPT>";
mysql_close();
}
And here's the one which work (but without heading)
if ( $pkt < 1 OR $user_id == 0) {
$message = 'This is a message.';
echo "<SCRIPT> //showing me
alert('$message');
</SCRIPT>";
mysql_close();
}
I would be thankful for help :)
#edit Maybe is there any command to make alert wait until whole browser load? (if it's the problem)
Maybe try redirect using JavaScript.
if ( $pkt < 1 OR $user_id == 0) {
$message = 'This is a message.';
echo "<SCRIPT> //not showing me this
alert('$message')
window.location.replace('url of the page');
</SCRIPT>";
mysql_close();
}
I know this is a old post, but here is how I made it in a similar example. This example checks if the administrator has logged in from a specific IP address, if it returns false it should redirect the user back to the login page and show an error message.
User has logged in page:
if ($_SERVER['REMOTE_ADDR'] == "ip address"){
$admin = True;
}else{
session_start();
$_SESSION['errorMessage'] = "WARNING: You dont have access to this area.";
header("Location: login.php");
}
login.php:
session_start();
if(isset($_SESSION['errorMessage'])){
echo "<script type='text/javascript'>
alert('" . $_SESSION['errorMessage'] . "');
</script>";
//to not make the error message appear again after refresh:
session_unset($_SESSION['errorMessage']);
}
this is a redirect:
header("Location: http://dunno.com/file.php");
the code below wont work
Your error is in the structure of your code. PHP, even in OOP is procedural and will run each line one after the other. So the way you've structured your code means the page is redirected before your echo. A better method is to use the javascript alert box to redirect your page using:
var prompt=window.confirm("message here. \r\n"+"Do you want to redirect?");
if(prompt)document.location.href='http://dunno.com/file.php');
Aaroniker is correct with the redirect comment. One way to make it work would be to send the message with a session variable and then add the message creation to the next page like so.
session_start();
if ( $pkt < 1 OR $user_id == 0) {
$_SESSION['message']= "this is a message";
header("Location: http://dunno.com/file.php");
On file.php:
session_start();
echo "<SCRIPT> //not showing me this
alert($_SESSION['message']);
</SCRIPT>";
mysql_close();
}
Another option would be to pass them with you header. Like so:
if ( $pkt < 1 OR $user_id == 0) {
$message= "this is a message";
header("Location: http://dunno.com/file.php?message=" . $message . ");
Then on file.php:
echo "<SCRIPT> //not showing me this
alert($_GET['message']);
</SCRIPT>";
mysql_close();
}
Use $_SERVER 'php_self'. It will allow you to create script on same page where you want alert. In this way you won't have to add header.
Here's an example:
<form name="login" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" accept-charset="utf-8" class="form_class">
<ul>
<li>
<label for="usermail">Username</label>
<input type="text" name="username" placeholder="Enter username" required>
</li>
<li>
<label for="password">Password </label>
<input type="password" name="password" placeholder="Enter your password" required>
</li>
<li id="custom">
<input type="submit" value="Sign In">
</li>
</ul>
</form>
$sqluname="root";
$sqlpword="hrhk";
$database="registration";
$server="127.0.0.1";
$db_handle=mysql_connect($server,$sqluname,$sqlpword,$database);
$db_found = mysql_select_db($database, $db_handle);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uname = $_POST["username"];
$pword = $_POST["password"];
$ulength=strlen($uname);
$plength=strlen($pword);
if($ulength > 5){
$sqlquery="SELECT * FROM members WHERE username='$uname' AND password='$pword'";
$result=mysql_query($sqlquery);
$num_rows=mysql_num_rows($result);
if ($num_rows >0) {
echo "<script>alert('Logged In');</script>";
session_start();
$_SESSION['sid']=$uname;
header("location:Yahoo/yahoo.php");
}
else{
echo "<script>alert('Wrong Username or Password!');</script>";
}
}
else{
echo"<script>alert('Username should be greater than 5 characters.');</script>";
}
}
?>
The below header function will run a 302 redirect by default and redirect the client to http://dunno.com/file.php so any code after the code begin processed after the header function will not be seen as the client is redirected from the page this code is on.
header("Location: http://dunno.com/file.php");
Please read up further on the header function here: http://www.php.net/manual/en/function.header.php
You could make you program sleep/wait for a few seconds(lets say 10 seconds for this example) before redirecting if you need the message to display like so:
if ( $pkt < 1 OR $user_id == 0)
{
$message = 'This is a message.';
echo "<SCRIPT> //not showing me this
alert('".$message."');
</SCRIPT>";
sleep(10);
mysql_close();
header("Location: http://dunno.com/file.php");
}
so I need to figure out how I can get my else statement to return to my previous function which is passprotect.html (the file I start on).
So I write in my password and click submit.
When I hit submit it checks with my PHP if the password is correct or not.
If the password is correct it writes "You did it!".
If it is wrong I want it to return back to the passprotect.html site with an error message saying, "Wrong password, try again!".
Here is my two codes:
<html>
<body>
<title>FriedBitz</title>
<form action="secret.php" method="post">
Password: <input type=password name=pass></input>
<input type=submit value=Enter>
</form>
</body>
</html>
and
<html>
<body>
HERE IS YOUR RESULT
<?php
if ( $_POST['pass'] === 'test')
{
echo "You did it!";
}
else
{
header('Location:www.example.com');
}
?>
</body>
</html>
So as the Marc B noted you can not use header that way.
From the php.net manual -> Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
If you have no option to change layout's of your project files (removing outputs before headers are sent) i suggest you to use ajax for this kind of work.
Or you need to place clickable link for user on a page instead of header.
Example of working header with your code:
<?php
if ( $_POST['pass'] === 'test')
{
$output = 'You did it!';
}
else
{
header('Location:www.example.com');
exit;
} ?>
<html>
<body>
<?php echo $output; ?>
</body>
</html>