Reputation: 1038
I created a redirect page in PHP that whenever some one visits that page, it will add a cookie in browser and redirect user to some other page: ex: google.com
.
To do that, I have used javascript to redirect but problem is that when I extract my url it doesn't show google.com
. During extraction it shows the same page's information then I use php header()
for redirection and it shows me the google.com
info.
Now I need help to make this code work with cookie and header.
Code:
<?php
header("location: https://www.google.com");
echo '<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Redirecting...</title>
<script type="text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
createCookie("karachi","testing",100);
</script>
</head>
<body>
</body>
</html>';
?>
Upvotes: 2
Views: 4912
Reputation: 11
<meta http-equiv="refresh" content="5; url=exemple.com">
if you need add a message, you can simply set
<h1>Redirection en cours... Veuillez patienter.</h1>
Upvotes: 0
Reputation: 41885
Instead of setting it on JavaScript. Why not use PHP.
$date_of_expiry = time() + (86400 * 30); // 30 days
if(setcookie('karachi', 'testing', $date_of_expiry)) {
sleep(3); // sleep 3 seconds
header('Location: http://www.google.com/');
}
Or an alternative:
$date_of_expiry = time() + (86400 * 30); // 30 days
if(setcookie('karachi', 'testing', $date_of_expiry)) {
echo '<h1>Redirecting.. Please wait.</h1>';
echo '<meta http-equiv="refresh" content="3;url=http://www.google.com">';
}
On Javascript:
echo '<h1>Redirecting.. Please wait.</h1>';
// echo 'logic javascript';
echo '
<script>
setTimeout(function(){
window.location.href = "http://www.google.com"
}, 3000);
</script>
';
Upvotes: 3
Reputation: 399
Give this a shot. I haven't test it, but it will give you the right idea to start with:
<?php ?>
<script type="text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
createCookie("karachi","testing",100);
</script>
<?php
header("location: https://www.google.com");
?>
I opened and closed the php tag in the beginning because I am assuming this will be in a php file. You may also put your cookie code in a separate .html or .php file and use a include before your header.
include_once 'cookiecode.php';
The trick with headers is getting your task done before presenting any html that displays to the screen. I am pretty certain headers also have to be done before the open tag.
Hope this helps!
Upvotes: 1