我不是编码员,但我正在努力学习。 我有这个代码片段,我期望在resses.txt文件中只输出一次输出,而是将它写入3次。请注意,在尝试此操作之前,我总是在浏览器中清除我的cookie。 (我模拟之前从未访问过我网站的用户)。 你还可以向我解释一下这种行为吗?
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
$ress = $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
} else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
$_SESSION['screen_width'] = $_REQUEST['width'];
$_SESSION['screen_height'] = $_REQUEST['height'];
header('Location: ' . $_SERVER['PHP_SELF']);
} else {
echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
$file = fopen("resses.txt", "a");
$ressescontent = "screen resolution is
$ress
";
fputs ($file, "###############\r\n");
fputs ($file, "$ressescontent\r\n");
fclose ($file);
?>
所以不是这个
###############
screen resolution is
1280x1024
我得到了这个:
###############
screen resolution is
###############
screen resolution is
###############
screen resolution is
1280x1024
答案 0 :(得分:2)
您的文件编写代码超出了if statement
的内容。
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
$ress = $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
$file = fopen("resses.txt", "a");
$ressescontent = "screen resolution is $ress";
fputs ($file, "###############\r\n");
fputs ($file, "$ressescontent\r\n");
fclose ($file);
} else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
$_SESSION['screen_width'] = $_REQUEST['width'];
$_SESSION['screen_height'] = $_REQUEST['height'];
header('Location: ' . $_SERVER['PHP_SELF']);
} else {
echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
?>
答案 1 :(得分:0)
以上所有答案都是正确的。但可能无法帮助您理解原因。
您遇到的问题是每次都会运行整个脚本。所以在第一次传递时,会话中没有任何内容,$_REQUEST
变量为空,因此javascript将触发重定向页面。 php脚本在运行时龋齿,因此文件将被打开并写入,没有高度或宽度信息。
浏览器将执行javascript重定向。让我们通过php脚本进行第二次传递。这次设置了$_REQUEST
变量,但是会话中仍然没有任何内容,所以这次通过会话详细信息将被设置并且标头被发送以重定向页面,但是PHP脚本讽刺运行所以文件将被打开并写入,没有高度或宽度信息。
浏览器将对标题作出反应并再次重定向到该页面。带我们到第三遍。这次$_REQUEST
变量为空,但会话中包含一些数据。因此,然后设置$ress
变量,当文件打开并写入其中时,其中包含正确的数据。
HAL9000的解决方案或Rikesh都是可行的,但我更喜欢Rikesh将文件写入if语句,因为它使代码更容易理解。