php cookie 和会话变量和 ip 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6500654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php cookies and session variables and ip address
提问by clk
I posted a similar question before, but never really got an answer that helped me, so I'm looking to try again. As a disclaimer, I know that a lot of the information in here doesn't follow perfect coding practices, but it is for exercise purposes only. I've tried a million things and nothing seems to be working because I'm not really sure where everything should go! I desperately need some (any!) help so thanks in advance if you can offer anything!
我之前发布过类似的问题,但从未真正得到对我有帮助的答案,所以我想再试一次。作为免责声明,我知道这里的很多信息并不遵循完美的编码实践,但仅用于练习目的。我已经尝试了一百万次,但似乎没有任何效果,因为我不确定一切应该去哪里!我非常需要一些(任何!)帮助,如果您能提供任何帮助,请提前致谢!
I'm trying to create a simple form / page that uses some basic cookie and session stuff to produce some user-specific data. I was moving along good until I came across a few problems that I can't figure out. On my first page everything is good except for I just want the NAME of the browser the user is using. (for example, I want just the simple title: Firefox instead of the whole long version of the browser.) I've seen this be done so I think it's possible, I just don't know how to do it!
我正在尝试创建一个简单的表单/页面,它使用一些基本的 cookie 和会话内容来生成一些特定于用户的数据。我一直很好,直到我遇到了一些我无法弄清楚的问题。在我的第一页上,一切都很好,除了我只想要用户正在使用的浏览器的名称。(例如,我只想要简单的标题:Firefox 而不是浏览器的整个长版。)我已经看到这样做了,所以我认为这是可能的,我只是不知道该怎么做!
My real problems come up right about here, because I'm not exactly sure how to store the IP address, browser info and the current date/time (which I want shown on page 2) as session variables. Tried a few things I found, but I don't think I was doing it right.
我真正的问题就出现在这里,因为我不确定如何将 IP 地址、浏览器信息和当前日期/时间(我想在第 2 页上显示)存储为会话变量。尝试了一些我发现的东西,但我认为我做得不对。
I also worked endlessly on trying to store the username and passwords as two separate cookies each...suggestions? Finally, what do I need to do to have a location header (used to call form_data.php) with output buffering?
我还无休止地尝试将用户名和密码存储为两个单独的 cookie,每个...建议?最后,我需要做什么才能拥有带有输出缓冲的位置标头(用于调用 form_data.php)?
(Not sure this will be that helpful, considering I probably did everything wrong! LOL) This is a totally stripped-down version of my code. Tried to post my cleanest version, even though it doesn't have much info, so that you could easily see what I was trying to do.
(不确定这会不会有帮助,考虑到我可能做错了所有事情!大声笑)这是我代码的完全精简版本。试图发布我最干净的版本,即使它没有太多信息,以便您可以轻松地看到我想要做什么。
main file code:
主文件代码:
<?php
header('Location: form_data.php');
setcookie('username', $_POST['username']);
setcookie('password', $_POST['password']);
//I know this isn't working.
//honestly I just left this in here as to show where I had been
//trying to save the cookie data. Pretty obvious how bad my
//trial and error with this went!
}
?>
<?php
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
echo " By the way, your IP address is: </b>".$_SESSION['ip']."<br />";
echo " You already know this, but the browser you are currently using
to view this page is:<br/>"; //What is the correct function that I should be using here?
echo "<form action=\"form_data.php\" method=\"post\">";
echo "username:<input type=\"text\" name=\"username\" size=\"20\" value=\"\"><br/>";
echo "password:<input type=\"password\" name=\"password\" size=\"20\" value=\"\"><br/>";
echo "<input type=\"submit\" value=\"Submit, please\" />";
echo "<br /><input type=\"hidden\" name=\"submitted\" value=\"true\" />";
?>
form_data.php
form_data.php
<?php
echo "Hello, ".$username;//I'm trying to get the cookie data for the username
echo "Your password is ".$password; //Samething here (want cookie data)
echo "The date and time you entered this form is: ".date("F j, Y")." -- ".date("g:i a");
echo "<br/>Your IP:".$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
echo "<br/>Your broswer:".;//I want full broswer data here...dont know how to do it.
//Overall, was this the way to get the session variables for IP, date/time and browser?
echo "Thank you for filling out this form!";
?>
回答by Michael Berkowski
To get the browser, use the get_browser()
function:
要获取浏览器,请使用以下get_browser()
函数:
$browserinfo = get_browser($_SERVER['HTTP_USER_AGENT']);
$browsername = $browserinfo['browser'];
Your session and cookie storage will never work because you are making a header("Location");
call before attempting to set cookies. You cannot send any output before setting cookies or establishing a session.
您的会话和 cookie 存储将永远无法工作,因为您header("Location");
在尝试设置 cookie 之前进行了调用。在设置 cookie 或建立会话之前,您不能发送任何输出。
Before any output to the screen, call session_start()
;
在任何输出到屏幕之前,调用session_start()
;
// attach to your session (or create if it doesn't exist)
// You must call session_start() on every page where you intend to access or set session vars
// and it must be called before any output (including whitespace at the top)
session_start();
// Store some stuff...
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
// Store user info in session, not cookie
$_SESSION['username'] = $_POST['username'];
// Set a cookie
// Not a super secure token, but better than user/pass in cookies.
// Point here is just to show that it must be done before any output or before the redirection header.
$_SESSION['token'] = sha1(time() . rand() . $_SERVER['SERVER_NAME']);
setcookie('token', $_SESSION['token']);
// In practice, you'd want to store this token in a database with the username so it's persistent.
// Now do the redirection:
// Supposed to be an absolute URL by the HTTP spec
header("Location: http://example.com/form_data.php");
// exit right after the redirection to prevent further processing.
exit();
ADDENDUM after comments
评论后的附录
While you work, make sure PHP displays all errors on screen. Be sure to turn off display_errors
when your code goes onto a live public server.
在您工作时,请确保 PHP 在屏幕上显示所有错误。display_errors
当您的代码进入实时公共服务器时,请务必关闭。
error_reporting(E_ALL);
ini_set('display_errors', 1);
To retrieve values from cookies as you said in your question you didn't know how to do, use the $_COOKIE
superglobal:
要从 cookie 中检索您在问题中所说的值,您不知道该怎么做,请使用$_COOKIE
超全局:
// On the page that sets it...
setcookie('somename', 'somevalue', expiry, domain);
// On the page that retrieves it...
echo $_COOKIE['somename'];
回答by Alfred
> I'm trying to create a simple form /
> page that uses some basic cookie and
> session stuff to produce some
> user-specific data.
Sessions do use cookiesunder the cover(only store session_idinside cookie/set_cookie) and I advice you to use only sessions because cookies can leak information(store all the information inside cookie on that user's computer) which could be dangerous while session uses the server's filesystem/database or whatever you like when you override session_set_save_handler.
会话确实在掩护下使用cookie(仅将session_id存储在 cookie/ set_cookie 中),我建议您仅使用会话,因为 cookie 可能会泄漏信息(将所有信息存储在该用户计算机上的 cookie 中),这在会话使用服务器的时可能是危险的当您覆盖session_set_save_handler时,文件系统/数据库或任何您喜欢的东西。
> On my first page everything is good
> except for I just want the NAME of the
> browser the user is using.
Like Michaelsaid you can use get_browserfor that:
就像迈克尔说的,你可以使用get_browser:
Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.
尝试通过在 browscap.ini 文件中查找浏览器信息来确定用户浏览器的功能。
Like the PHP page says it tries to determine and you should NOTrely on this information for anything important because it can be wrong(you can fool the system, if you like). What I mean is you should not use it to validate/proof something.
像PHP网页说,它试图确定,你应该不依靠此信息任何东西重要,因为它可以是错误的(你可以骗过系统,如果你喜欢)。我的意思是你不应该用它来验证/证明某些东西。
> My real problems come up right about
> here, because I'm not exactly sure how
> to store the IP address, browser info
> and the current date/time (which I
> want shown on page 2) as session
> variables.
More information to retrieve the IP addresscan be read here(proxy-server could mislead you a little bit maybe?). To store that information just store it inside a session by first issuing session_start()
on top of every page(before outputting anything) that wants to use sessions(only those to not set cookies on every page which makes page a little slower) and next store the current time inside a session variable by doing something along the lines of $_SESSION['time'] = date(DATE_RFC822);
. You can read more about retrieving the time at date()page.
可以在此处阅读有关检索 IP 地址的更多信息(代理服务器可能会误导您吗?)。要存储该信息,只需将其存储在会话中,首先session_start()
在想要使用会话的每个页面上(在输出任何内容之前)(只有那些不在每个页面上设置 cookie 使页面变慢)然后存储当前时间在会话变量内通过做一些沿着$_SESSION['time'] = date(DATE_RFC822);
. 您可以阅读有关在date()页面检索时间的更多信息。
So the code on page 1
looks something like:
所以代码page 1
看起来像:
<?php
session_start();
$_SESSION['ip'] = getRealIpAddr(); # no php function => See http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html
$_SESSION['time'] = date(DATE_RFC822);
Then on page 2
you could retrieve this information using something like:
然后,page 2
您可以使用以下内容检索此信息:
<?php
session_start();
echo $_SESSION['ip']; // retrieve IP
> I also worked endlessly on trying to
> store the username and passwords as
> two separate cookies
> each...suggestions?
Don't store them inside a cookie(only using set_cookie and not using sessions to store information) but store them inside a session for extra security. But sessions are also vulnerable to session fixationso after storing something critical inside your session you should regenerate session idand never output/showthat information to the browser/user to prevent any leakage.
不要将它们存储在 cookie 中(仅使用 set_cookie 而不是使用会话来存储信息),而是将它们存储在会话中以获得额外的安全性。但是会话也容易受到会话固定的影响,因此在会话中存储了一些重要的内容后,您应该重新生成会话 ID,并且永远不要向浏览器/用户输出/显示该信息以防止任何泄漏。
> Finally, what do I need to do to have
> a location header (used to call
> form_data.php) with output buffering?
Like Michael said you should be using headerfunction and exitto terminate script after that
就像迈克尔说的那样,您应该使用标头函数并退出以在此之后终止脚本
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
P.S: Never store any really sensitive information like creditcard(use paypal or something) numbers or anything in your own database. I also advice you not to store passwords inside your database but use something like openId(Google's) for example to handle your authentication for extra security.
PS:永远不要在你自己的数据库中存储任何真正敏感的信息,比如信用卡(使用贝宝或其他东西)号码或任何东西。我还建议您不要将密码存储在您的数据库中,而是使用诸如 openId( Google's) 之类的东西来处理您的身份验证以获得额外的安全性。