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.
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!
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.";
}
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">
Am running the following code to gather some data from my page and store it in my database, however, i need to add some extra functionality to it but i don't seem to be able to do it correctly.
The Code:
// Get Referrer and Page
if (isset($_GET["ref"]))
{
// from javascript
$referer = $_GET["ref"];
$page = ((isset($_SERVER['HTTP_REFERER'])) ? (parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH)) : (''));
}
else
{
// from php
$referer = ((isset($_SERVER['HTTP_REFERER'])) ? ($_SERVER['HTTP_REFERER']) : (''));
$page = $_SERVER['PHP_SELF']; // with include via php
}
// Cleanup
if (basename($page) == basename(__FILE__)) $page = "" ;
This script is storing $page as "/site/index.php or /site/about.php", for example. I kinda want it to store it as "Index or About" without the whole /site/ and .php part.
Thanks in advance
Use pathinfo(), for example:
<?php
$page = "/site/index.php";
$page_info = pathinfo($page);
$page_name = $page_info['filename'];
echo $page_name; //output: index
?>
Hello i got an issue with the code I posted here (it's a very reduced version, thus many html stuff are omitted for clarity).
The goal is: it checks if the cookie is present and is filled it.
If the global vairable $_POST is empty, it checks if the cookie is present or is for some reason empty. In case the cookie doesn't exist or it is empty; it creates one.
Then show the content before the HTML form
After the submit of the form is clicked, the page recall itself and of course the $_POST is filled in. Thus the second half of the code, reads and shows the cookie's content.
In the reality when I call the page, the cookie is created (I checked with my browser) but the first reading is NOT shown!
if I click on submit, I read the cookie's content OR if I refresh the page with F5 it shows it.
But not when I load the page the "First" time.
Please could you help me to find where I make the mistake?
if (!$_POST) {
// Create Cookie
if (!isset($_COOKIE["ID"]) || ($_COOKIE["ID"] != true)){
$order_id = time();
$lifetime = 600;
setcookie("ID",$order_id,time()+$lifetime);
}//End IF "create cookie"
...
...
...
$order_id = $_COOKIE["ID"];
echo $pag = <<< FORM
$order_id
<form action="page.php" method="post">
...
...
<input type="submit">
</form>
FORM;
} elseif ($_POST) {
// Read Cookie for Contract
echo $order_id = $_COOKIE["ID"];
echo $order_id_date = date('l jS \of F Y');
...
...
...
setcookie("ID","",-50000);
} // End IF ELSEIF
Cookies are sent by the browser to the server on each request. Because you are still in the same request the cookie hasn't been sent.
That's why further in the same file (in the same request) this doesn't work:
$order_id = $_COOKIE["ID"]; // because the cookie hasn't been sent yet.
It also looks that that isn't necessary because the variable $order_id already contains the order id.
It would be better if you set it up this way.
$order_id = time();
if(isset($_COOKIE['ID']) && !empty($_COOKIE['ID'])) {
$order_id = $_COOKIE['ID'];
} else {
$lifetime = 600;
setcookie('ID', $order_id, time() + $lifetime);
}
Therefore you always set your order id and then replace it with the cookie id if its present.
I found a solution. It's a turn-around.
instead of the cookie like the one I created, i used the session. it works
I would like to report here the code:
session_start();
if (!$_POST) {
if ((!isset($_SESSION['order_id'])) or $_SESSION['order_id'] != true ){
$order_id_time = time(); // Assign variables
$_SESSION['order_id'] = $order_id_time;
}
$order_id_date = date('l jS \of F Y');
$order_id = $_SESSION['order_id'];
...
...
...
echo $pag = <<< FORM
$order_id
<form action="page.php" method="post">
...
...
<input type="submit">
</form>
FORM;
} elseif ($_POST) {
// Read Cookie for Contract
echo $cook = "Order ID: ".$_SESSION["order_id"]."<br /><br />";
...
...
...
session_destroy();
} // End IF ELSEIF