Is it possible to redirect a user to a different page through the use of PHP?
Say the user goes to www.example.com/page.php and I want to redirect them to www.example.com/index.php, how would I do so without the use of a meta refresh? Is it possible?
This could even protect my pages from unauthorized users.
Summary of existing answers plus my own two cents:
1. Basic answer
You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).
header('Location: '.$newURL);
2. Important details
die() or exit()
header("Location: https://example.com/myOtherPage.php");
die();
Why you should use die() or exit(): The Daily WTF
Absolute or relative URL
Since June 2014 both absolute and relative URLs can be used. See RFC 7231 which had replaced the old RFC 2616, where only absolute URLs were allowed.
Status Codes
PHP's "Location"-header still uses the HTTP 302-redirect code, this is a "temporary" redirect and may not be the one you should use. You should consider either 301 (permanent redirect) or 303 (other).
Note: W3C mentions that the 303-header is incompatible with "many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.
3. Documentation
HTTP Headers and the header() function in PHP
What the PHP manual says
What Wikipedia says
What the W3C says
4. Alternatives
You may use the alternative method of http_redirect($url); which needs the PECL package pecl to be installed.
5. Helper Functions
This function doesn't incorporate the 303 status code:
function Redirect($url, $permanent = false)
{
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit();
}
Redirect('https://example.com/', false);
This is more flexible:
function redirect($url, $statusCode = 303)
{
header('Location: ' . $url, true, $statusCode);
die();
}
6. Workaround
As mentioned header() redirects only work before anything is written out. They usually fail if invoked inmidst HTML output. Then you might use a HTML header workaround (not very professional!) like:
<meta http-equiv="refresh" content="0;url=finalpage.html">
Or a JavaScript redirect even.
window.location.replace("https://example.com/");
Use the header() function to send an HTTP Location header:
header('Location: '.$newURL);
Contrary to what some think, die() has nothing to do with redirection. Use it only if you want to redirect instead of normal execution.
File example.php:
<?php
header('Location: static.html');
$fh = fopen('/tmp/track.txt', 'a');
fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
fclose($fh);
?>
Result of three executions:
bart#hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00
Resuming — obligatory die()/exit() is some urban legend that has nothing to do with actual PHP. It has nothing to do with client "respecting" the Location: header. Sending a header does not stop PHP execution, regardless of the client used.
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://www.google.com/', false);
Don't forget to die() / exit() !
Output JavaScript from PHP using echo, which will do the job.
echo '<script type="text/javascript">
window.location = "http://www.google.com/"
</script>';
You can't really do it in PHP unless you buffer the page output and then later check for redirect condition. That might be too much of a hassle. Remember that headers are the first thing that is sent from the page. Most of the redirect is usually required later in the page. For that you have to buffer all the output of the page and check for redirect condition later. At that point you can either redirect page user header() or simply echo the buffered output.
For more about buffering (advantages)
What is output buffering?
1. Without header
here you will not face any problem
<?php echo "<script>location.href='target-page.php';</script>"; ?>
2. Using header function with exit()
<?php
header('Location: target-page.php');
exit();
?>
but if you use header function then some times you will get "warning
like header already send" to resolve that do not echo or print before sending headers or you can simply use die() or exit() after header function.
3. Using header function with ob_start() and ob_end_flush()
<?php
ob_start(); //this should be first line of your page
header('Location: target-page.php');
ob_end_flush(); //this should be last line of your page
?>
Most of these answers are forgetting a very important step!
header("Location: myOtherPage.php");
die();
Leaving that vital second line out might see you end up on The Daily WTF. The problem is that browsers do not have to respect the headers which your page return, so with headers being ignored, the rest of the page will be executed without a redirect.
Use:
<?php header('Location: another-php-file.php'); exit(); ?>
Or if you've already opened PHP tags, use this:
header('Location: another-php-file.php'); exit();
You can also redirect to external pages, e.g.:
header('Location: https://www.google.com'); exit();
Make sure you include exit() or include die().
You can use session variables to control access to pages and authorize valid users as well:
<?php
session_start();
if (!isset( $_SESSION["valid_user"]))
{
header("location:../");
exit();
}
// Page goes here
?>
http://php.net/manual/en/reserved.variables.session.php.
Recently, I got cyber attacks and decided, I needed to know the users trying to access the Admin Panel or reserved part of the web Application.
So, I added a log access for the IP address and user sessions in a text file, because I don't want to bother my database.
Many of these answers are correct, but they assume you have an absolute URL, which may not be the case. If you want to use a relative URL and generate the rest, then you can do something like this...
$url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= '/your-relative/path-goes/here/'; // <-- Your relative path
header('Location: ' . $url, true, 302); // Use either 301 or 302
header( 'Location: http://www.yoursite.com/new_page.html' );
Use the following code:
header("Location: /index.php");
exit(0);
I've already answered this question, but I'll do it again since in the meanwhile I've learnt that there are special cases if you're running in CLI (redirects cannot happen and thus shouldn't exit()) or if your webserver is running PHP as a (F)CGI (it needs a previously set Status header to properly redirect).
function Redirect($url, $code = 302)
{
if (strncmp('cli', PHP_SAPI, 3) !== 0)
{
if (headers_sent() !== true)
{
if (strlen(session_id()) > 0) // If using sessions
{
session_regenerate_id(true); // Avoids session fixation attacks
session_write_close(); // Avoids having sessions lock other requests
}
if (strncmp('cgi', PHP_SAPI, 3) === 0)
{
header(sprintf('Status: %03u', $code), true, $code);
}
header('Location: ' . $url, true, (preg_match('~^30[1237]$~', $code) > 0) ? $code : 302);
}
exit();
}
}
I've also handled the issue of supporting the different HTTP redirection codes (301, 302, 303 and 307), as it was addressed in the comments of my previous answer. Here are the descriptions:
301 - Moved Permanently
302 - Found
303 - See Other
307 - Temporary Redirect (HTTP/1.1)
To redirect the visitor to another page (particularly useful in a conditional loop), simply use the following code:
<?php
header('Location: mypage.php');
?>
In this case, mypage.php is the address of the page to which you would like to redirect the visitors. This address can be absolute and may also include the parameters in this format: mypage.php?param1=val1&m2=val2)
Relative/Absolute Path
When dealing with relative or absolute paths, it is ideal to choose an absolute path from the root of the server (DOCUMENT_ROOT). Use the following format:
<?php
header('Location: /directory/mypage.php');
?>
If ever the target page is on another server, you include the full URL:
<?php
header('Location: http://www.ccm.net/forum/');
?>
HTTP Headers
According to HTTP protocol, HTTP headers must be sent before any type of content. This means that no characters should ever be sent before the header — not even an empty space!
Temporary/Permanent Redirections
By default, the type of redirection presented above is a temporary one. This means that search engines, such as Google Search, will not take the redirection into account when indexing.
If you would like to notify search engines that a page has been permanently moved to another location, use the following code:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: new_address');
?>
For example, this page has the following code:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: /pc/imprimante.php3');
exit();
?>
When you click on the link above, you are automatically redirected to this page. Moreover, it is a permanent redirection (Status: 301 Moved Permanently). So, if you type the first URL into Google, you will automatically be redirected to the second, redirected link.
Interpretation of PHP Code
The PHP code located after the header() will be interpreted by the server, even if the visitor moves to the address specified in the redirection. In most cases, this means that you need a method to follow the header() function of the exit() function in order to decrease the load of the server:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: address');
exit();
?>
header("Location: https://www.example.com/redirect.php");
Direct redirect to this link https://www.example.com/redirect.php
$redirect = "https://www.example.com/redirect.php";
header("Location: $redirect");
First get $redirect value and than redirect to [value] like: https://www.example.com/redirect.php
Use:
<?php
header('Location: redirectpage.php');
header('Location: redirectpage.php');
exit();
echo "<script>location.href='redirectpage.php';</script>";
?>
This is a regular and normal PHP redirect, but you can make a redirecting page with a few seconds wait by the below code:
<?php
header('refresh:5;url=redirectpage.php '); // Note: here 5 means 5 seconds wait for redirect.
?>
Yes, it's possible to use PHP. We will redirect to another page.
Try following code:
<?php
header("Location:./"); // Redirect to index file
header("Location:index.php"); // Redirect to index file
header("Location:example.php");
?>
To redirect in PHP use:
<?php header('Location: URL'); exit; ?>
In the eve of the semantic web, correctness is something to consider. Unfortunately, PHP's "Location"-header still uses the HTTP 302-redirect code, which, strictly, isn't the best one for redirection. The one it should use instead, is the 303 one.
W3C is kind enough to mention that the 303-header is incompatible with "many pre-HTTP/1.1 user agents," which would amount to no browser in current use. So, the 302 is a relic, which shouldn't be used.
...or you could just ignore it, as everyone else...
You can use some JavaScript methods like below
self.location="http://www.example.com/index.php";
window.location.href="http://www.example.com/index.php";
document.location.href = 'http://www.example.com/index.php';
window.location.replace("http://www.example.com/index.php");
Yes, you can use the header() function,
header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();
And also best practice is to call the exit() function right after the header() function to avoid the below code execution.
According to the documentation, header() must be called before any actual output is sent.
Like others here said, sending the location header with:
header( "Location: http://www.mywebsite.com/otherpage.php" );
but you need to do it before you've sent any other output to the browser.
Also, if you're going to use this to block un-authenticated users from certain pages, like you mentioned, keep in mind that some user agents will ignore this and continue on the current page anyway, so you'll need to die() after you send it.
Here are my thoughts:
IMHO, the best way to redirect an incoming request would be by using location headers, which goes
<?php
header("Location: /index.php");
?>
Once this statement is executed, and output sent out, the browser will begin re-directing the user. However, ensure that there hasn't been any output (any echo / var_dump) before sending headers, else it will lead to errors.
Although this is a quick-and-dirty way to achieve what was originally asked, it would eventually turn out to be an SEO disaster, as this kind of redirect is always interpreted as a 301 / 302 redirect, hence search engines will always see your index page as a re-directed page, and not something of a landing page / main page.
Hence it will affect the SEO settings of the website.
The best way to redirect with PHP is the following code...
header("Location: /index.php");
Make sure no code will work after
header("Location: /index.php");
All the code must be executed before the above line.
Suppose,
Case 1:
echo "I am a web developer";
header("Location: /index.php");
It will redirect properly to the location (index.php).
Case 2:
return $something;
header("Location: /index.php");
The above code will not redirect to the location (index.php).
You can try using
header('Location:'.$your_url)
for more info you can refer php official documentation
We can do it in two ways:
When the user comes on https://bskud.com/PINCODE/BIHAR/index.php then redirect to https://bskud.com/PINCODE/BIHAR.php
By the below PHP code
<?php
header("Location: https://bskud.com/PINCODE/BIHAR.php");
exit;
?>
Save the above code in https://bskud.com/PINCODE/BIHAR/index.php
When any condition is true then redirect to another page:
<?php
$myVar = "bskud";
if ($myVar == "bskud") {
?>
<script> window.location.href="https://bskud.com"; </script>
<?php
}
else {
echo "<b>Check the website name again</b>";
}
?>
1. Using header, a built-in PHP function
a) Simple redirect without parameters
<?php
header('Location: index.php');
?>
b) Redirect with GET parameters
<?php
$id = 2;
header("Location: index.php?id=$id&msg=succesfully redirect");
?>
2. Redirect with JavaScript in PHP
a) Simple redirect without parameters
<?php
echo "<script>location.href='index.php';</script>";
?>
b) Redirect with GET parameters
<?php
$id = 2;
echo "<script>location.href='index.php?id=$id&msg=succesfully redirect';</script>";
?>
Using header function for routing
<?php
header('Location: B.php');
exit();
?>
Suppose we want to route from A.php file to B.php than we have to take help of <button> or <a>. Lets see an example
<?php
if(isset($_GET['go_to_page_b'])) {
header('Location: B.php');
exit();
}
?>
<p>I am page A</p>
<button name='go_to_page_b'>Page B</button>
B.php
<p> I am Page B</p>
Use:
<?php
$url = "targetpage"
function redirect$url(){
if (headers_sent()) == false{
echo '<script>window.location.href="' . $url . '";</script>';
}
}
?>
There are multiple ways of doing this, but if you’d prefer php, I’d recommend the use of the header() function.
Basically
$your_target_url = “www.example.com/index.php”;
header(“Location : $your_target_url”);
exit();
If you want to kick it up a notch, it’s best to use it in functions. That way, you are able to add authentications and other checking elemnts in it.
Let’s try with by checking the user’s level.
So, suppose you have stored the user’s authority level in a session called u_auth.
In the function.php
<?php
function authRedirect($get_auth_level,
$required_level,
$if_fail_link = “www.example.com/index.php”){
if ($get_auth_level != $required_level){
header(location : $if_fail_link);
return false;
exit();
}
else{
return true;
}
}
. . .
You’ll then call the function for every page that you want to authenticate.
Like in page.php or any other page.
<?php
// page.php
require “function.php”
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 5
authRedirect($_SESSION[‘u_auth’], 5);
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 4
authRedirect($_SESSION[‘u_auth’], 4);
// Redirects to www.someotherplace.com/somepage.php if the
// user isn’t authentication level 2
authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);
. . .
References;
http://php.net/manual/en/function.header.php
I like the kind of redirection after counting seconds
<?php
header("Refresh: 3;url=https://theweek.com.br/índex.php");
I apologize if my question title is at all confusing, this is my first post and despite reading https://stackoverflow.com/help/on-topic I feel like I may still have some flaws in my question-writing abilities.
TL;DR: JavaScript animation works if I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), but doesn't if I do (and I need to). Any reasons or solutions?
Anyway,
The context:
I have a html form embedded in a php document which is used to upload an image, delete an image, etc.
The main code takes place on ProjectUserProfile.php (and works perfectly), and after the image has been uploaded, I use header("location: ProjectUserProfile.php?UploadSuccessful") to return to the page, and prompt a refresh.
The problem:
If I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), the image will not change, etc, so it is a necessity for me to use it. However, recently I have implemented "slide in notifications" if you will which display success and error messages. These work correctly normally, but fail to appear if I return to the page using header("location: ProjectUserProfile.php?UploadSuccessful").
<?php
// all the uploading etc that works occurs here
header("location: ProjectUserProfile.php?UploadSuccessful");
echo "<script> openMessage('Information','The duplicate files were successfully uploaded!') </script>";
?>
After redirecting to ProjectUserProfile.php?UploadSuccessful, there is failure to acknowledge openMessage, and so nothing happens.
Whereas, had I not used header("location: ProjectUserProfile.php?UploadSuccessful"), the "notification" would slide in and work.
Does anyone have any solutions or suggestions?
Relevant code for the javascript function 'openMessage()' below:
function openMessage(Purpose, DisplayText){
var notificationDiv = document.getElementById("slideinNotification");
if(notificationDiv){
alert("exists");
}
else{
alert("does not exist");
}
document.addEventListener("DOMContentLoaded", function(event){
if(Purpose == "Information"){
document.getElementById("slideInNotification").style.backgroundColor = "#4CAF50";
}
else if(Purpose == "Warning"){
document.getElementById("slideInNotification").style.backgroundColor = "#FF9800";
}
else if(Purpose == "Error"){
document.getElementById("slideInNotification").style.backgroundColor = "#F44336";
}
document.getElementById("notificationMessage").innerHTML = DisplayText;
moveElement();
});
}
<?php
if($filesWereDeleted == true){
$connection = new mysqli("localhost", "root", "root", "project");
$result = $connection -> query("UPDATE UserProfileImage SET UploadStatus = 1 WHERE UserUniqueID = '$userProfileId'");
header("location: ProjectUserProfile.php?DeletionSuccessful");
echo "<script> openMessage('Information','The profile image was successfully deleted!') </script>";
}
?>
<div id = "slideInNotification" class = "slideNotification">
<p id = "notificationMessage" class = "notificationInfo"></p>
×
</div>
First, your UPDATE query exposed to SQL Injection, if you get the id from the user, I hope note, read about prepared statement.
Second, about your problem, you echo the notify script in the same response you send the Location header , so before the the browser even load your JavaScript code it redirect the client to the new page when your notify javascript code not echoed...
If your problem is that user updates it's image and it's doesn't appear due it cached you can use uniqid() in the get query of image src or modify time, more effective
The thing is, once you use header("location: ProjectUserProfile.php?DeletionSuccessful"); you're not supposed to write anything into the output, as the browser will ignore it. That aside, I'm not exactly sure about how a single line of <script> openMessage('Information','The duplicate files were successfully uploaded!') </script> could mean anything to the browser, since that wouldn't constitute an HTML document by itself, unless you're receiving it through AJAX or loading it into an <iframe>; but even then, I doubt mixing control instructions (a redirect) with view markup (the script tag) would be a good idea.
You're going to have to post the confirmation message in ProjectUserProfile.php, so move your script tag there. You can use that ?UploadSuccessful bit as reference for you to know whether to include your script for the message in the document is necessary or not.
I have a page with a header include, and the include needs a phone number to change on it ONLY if the filename of the current page contains a certain word.
Normally, for a change that is not within an include, the below code would work.
<?php if (strpos($_SERVER['REQUEST_URI'],'example-match') !== false)
{
echo '555-555-5555';
}
else
{
echo '1-800-555-5555';
}
?>
However, since the code is in an included file on the page, rather than the original page itself, the server instead is returning the name of that included file.
Example: www.example.com/im-on-this-page.html returns the name of the include the php file is in - www.example.com/header-include.php.
Is there a way to grab the URL of the page the include is "included on", rather than the url of the include, from code that is within the include?
UPDATE:
The file is being included via Javascript, since the page is it being included on is an html file:
<script>
$('#Header').load('/includes/header.php');
</script>
As of your last comment:
Then it is not an include but a GET request to the PHP delivering a JavaScript. And then, the given URL is proper. In order to find out from where the script has been included you may either look for the referer header (which is instable) or pass the current file to the script itself:
<script> $('#Header')
.load('/includes/header.php?from=encodeUriComponent("<?php echo $_SERVER['REQUEST_URI'] ?php>")'); </script>
Within your script, instead of $_SERVER['REQUEST_URI'] then use $_GET['from']
As commentors have mentioned as well. This is incorrect. $_SERVER does not change for the duration of the script (and includes). Including a file will not alter it.
A javascript include, meaning it is actually called by the client by an ajax call, and not included on the server before the page is presented.
(you load a page, and then load another page which you "print" somewhere on the first)
a quick and dirty fix would be to write something along these lines on the first php file
<?php if (strpos($_SERVER['REQUEST_URI'],'example-match') !== false)
{
echo "<script> var phone_number = '555-555-5555';</script>";
}
else
{
echo "<script> var phone_number = '1-800-555-5555';</script>";
}
?>
which will create a variable on the client side, which you then can call from the loaded page as a javascript variable
Before i go on, I'm aware that this question has been asked a couple of times but it doesn't deal with specificity.
I have a functions.php script which contains a couple of functions and i would like to call a specific function when the user clicks on an anchor tag.
I have gone through most of the questions in this manner and i understand that this would be done through javascript and ajax load the page specified with the on-click attribute.
My question is when this happens(page is being loaded) how do I call a specific function out of the functions.php script and if I have required it on the current page where the anchor tag exists will it cause complications?
To be more precise i have a register.php page which does the following; take user data then validate, if validated insert into DB and send a mail to the user to verify his account then redirect to a registration_complete.php page which has the option of resending the link if user didn't receive it. Hence clicking the link will run a specific mail function in the functions.php file.
The Code is written below
register.php
<?php
session_start();
$_SESSION['name'] = hmtspecialchars($_POST['name']);
//validation code goes here
if (isset ($_POST)){ //check that fields are not empty etc...
// insert into db code...
// email the user code...
// redirect to registration_complete.php code..
}
?>
<form method='post' action="">
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type= "submit" value="submit">
</form>
registration_complete.php
<?php
require'functions.php'
session_start();
$Name = $_SESSION['name']
$RegisterationComplete = "Thank you . ' ' . ' $Name' . ' ' . for registering pls click on the link in the email sent to the email address you provided to verify you account. If you didn't recieve the email click on the resend email link below to get on resent to you. Please make sure to check your spam folder if you did not see it in your inbox folder."
?>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
Resend Verification Link
Please not that i have copied the js code from one of the answers related to my question
functions.php
<?php
//connect to db code
// insert into db code
// send verification link code using PHP Mailer function..
?>
So when ajax loads the functions.php page how does javascript call the exact function(PHP Mailer).
I just want to state that i am new to programming i'm only a bit conversant with php. My knowledge of Javascript and Ajax can be said to be negligible. Also want to say a big thank you to all contributors.
Javascript will never call PHP functions, since PHP is running on the server and Javascript is running in the web-browser. The server and the web-browser are assumed to be different machines, the only exception being testing by developers. Therefore, if you have a function in functions.php called foo, Javascript will not be able to call it.
As you have already mentioned in your question, this might involve AJAX, which is surely true, but let's be more exact: when your Javascript code intends to "execute" a PHP function, it needs to trigger a request to the server. Not necessarily with AJAX, as you can trigger form submission, or anchor click as well. The request will reach the server, which will handle it.
Now, since we know that the life cycle is as follows:
Javascript detects that foo has to be executed
Javascript triggers a request to the server
Server is requested
Server handles the request
Server responds
The missing piece in the puzzle is to let the server know that it has to execute foo. To achieve this, the server has to determine somehow whether foo needs to be executed. This can be done with various way, including get params or post params. Next, you need to modify your Javascript code or html structure to let the server know that the function needs to be executed.
You can add a get parameter to the href of the anchor tag, for instance, but in general, you need to let the server know what the intention is and at server-side you need to handle that intention.
Also, you are doing validation on the server. This is ok, but may I advise you to validate the inputs on client-side and prevent posting if the input is invalid, to reduce server load... On server-side, if the post is valid, you need to execute the needed functions.
Also, this part is not exactly correct:
if (isset ($_POST)){
This is not the right approach to check whether this was a post request. You need
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
instead.
It is not important if the Request comes from javascript or a regular server Request (user clicks on link). You need to check the GET or POST parameters and redirect the Request to a specific function.
<?php
if( isset( $_GET['method'] ) ) {
// NOTE: untested and REALY unsecure Code
$method = $_GET['method'];
if( function_exists( $method ) ) {
call_user_func( $method );
}
}
else {
echo '<a id="link" href="?method=foo">klickme</a>';
}
function foo(){
echo 'in method';
}
?>
<div id="answer"><!-- server answer here --></div>
when you now have a link
http://yourSite.com?method=foo
and the function foo gets executed.
Now the JS part you have to check if the user clicks on a link, or sends a form. Then you have to send the request to server using Ajax and handle the result from the Server.
// inject the serverData in DOM
function loadSuccess( e ) {
document.getElementById( 'answer' ).innerHTML = e.target.response;
}
// handle click, open ajax request
function doClick( e ) {
e.preventDefault();
var ajax = new XMLHttpRequest();
ajax.open("GET", e.target.href ,true);
ajax.send();
ajax.addEventListener('load', loadSuccess);
}
var link = document.getElementById( 'link' );
link.addEventListener( 'click', doClick );
i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?