我正在尝试将PHP输出的值捕获到会话或cookie中,以便我可以在其他页面中调用它。请参阅下面的示例
会话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>
我现在想要获取第2页中的会话值。
会话使page2.php
<?php
session_start();
echo $_SESSION['filepath'].": ".$_SESSION['nwidth']."x".$_SESSION['nheight'];
session_write_close();
?>
问题是page1.php没有生成会话。我尝试使用cookie做同样的事情,我也没有运气。
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();
?>
我现在想要获取第2页中的cookie值。
<?php
ob_start();
session_start();
echo $_COOKIE['test_cookie1'].": ".$_COOKIE['test_cookie2']."x".$_COOKIE['test_cookie3'];
session_write_close();
ob_end_clean();
?>
未生成Cookie且未保存该值。有人能告诉我我做错了什么吗?代码看起来不错,应该保存高度/宽度和文件名的值/输出。另外,如果在PHP中无法做到这一点,我是否应该使用Ajax来保存值?如果有,有人可以指出我正确的方向吗?
提前感谢大家的帮助!
答案 0 :(得分:0)
测试一下,如果它没有在那里工作,你的php安装或配置有问题。单击刷新时,会话值应增加+1
<?php
session_start();
if (isset($_SESSION['test']))
{
$_SESSION['test'] = $_SESSION['test'] + 1;
}
else
{
$_SESSION['test'] = 1;
}
echo 'Session value = '.$_SESSION['test'].'<br /><a href="">Refresh</a>';
?>