Capturing PHP value in session or cookie - php

I am trying to capture the value of PHP output into a session or cookie so I can call it in other pages. Please see example below
session-page1.php
<?php
session_start();
ob_start();
?>
<!DOCTYPE HTML>
<!--
Strongly Typed 1.1 by HTML5 UP
html5up.net | #n33co
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html lang="en" xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml">
<?php $servurl = basename($_SERVER['REQUEST_URI']); ?>
<?php include_once "includes/ghead.php" ?>
<body itemscope itemtype="http://schema.org/CreativeWork" class="upload">
HEAD AND HEADER HTML CODE GOES HERE
<?php
$fpath="upload/myImage.jpg";
$size = getimagesize("$fpath");
$nheight = $size[1];
$nwidth = $size[0];
// Setting sessions
$_SESSION['filepath'] = $fpath;
$_SESSION['nwidth'] = $nwidth;
$_SESSION['nheight'] = $nheight;
session_write_close();
?>
<header>
<h2><?php echo $fpath; ?></h2>
<br> some html code goes here
<br> <a href='session-page2.php'>go to page 2</a>
</header>
<?php echo $_SESSION['filepath']; ?>
</body>
</html>
I want to now get the session values in page 2.
session-page2.php
<?php
session_start();
echo $_SESSION['filepath'].": ".$_SESSION['nwidth']."x".$_SESSION['nheight'];
session_write_close();
?>
The issue is that page1.php is not generating the session. I tried the same thing using cookies and I am not having any luck either.
cookie-page1.php
<?php
ob_start();
session_start();
$fpath="upload/myImage.jpg";
$size = getimagesize("$fpath");
$nheight = $size[1];
$nwidth = $size[0];
// Setting cookies
$cookie_name = 'test_cookie';
$cookie_value = $fpath;
setcookie($cookie_name, $cookie_value, time() + (3600), '/'); // 1 hour (60 minutes * 60 seconds = 3,600 seconds)
$cookie_name2 = 'test_cookie2';
$cookie_value2 = $nwidth;
setcookie($cookie_name2, $cookie_value2, time() + (3600), '/'); // 1 hour (60 minutes * 60 seconds = 3,600 seconds)
$cookie_name3 = 'test_cookie3';
$cookie_value3 = $nheight;
setcookie($cookie_name3, $cookie_value3, time() + (3600), '/'); // 1 hour (60 minutes * 60 seconds = 3,600 seconds)
session_write_close();
ob_end_clean();
?>
I want to now get the cookie values in page 2.
<?php
ob_start();
session_start();
echo $_COOKIE['test_cookie1'].": ".$_COOKIE['test_cookie2']."x".$_COOKIE['test_cookie3'];
session_write_close();
ob_end_clean();
?>
The cookie is not generated and the value is not saved. Can someone tell me what I am doing wrong? The code looks ok and should save the value/output of height/width and filename. Also, if this is not possible in PHP, should I be using Ajax to save the value? if yes, can someone point me in the right direction?
Thank you all in advance for your help!

Test this one, if it's not working there's something wrong with your php installation or configuration. When you click refresh the session value should increase with +1
<?php
session_start();
if (isset($_SESSION['test']))
{
$_SESSION['test'] = $_SESSION['test'] + 1;
}
else
{
$_SESSION['test'] = 1;
}
echo 'Session value = '.$_SESSION['test'].'<br />Refresh';
?>

Related

PHP - Set cookie and redirect

I am trying to set a cookie and redirect. Using Debian GNU/Linux 6.0 (64 bit) with PHP 5.3.3-7+squeeze19 with Suhosin-Patch (cli) (built: Feb 17 2014 10:10:23) and Apache/2.2.16 (Debian).
For some reason this works:
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
?>
But this does not:
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
header("Location: http://www.example.com");
exit;
?>
Even after several page loads. I've tried adding error reporting to the top of my code, but I don't see any errors when I load the page nor in the Apache log (/var/log/apache2/error.log):
error_reporting(E_ALL);ini_set('display_errors','1');
For some reason whenever I redirect, even using javascript as below, a cookie will not add.
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="1;url=http://www.example.com">
<script type="text/javascript">
window.location.href = "http://www.example.com"
</script>
<title>Page Redirection</title>
</head>
<body>
If you are not redirected, follow <a href='http://www.example.com'>this link</a>!
</body>
</html>
Why does the first example work but not the others?
Use include rather than redirect
This also saves the Browser a round trip HTTP request
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
include('/home/user/public_html/index.html');
exit;
?>
While I prefer include over a redirect header, your cookie should work. I have tested and it works just like it should.
In my test I redirected to another domain. The cookie is set in the domain where the PHP script resides.
setcookie('test', 'test', time() + (86400 * 30), "/");
header("Location: http://www.intel.com");
Works just like it is supposed to:
I was also getting this weirdness but with js redirect. Testing with chrome browser on xp.
The way I solved it was to do the cookie setting with injected js using document.cookie =
?>
<script type="text/javascript">
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;
}
setCookie("foo","<?php echo $bar; ?>",30);
window.location = "<?php echo $destination_page; ?>.php";
</script>
<?php
then the problem went away.
It felt like the redirect was causing the php setcookie to fail for some reason...

