Bear with me. Over the years I've begun to understand that I'm terrible at explaining myself.
I have a site with a page full of Spotify download links. On their first visit, people need to fill out a contact form to capture their email before being able to download. After that, they can download as many playlists as they want, forever.
When they click on the link the first time, a popup window opens the form.
After filling it out, the form redirects them to a new URL that sets the cookie (../playlists-for-events/?download=true). It also sets a variable so that the page doesn't need to be reloaded to download.
Now that the cookie is set, the playlists can be downloaded on any visit to the page (../playlists-for-events).
The cookie is setting as it's supposed to, but the PHP I've written isn't working.
The cookie
<?php $cookie_name = 'spotify-download';
$cookie_value = 'allow';
$date_of_expiry = time() + (10 * 365 * 24 * 60 * 60);
if(isset($_GET['download']) && $_GET['download'] == 'true'){
setcookie($cookie_name, $cookie_value, $date_of_expiry, '/',null,false,true);
$_COOKIE['spotify-download'] = 'allow';
} ?>
And the PHP that basically says "if the cookie isn't set, open the popup, else, start the download"
<?php if(!isset($_COOKIE['spotify-download'])) { ?>
<script type="text/javascript">function zforms_open_window(...)></script><a></a>
<?php } else { ?>
<?php } ?>
Help?
I've tested your code and it works fine, but the cookie can not be read until it is set. i.e. User redirected to /?download=true to set the cookie, it then needs to reload the page or go somewhere else that can now read the cookie.
<?php
$cookie_name = 'spotify-download';
$cookie_value = 'allow';
$date_of_expiry = time() + (10 * 365 * 24 * 60 * 60);
if( isset( $_GET['download'] ) && $_GET['download'] === 'true' ){
setcookie($cookie_name, $cookie_value, $date_of_expiry);
$_COOKIE[$cookie_name] = $cookie_value;
}
if( isset( $_COOKIE[$cookie_name] ) && $_COOKIE[$cookie_name] === $cookie_value) {
echo "You have access!";
} else {
echo "Access denied.";
}
Related
When I open my website on localhost on chrome or other browser it set cookie until I close my browser. When I close my Chrome or other browser it delete my cookie even I have specified expiry time also. But it not lost on fire-fox, in fire-fox cookie is working properly even after closing browser. Why chrome and other browser delete my cookie after closing browser.
the code I have used :
setcookie( "CookieName", "Cookievalue", time() + 3600, "/");
Hello and Welcome Lucky Jaiswal, Please first off check whether chrome clears all cookies on exit. You can do this by going to settings then to privacy and security and then click on cookies and site data, there will be a toggle button saying clear all cookies and site data on exit please check if it is toggled on if yes please toggle it off and try your code again. If the problem still persists I shall try to give you another solution.
(Edit_2) Try this:
<?php
if ( isset($_COOKIE['test']) ) {
echo 'Cookie exists';
} else {
echo 'Cookie not found';
}
if (isset($_POST['login'])) {
if ( $_POST['name'] /* Add your extra conditions for example $_POST['name'] && $_POST['email'] && $_POST['password'] something like that*/ ) {
print_r($_POST);
session_start();
ob_start();
$name = $_POST['name'] ?? '';
$conn = mysqli_connect("localhost", "root", "", "trial") ;
$query = "SELECT * FROM `trialtable` WHERE `name` = '".mysqli_real_escape_string($conn, $name)."'";
$result = mysqli_query($conn, $query) or die("Error 3");
$row = mysqli_fetch_assoc($result);
if ($name == $row['name']) {
setcookie("test", '"'.$row['id'].'"', time() + 3600, "/");
}
mysqli_close($conn);
}
}
?>
P.S: Tested in Chrome, Microsoft Edge and Firefox!
hi i want to set a cookie on button click but i have a problem with it
this is my first version of code and it is working fine
<?php
$ID = is_numeric($_GET['ID']) ? $_GET['ID'] : 1;
$cookie_name = "favoritepost";
if ( isset($_COOKIE[$cookie_name]) ) {
$kookie = unserialize($_COOKIE[$cookie_name]);
} else {
$kookie = array();
}
if ( ! in_array($ID, $kookie) ) {
$kookie[] = $ID;
}
setcookie($cookie_name, serialize($kookie), time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
then as i said i wanted to change the cookie set as button click so i wrote this code but it is not workinf and it gives me no cookie set what is the problem. thanks
<!doctype html>
<?php
$ID = is_numeric($_GET['ID']) ? $_GET['ID'] : 1;
$cookie_name = "favoritepost";
if ( isset($_COOKIE[$cookie_name]) ) {
$kookie = unserialize($_COOKIE[$cookie_name]);
} else {
$kookie = array();
}
if ( ! in_array($ID, $kookie) ) {
$kookie[] = $ID;
}
?>
<button type="button" onclick="setcookie('<?php echo $cookie_name;?>', '<?php echo serialize($kookie);?>', time() + (86400 * 30), "/")">Click Me!</button>
<html>
You're mixing JS and PHP, and it's a deadly combination. JS is a client-side language where as PHP is a sever side language.
Every thing you write in PHP is executed server and everything your write in JS is executed client side.
First solution is use AJAX calls to connect PHP script with JS. Call AJAX function on click of a button which calls PHP script on server side to save the cookie.
Reference: http://www.w3schools.com/PHP/php_ajax_php.asp
Another solution is perform operations on client side only to save/retrive cookie.
Reference: http://www.w3schools.com/js/js_cookies.asp
Doing it on server-side is preferable as it gives more security then
client side code.
I have a simple website where you need only a password to access the contents. Then there are 3 fields where user inputs data, which are then stored in cookies. In the end - there is a logout script that resets the session and unsets cookies.
Please find the relevant code below:
Login page (index)
<?php
session_start();
$password = '';
$wrongPassword = '';
if (isset($_POST['sub'])) {
$password = $_POST['login_passcode'];
if ($password === 'PASSCODE') {
$_SESSION['login'] = true;
header('LOCATION:/personal.php');
die();
} else {
$wrongPassword = true;
}
}
if (isset($_COOKIE['m_username'])) {
header('LOCATION:/personal.php');
die();
}
?>
The page with contents, where user inputs name, department and start date
<?PHP
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header("Location:/index.php");
die();
}
?>
and the logout script:
<?PHP
session_start();
if (isset($_COOKIE[session_name()])):
setcookie(session_name(), '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_username'])):
setcookie('marriott_username', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_startdate'])):
setcookie('marriott_startdate', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_department'])):
setcookie('m_department', '', time() - 7000000,'/');
endif;
$_SESSION = array();
session_destroy();
header ("Location:/index.php");
die();
?>
jQuery to create cookies below:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Cookies do expire (at least on chrome), however after trying to access website after a few hours or days, I get the error about too many redirections. I believe this might be due to some differences between session expiration time and cookies expiration time (5 days for cookies), but I don't really know where to start fixing these...
Also, on Internet Explorer (IE8) the redirects problem occurs even when I go through logout directly.
Will be grateful for any help,
E.
You are correct in thinking different cookie expirations are behind the too many redirects problem.
If isset($_COOKIE['m_username']) is true in the index page, then you are redirected to the personal page, in which if if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) is also true, it sends you back to the index, therefore creating a loop. This would be caused by the session cookie expiring before the cookies you set.
The $_COOKIE and $_SESSION superglobals refer to two different sets of cookies. One solution is to use just the PHP session and store all your session data in the $_SESSION superglobal.
For example:
$_SESSION['m_username'] = 'whatever_value';
This will however generate an overhead in extra memory usage. If you still want to use your own cookies then just make sure any logic determining redirects is based on the session, not the presence of cookies you set.
For example:
// When logging in
$_SESSION['logged_in'] = true;
// On every page that requires login
if(!$_SESSION['logged_in']) // Redirect
In my PHP project, I want to add a user remember me checkbox so that everybody can choose to stay logged in:
Until now I do my normal log in like:
public function loginUser($psMail, $psPwd, $pnRememberMe = 0) {
// Check credentials and so on
// If mail and password matches
if(CREDENTIALS OKAY) {
$_SESSION["username"] = "foo";
$lnExpire = time() + 3600 * 24 * 60;
setcookie("remember", base64_encode(USERID), $lnExpire);
setcookie("rememberToken", md5(SOMESTUFF), $lnExpire);
}
}
When I log in, I can see the created cookie variables with:
print_r($_COOKIE);
Now I try to leave the site with my logout function:
// Unset the session variables
$_SESSION = array();
// Destroy the session.
session_destroy();
But now, when I am at the landing page, there are also my cookies gone?
Could this be because of my session site settings?
ini_set("session.use_only_cookies", "1");
ini_set("session.use_trans_sid", "0");
php function setcookie has fourth argument path, from documentation "The path on the server in which the cookie will be available on". By default it set path to actual your directory. Try set "/" Then it will be available for all domain. http://php.net/manual/en/function.setcookie.php
Try this code hope it will work for you
if(count($_POST>0) && isset($_POST['checkbox']))
{
setcookie('name',$_POST['uname'],time()+3600);
setcookie('password',$_POST['pw'],time()+3600);
}
elseif(count($_POST)>0)
{
setcookie('name','',time()-3600);
setcookie('password','',time()-3600);
}
if(count($_POST)>0 && $_POST['uname']!="" && $_POST['password']!="")
{
if(isset($_COOKIE['name']) && isset($_COOKIE['password']))
{
echo $_COOKIE['name'];
echo $_COOKIE['password'];
}
your login detail code here.....
My web structure is
Header-of-page
Nav Link || iFrame
Footer
I'm Trying to handle session timeout, when session has timeout I'm trying to redirect page to login page, this works fine(session timeout).
Problem:
When I'm redirecting the page,login page is displayed in iFrame, which is not expected.
How can I redirect to login page(whole window),rather than opeing it in iFrame.
I Tried:
1. using header
2. using javascript(Commented)
<?php session_start();
$timeout = 1; // Set timeout minutes
$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['timeout']))
{
$session_life = time() - $_SESSION['timeout'];
if ($session_life > $timeout)
{
session_destroy();
header("Location: login.php?msg=timeout");
// echo '<script language="javascript">';
// echo 'window.location.replace("login.php");';
// echo '</script>';
}
}
$_SESSION['timeout'] = time();
?>
Please guide me for this issue. Thanks!
Try this: window.top.location.href = "http://www.site.com";
As long as this is on the same domain name.
More here: Redirect parent window from an iframe action
use this one
in script window.parent.location='http://localhost/users/login.php'
or follow this link
https://forums.digitalpoint.com/threads/button-to-navigate-to-a-new-page-but-exit-the-iframe-too.1846291/
hope you will get solution.
create form with target="_parent" and action="login.php"
and submit using $(form).submit();
The problem here is than the iFrame is a another window in the partent window.
So when is begin redirected the iFrame only affect self (Not the parent or partents of the parent).
To don't use javascript we can put a link to login.php wich target the parent.
Goto login.php
_top will target the top window frame.
http://reference.sitepoint.com/html/a/target#target__li5 Read about target attribute set on _top.
The other method is using javascript:
window.top.location.assign("http://www.yoursite.com/login.php"); // Redirect
// window top frame to "http://yoursite.com/login.php"
Please read following links about javascript window documentation:
http://www.w3schools.com/jsref/prop_win_top.asp
http://www.w3schools.com/js/js_window_location.asp
In case yo want a "PHP" code, just use echo
http://www.php.net/manual/en/function.echo.php
I hope this mightly helps.
one of the probably mistakes,
if the encoding of this file is "UTF-8" it will create 2 hidden characters in the top of the file.
To fix this issue, try to change the encoding to "UTF-8 without BOM"
you can put a exit; after the redirect
<?php session_start();
$timeout = 1; // Set timeout minutes
$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['timeout']))
{
$session_life = time() - $_SESSION['timeout'];
if ($session_life > $timeout)
{
session_destroy();
header("Location: login.php?msg=timeout");
exit(); // LOOK AT THIS LINE
// echo '<script language="javascript">';
// echo 'window.location.replace("login.php");';
// echo '</script>';
}
}
$_SESSION['timeout'] = time();
?>
Try this way. Php redirection works before JS redirection so browser never runs JS.
which that's the only way you can redirect whole window object.
<?php session_start();
$timeout = 1; // Set timeout minutes
$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['timeout']))
{
$session_life = time() - $_SESSION['timeout'];
if ($session_life > $timeout)
{
session_destroy();
// header("Location: login.php?msg=timeout");
echo '<script language="javascript">window.top.location.href = "login.php?msg=timeout";</script>';
}
}
$_SESSION['timeout'] = time();
You would need to break the iframe. Try this..
if(this != top){
top.location.href = this.location.href;
}
OR (with doc reference)
if(this != top){
top.document.location.href = this.document.location.href;
}
Alternatively
this.top.location !== this.location && (this.top.location = this.location);
I am guessing this php being in the file running in the iframe in that case you have to instruct the parent window to redirect to login.
Echo the below code from php so when you page will render in browser, it will instruct the script to reload the page. But for the page not to load the rest of the page issue an exit(0). Your final script should look like below.
<?php session_start();
$timeout = 1; // Set timeout minutes
$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['timeout']))
{
$session_life = time() - $_SESSION['timeout'];
if ($session_life > $timeout)
{
session_destroy();
echo '<script language="javascript">';
//Echo the exact full url to your login page
echo 'window.parent.location="login.php?msg=timeout"';
echo '</script>';
exit(0); // So script won't go further displaying the page
}
}
$_SESSION['timeout'] = time();
?>
Hope that helps.
Check this solution out. I would put it before the header to prevent flickering. This way, your page will be prevented from swallowing itself.
http://usablelayout.com/articles/automatically-break-out-iframe
<script type="text/javascript">
<!--
if (top.location!= self.location) {
top.location = self.location.href
}
//-->
</script>
If you are using the login action on the same page, Header redirection will not work.
you can use simple the window.location.href='url';
For the login , you have to send the login query to new page, from there you can easily redirect easily...
Try this one
php
echo "<script> window.location='forgot.php'</script>";
html
<META HTTP-EQUIV="REFRESH" CONTENT="3;URL=http://google.com">