I've written a some PHP that interacts with a SQL database and is just around as an intermediate between two pages.
I want a user to automatically be forced to leave that page and move to another (or even a back to previous page function)
What is the easiest way to do this? I'm happy to use PHP, HTML, or JavaScript to do it.
From php you can use the header() function to change the location:
header("Location: newpage.html");
Just be aware that if you're using header, you can't emit any html or whitespace before you make this call unless you're buffering output. Doing so will cause warnings to the effect that headers have already been sent (there is a way to work around this).
To "move" to a page in PHP you can use the header function.
Ex: header('Location: http://www.example.com/');
In PHP I use the following code at the end of a script to move the user to the next page
<?php
// MYSQL SECTION
// PHP SECTION
header('Location: /next.php');
?>
Just make sure you haven't passed any actual HTML in the page before the header code or the script will break with an error that headers have already been sent.
If you script just interacts with SQL database and does not output anything just simply send a redirect header.
<?php
// sql interaction code goes here.
header('Location: /uri/to/secondpage.php');
exit;
?>
from PHP you can call JavaScript by this way
echo "<script>document.location.href = \"yourpage.php\"</script>";
This code wont bother if there any white space or html content before the line.
you can use the php header function
void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
with following example it would be more clear to you.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
?>
but there is some limitation with the header function in php
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. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
in php
<?php
//the user must leave now
echo"<meta http-equiv='refresh' content='".$time_in_seconds."; URL=abc.com'>";//will move after the time specified,,0 can be specified to move immediately
exit();
?>
in js
window.location="abc.com";//will move immediately,you can time using setTimeout function
Related
So I want to make a search form that queries data from a MySQL DB and then feeds the results to another PHP page as in e.g.:
url.com/page?var1=dbresult&var2=dbresult2
I know how to send the request to mysql and receive the data, but how do i forward this data to the other php script automatically? The issue is that I can't change the second PHP page as it is part of a plugin. So basically I'll need to forward the user upon submission of the form and after the SQL query to the second PHP page, providing the data as shown in the example.
Thanks for any hint!
i'm not sure what exactly your requirement but this is answer i think you want, you want to append the data which fetch from db into your url-->url.com/page?var1=dbresult&var2=dbresult2
so when you fetch data from db, you should add this line in your php code
<a href='url.com/page.php?var1=".$dbresult."&var2=".$dbresult2 ." '>click here</a>
where $dbresult and $dbresult2 = data fetch from db
Including action page is the only way recommended by professionals.
In the action page, you have the server side code that process the forms and interact with the DB.
No HTML content is there in the action page.
If the name of a page is **myform.php**,
then the action page can be called something like-**myform_action.php**[or any other name]
But include myform_action.php in myform.php like:
<?php include 'myform_action.php'; ?>
This is not a ultimate solution for this question.
There are many other PHP stuffs works along with this for this requirement.
In case of redirection, PHP uses a function header(). The header() function sends a raw HTTP header to a client. Here is the syntax:
void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
An example:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
?>
OR
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. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>
I'm learning PHP and been looking for this for a while. What I want to achieve is something like so:
if (true/false) {
go to this url;
}
Every time I search terms like php redirects or php links etc., 99% of the time I get something "headers". I read that header redirects can achieve this but no code can go before it, that it must be first on the page else it wont work.
If that's so, then how can I achieve this?
i read that header redirects can achieve this but no code can go before it. that it must be first on the page else it wont work.
That's wrong. There must be no output before this. Thus you have to ensure, that you don't echo, print, ?>something<?php (or whatever) anything before.
if (true) {
header('Location: ' . $url, false, 302);
exit; // Ensures, that there is no code _after_ the redirect executed
}
You can ready everything about it in the official manual. Especially:
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. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
echo '<script type="text/javascript"> document.location = "http://yoururl.com";</script>'
and this will be executed when this part of script is executed.
You can use this if you need some output before the redirect:
header("refresh: $time_in_seconds; url=$your_url);
You still must call this before output is actually sent however. Send the header, then send your output - the page will "redirect" in the time specified.
Disclaimer: I must admit, I'm not sure what the implications of this are and can't find docs on it, so I can't necessarily recommend it - but I can validate that it works.
I want to redirect from login page to my main page using php.
I use the following line of code: header('location:index.php');
inspite of redirection i received the error like:
Warning: Cannot modify header information -
headers already sent by (output started at C:\wamp\www\student\login.php:18)
in C:\wamp\www\student\login.php on line 19
This error occures if you print something before header() function.
For example:
<?php
echo 'test';
header('location:index.php');
exit;
?>
or even:
<html>
<head> .....
<?php
echo 'test';
header('location:index.php');
exit;
?>
You have to move this piece of PHP code before any operation that gives you an output.
You can also do the following trick but it is the second way you should try:
<?php
echo 'test';
ob_start();
flush();
header('location:index.php');
exit;
?>
you need to turn on the output buffer by inserting
ob_start();
at first line of php code
If you have already "echo'd" or "print'd" anything onto the page, either inside your script or outside of any set of PHP tags, then you cannot send any headers anymore. This is what your error message is stating.
Also, you should (try) to use full paths in location tags, it's better for SEO to use full URLs for every link on your website, let alone the redirects.
make sure that the header function is called before any response is outputted, e.g. header() function must be called before any echo functions or print_r, try removing the spaces before the <?php opening tag.
Its very difficult to decide what constitutes output to a page. I tried to eliminate my problem by removing all "echo's", "prints" etc but couldnt make the redirection work. I think there was a problem with a returned sql query. Adding the buffer and flushing it cured the problem.
You need to find out whether the header was sent already sent by checking line by line with header_sent() it will return true or false. If it's already sent you can't use header(). Try meta http-equiv="refresh" content="0;URL='your url'" /.Don't forget to add open and closing tags.<>
header("profil.php?id=" . $show["id"]);
What i tried to do, but headers are already sent at top, so how can I redirect the user? Should I use window.location.replace("URL"); (javascript) instead?
If you can't control the very beginning of the script, where headers would be sent, then yes, your only method is to use JavaScript.
Also, the proper syntax is header('Location: profil.php?id=' . $show['id']);
You need the Location: part so the browser knows what header it's receiving. Also, don't forget to do an exit() or die() right after the redirect.
Someone correct me if i'm wrong, but I think you can use ob_start() at the beginning of your page and that will allow you to redirect via PHP even if headers are already sent.
You should redesign your application, to make it more sensible.
It should start output only when it necessary, not just every time this file is called.
You have to modify all your code by dividing every script to 2 parts. First part will contain all data manipulations and second will contain output only. It will be better to put the latter one into separate file, called template. thus your profiles php will looks like
include 'dbc.php';
//some code that sends headers, gets data etc
//after it's all done, call your template files
include 'top.php';
include 'profiles.tpl.php';
include 'bottom.php';
there can be some variations, but the main idea would be the same: separate your data manipulation from data presentation.
From the header documentation:
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. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
The headers are being sent before your call to header() due to output from the script. You just need to track down where the output is coming from.
I see it that you have two options
1) You try to ensure that your headers are not set until after you have executed your code. Your headers being set before you have even determined what you are sending back to the user suggests your code is a little messy, or you are constrained in some way.
2) You can use your javascript solution. However, I would consider this as a hack, rather than an appropriate solution. Try to figure out the answer to why you can't use approach 1.
EDIT: A code example added
Your code should look something like this
<?php
// perform logic to determine if you need to do the redirect or not.
// if you do need to redirect, set the following
$iNeedToRedirect = true;
// if you do not need to redirect, set the following
$iNeedToRedirect = false;
if ($iNeedToRedirect) {
header("Location: profil.php?id=" . $show["id"]");
die();
}
// if code gets here, carry on as normal
include("dbc.php");
include("top.php");
... etc etc etc
?>
How can I redirect in PHP with this setup below without getting header output errors, I understand that nothing can be printed to the browser before a header is set, I am looking for a solution, not an explanation of why it happens please.
<?PHP
// include header
include ('header.inc.php');
// In my body section file if this is a page that requires a user be logged in then
// I run a function validlogin($url-of-page-we-are-on); inside of that file
//the function is below, it outputs a redirect to login page if not logged in
// include body of page we want
include ('SOME-FILE-HERE.php');
// include footer
include ('footer.inc.php');
// here is the function that is in the body pages, it is only called on a page that we require a logged in user so there are hundreds of pages that do have this and a bunch that don't, it's on a page to page basis
function validlogin($url) {
if ($_SESSION['auto_id'] == '') {
$msg = 'Please login';
$_SESSION['sess_login_msg'] = $msg;
$_SESSION['backurl'] = $url;
$temp = '';
header("Location: /");
exit();
}
}
?>
I would like to user php's header function and not a meta or javascript redirect
Also maintainning a list of pages that require login or not is not an option here if possible
Use ob_start() in the first line even befor the include. so you can set headers anytime.
Can't you just do this:
<?php
validlogin($url); // call the function here
include ('header.inc.php');
include ('SOME-FILE-HERE.php');
include ('footer.inc.php');
?>
Or, put the include files in every one of the "SOME-FILE-HERE"-type files, if that's possible, so you end up with:
<?php
validlogin($url); // call the function here
include ('header.inc.php');
?>
<h1>Page heading</h1>
...page content etc...
<?php
include ('footer.inc.php');
?>
use { echo '<META HTTP-EQUIV="Refresh" Content="0; URL=process.php">';}
As long as you have no script output before the header() function you should be fine. Check there are no echo's or whitespace. Also putting ob_start() at the beginning can help. sometimes there is invisible whitespace - changing the format of your document to ANSI or Unicode may help!
As a note (although I think you already know) header does not terminate the script so the exit() (which you have) is a definite requirement.
Does the footer.inc.php and SOME-FILE-HERE.php write to the response stream immediately? Because if so, this won't work as you will have already written something before you sent the headers.
You need to buffer the ouput so that the HTTP header is not send on the first output. You can either buffer any ouput implicitly by enabling ouput_buffering or explicitly by calling ob_start. But the latter has to be called before the first output, so ideally in the first line of the script that’s initially called.
As already mentioned by the others use ob_start() or the output_buffer-setting to buffer the output. Apart from that it's from my point of view not a good practice to output content in the middle of functional code but this is a another topic.
You can find more information at Google or in this Article about Output Buffering in PHP.