How to include Session Timeout in all controllers?

I need a session timeout for my website.
My current code works when I add it in all functions on all my controllers.
Is there a way to write it only once and include it to all of the controllers?
-in config file with URL & Session check or so?
My code which works:
if(isset($_SESSION['timeout']) && $_SESSION['timeout'] + 4 < time()) //4 seconds
{
session_destroy();
echo "<script>
alert('Session Timed Out.');
</script>";
?> <script> window.location ="<?php echo URL;?>"; </script> <?php
}
$_SESSION['timeout'] = time();
The above code works when I add this in all functions on all my controllers.
But I need a single page code.
You need to start the session before you could destroy it
use the following code in your config file
session_start();
if(isset($_SESSION['timeout']) && $_SESSION['timeout'] + 4 < time()) //4 seconds
{
session_destroy();
echo "<script>
alert('Session Timed Out.');
</script>";
?> <script> window.location ="<?php echo URL;?>"; </script> <?php
}
$_SESSION['timeout'] = time();
and delete session_start from your controller files. It should work, I tested it on my localhost
Edit
To exclude login page use the following code
assuming that your login page url contains "login", modify $string as per your login page url
$string = "login";
$url = $_SERVER['REQUEST_URI'];
session_start();
if(isset($_SESSION['timeout']) && $_SESSION['timeout'] + 4 < time() && !strpos($url, $string)) //4 seconds
{
session_destroy();
echo "<script>
alert('Session Timed Out.');
</script>";
?> <script> window.location ="<?php echo URL;?>"; </script> <?php
}
$_SESSION['timeout'] = time();
place this code in common or config php file
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
You can set session parameters with
session_set_cookie_params http://php.net/manual/en/function.session-set-cookie-params.php

Setting a timeout for a session after a user has logged in

I've got a login page that needs to close if a user has been inactive for a certain amount of time. I figured that setting the session variables to cookies would be the best way to do this(If there's a better way or if my way is wrong, please tell me). The problem is that the session is being destroyed and cookies are being unset before the script has run. Should I move the if statement to the bottom of the page? Should I even need the if statement? Am I even doing this right? Thanks in advance.
<?php
require("../includes/header.php");
$expire = time() + 90;
setcookie("User", $_SESSION["user"], $expire);
setcookie("Image", $_SESSION["image"], $expire);
setcookie("Program", $_SESSION["program"], $expire);
setcookie("Email", $_SESSION["email"], $expire);
setcookie("Role", $_SESSION["role"], $expire);
if($expire){
unset($_COOKIE["User"]);
unset($_COOKIE["Image"]);
unset($_COOKIE["Program"]);
unset($_COOKIE["Email"]);
unset($_COOKIE["Role"]);
session_destroy();
echo "Session has expired.";
}
?>
<body>
<div id="page">
<header>
<div id="logo" class="logo_bg"></div>
<div id="fsi_logo" class="logo_bg"></div>
</header>
<div id="main">
<div id="instructor">
<?php
echo "<img id=instructor_image src=" .$_COOKIE["Image"] .">";
echo "<h1>" .$_COOKIE["User"] ."</h1>";
echo "<span><p>" .$_COOKIE["Program"] ."</p> - <h2>" .$_COOKIE["Role"] ."</h2></span>";
echo "" .$_COOKIE["Email"] ."";
?>
</div>
<?php require("../includes/footer.html"); ?>
In your example if($expire) is always true. You don't have to move it to the bottom of the page if you store the expire time in a session. Something like this:
if(!isset($_SESSION["expire"])) {
$_SESSION["expire"] = time() + 90; // This would add 90 seconds though...
// More set logic
} elseif($_SESSION["expire"] < time()) {
// Unset logic
} else {
// Refresh timer
}

PHP Cookie and browser refresh confusion

I have this code here and I noticed when I changed the value to something else. I have to refresh the page not once but twice in order to see the new value.
Is this related to HTTP headers and super globals? or something why do I have to refresh twice to see the new value why is not one refresh? I've tried reading similar questions on other threads but still not clear on this manner as far why? and what's doing. Can someone give me a clear explanation, thank you.
<?php
$name = "test";
$value = "hello";
$expire = time() + (60*60*24*7);
setcookie($name, $value, $expire);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP</title>
</head>
<body>
<?php
$test = isset($_COOKIE["test"]) ? $_COOKIE["test"] : "";
echo $test;
?>
</body>
so If I change the value to say 500 then I have to refresh twice to see the new value on the page.
The answer is here https://stackoverflow.com/a/17085896/2243372 .
Try to refresh your page programmatically. Example:
<?php
if (isset($_COOKIE['test'])) {
echo 'COOKIE = ', $_COOKIE['test'];
} else {
setcookie('test', 'my-cookie-value', strtotime('+1 day'));
if ( ! isset($_GET['setcookie'])) {
header('Refresh: 0; url=?setcookie=done');
} else {
echo 'Your browser does not accept cookies!';
}
}

PHP redirection using header

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">

Categories