The first time a page is accessed, PHP doesn't yet know if the browser is accepting cookies or not, so after session_start() is called, SID will be non-empty, and the PHPSESSID gets inserted in all link URLs on that page that are properly using SID.
This has the consequence that if, for example, a search engine bot hits your home page first, all links that it sees on your home page will have the ugly PHPSESSID=... in them.
This appears to be the default behavior. A work-around is to turn on session.use_only_cookies, but then you lose session data for anyone who has their cookies turned off.
세션 ID 전달하기
세션 id를 전달하는 두가지 방법이 있습니다:
- 쿠키
- URL 인수
세션 모듈은 두 방법을 모두 지원합니다. 쿠키가 최적이지만, 항상 사용할 수는 없으므로 다른 방법을 제공합니다. 두번째 방법은 세션 id를 직접 URL에 덧붙이는 것입니다.
PHP는 링크를 투명하게 변경할 수 있습니다. PHP 4.2.0 이후를 사용하지 않는다면, PHP를 빌드할 때 수동으로 활성화해야 합니다. 유닉스에서, configure 시에 --enable-trans-sid를 넘겨야 합니다. 이 빌드 옵션으로 session.use_trans_sid 실행시 옵션이 활성화되고, 상대 URI는 자동적으로 세션 id를 가지도록 변경됩니다.
Note:
arg_separator.output php.ini 지시어로 인수 구분자를 변경할 수 있습니다. 완전한 XHTML 호환을 위해서는, &를 지정하십시오.
다른 방법으로는, 세션 시작시에 정의되는 SID 상수를 사용할 수 있습니다. 클라이언트가 적합한 세션 쿠키를 전송하지 않는다면, session_name=session_id 형식을 가집니다. 그렇지 않으면, 빈 문자열입니다. 그러므로, 조건에 상관 없이 항상 URL에 붙일 수 있습니다.
다음 예제는 어떻게 변수를 등록하고, SID를 사용하여 다른 페이지에 어떻게 연결하는지 보여줍니다.
Example #1 한 사용자의 히트 수 세기
<?php
session_start();
if (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
?>
<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
</p>
<p>
To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click
here</a>.
</p>
SID를 출력할 때 XSS 관련 공격을 방지하기 위하여 htmlspecialchars()를 사용합니다.
위처럼 SID를 출력하면, PHP 컴파일 시에 --enable-trans-sid를 사용할 필요가 없습니다.
Note:
외부 사이트를 지정할 수 있는 절대 URL에 대해서는 SID를 붙이지 마십시오. SID가 다른 서버로 유출되어 보안 위험이 생깁니다.
The previous user is correct, but you can get around this by starting your sessions like this:
session_start($mysession);
Or you can set up an if statement that determines if $mysession is set and whatnot...
When you generate URLs yourself using the SID variable, it must come first in the URL parameter list. For example, if SID expands to "mysession=123" then this does NOT work:
file.php?var1=value&mysession=123
The SID must come first:
file.php?mysession=123&var1=value
If the SID does not come first then session_start() does not recognise it and it creates a new session instead of loading the old one.
