session_register

(PHP 4, PHP 5 < 5.4.0)

session_register하나 이상의 전역 변수를 현재 세션에 등록

설명

bool session_register ( mixed $name [, mixed $... ] )

session_register()는 변수명을 가지는 문자열이나 변수명 또는 다른 배열을 포함하는 배열을 가변 길이 인수로 받습니다. 각 이름에 대해서, session_register()는 그 이름을 가지는 전역 변수를 현재 세션에 등록합니다.

$_SESSION이나 $HTTP_SESSION_VARS(PHP < 4.1.0) 배열에 적합한 멤버를 설정해서 세션 변수를 생성할 수 있습니다.

<?php
// Use of session_register() is deprecated
$barney "A big purple dinosaur.";
session_register("barney");

// Use of $_SESSION is preferred, as of PHP 4.1.0
$_SESSION["zim"] = "An invader from another planet.";

// The old way was to use $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "He's got square pants.";
?>

이 함수를 호출하기 전에 session_start()를 호출하지 않으면, 암시적으로 인수 없이 session_start()를 호출합니다. $_SESSION은 이러한 동작을 하지 않으므로, 사용하기 전에 session_start()가 필요합니다.

Warning

이 함수는 PHP 5.3.0부터 배제됩니다. 이 기능에 의존하지 않기를 권합니다.

인수

name

변수명을 가지는 문자열이나 변수명 또는 다른 배열을 포함하는 배열.

...

반환값

성공 시 TRUE를, 실패 시 FALSE를 반환합니다.

주의

Caution

스크립트가 register_globals에 관계 없이 작동하게 하려면, $_SESSION 배열을 사용해야 합니다. $_SESSION 엔트리는 자동적으로 등록됩니다. 스크립트가 session_register()를 사용한다면, PHP 지시어 register_globals가 꺼져 있는 환경에서는 작동하지 않습니다.

Note: register_globals: 중요 경고

PHP 4.2.0부터 PHP 지시어 register_globals의 기본값은 off입니다. PHP 커뮤니티에서는 이 지시어에 의존하지 않는 superglobals 방식의 사용을 권합니다.

Caution

이 함수는 전역 변수를 등록합니다. 세션 변수를 함수 안에서 등록하려면, global 키워드나 $GLOBALS[] 배열을 사용해서 전역으로 만들거나, 아래에 설명된 특수 세션 배열을 사용해야 합니다.

Caution

$_SESSION(또는 $HTTP_SESSION_VARS)을 사용한다면, session_register(), session_is_registered(), session_unregister()를 사용하지 마십시오.

Note:

자원 변수를 세션에 등록할 수 없습니다. 예를 들면, 데이터베이스 접속을 생성해서 접속 id를 세션 변수에 등록한 다음에 세션이 복구되었을 때, 접속은 유효하지 않습니다. 자원을 반환하는 PHP 함수는 함수 정의에 반환형이 resource로 되어 있습니다. 자원을 반환하는 함수 목록이 자원형 부록에 있습니다.

$_SESSION(또는 PHP 4.0.6까지 $HTTP_SESSION_VARS)을 사용한다면, $_SESSION에 값을 할당하십시오. 예: $_SESSION['var'] = 'ABC';

참고

add a note add a note

User Contributed Notes 15 notes

up
18
Ezion oudpapierdoos at gmail dot com
9 years ago
Below is a fix that may be included in older code to make it work with PHP6.
When needed it recreates the functions
- session_register()
- session_is_registered()
- session_unregister()

The functions inside the function fix_session_register() are only available  after fix_session_register() has run.
Therefore in PHP<6 where there already is a session_register() nothing happens.

<?php
// Fix for removed Session functions
function fix_session_register(){
    function
session_register(){
       
$args = func_get_args();
        foreach (
$args as $key){
           
$_SESSION[$key]=$GLOBALS[$key];
        }
    }
    function
session_is_registered($key){
        return isset(
$_SESSION[$key]);
    }
    function
session_unregister($key){
        unset(
$_SESSION[$key]);
    }
}
if (!
function_exists('session_register')) fix_session_register();
?>


[EDIT BY danbrown AT php DOT net: Bugfix provided by "dr3w" on 02-APR-2010: "its [sic] function_exists with an S at the end".]
up
12
rob at akrabat dot com
10 years ago
if you remove session_register() calls and replace with $_SESSION assignments, make sure that it wasn't being used in place of session_start(). If it was, you'll need to add a call to session_start() too, before you assign to $_SESSION.
up
1
pike-php at kw dot nl
2 years ago
There are a few compat functions for session_register here that had me tripped up.

1) when registering a session var, the value of the global you are registering should *not* override an existing session value. that would defeat the purpose of the session. instead the global should be refered to the sessions value.

2) the global should become a reference to the sessions value, so that when you change the globals value later, the session variable should change too.

This is what I'm using now

<?php
if (!function_exists('session_register')) {
     function
session_register($name){
        global $
$name;
        if (!isset(
$_SESSION[$name])) {
           
$_SESSION[$name] = $$name;
          }
          $
$name = &$_SESSION[$name];
      }
    }
?>
up
2
dee dot earley at icode dot co dot uk
3 years ago
Something that hasn't really been touch on when migrating old code, is that changes to variables made AFTER the session_register() call are still included in the session state.
A lot of the implementations above only add the entry to $_SESSION[] at the point it's called.
If the old code relies on this behaviour, you will either need to have code called on exit to assign back to $_SESSION, or replace it in entirety with $_SESSION usage. With over 1000 uses of the session_ functions, this is a bit daunting!
up
1
david dot jufer at kirchenweb dot ch
3 years ago
This code replaces the removed function "session_register" for PHP >= 5.4.0
"session_start()" must be called before.

<?php

function session_register($name){
    if(isset(
$GLOBALS[$name])) $_SESSION[$name] = $GLOBALS[$name];
   
$GLOBALS[$name] = &$_SESSION[$name];
}

?>
up
1
Scarab
10 years ago
If you want to store an  object into the session, you have to check up that object can be serialized at all.
For example, if your object contains aggregated PDO object (which can't be serialized), you will get an error and no data would be stored.
up
1
david dot demri at gmail dot com
10 years ago
If you have an old code with a lot of call to the function session_register(), and you would like to make it compatible with PHP5 or PHP6, instead of rewriting all your code by replacing this function by $_SESSION['var']="val"; you could use the function set_session_vars(), that is used exactly the same way than session_register() (but there is no implicit call to session_start() ).

<?php
function set_session_vars() {
   
$nb_args=func_num_args();
   
$arg_list=func_get_args();
    for(
$i=0;$i<$nb_args;$i++) {
        global $
$arg_list[$i];
       
$_SESSION[$arg_list[$i]] = $$arg_list[$i];
    }
}
?>
up
0
mikej
15 years ago
I've noticed that if you try to assign a value to a session variable with a numeric name, the variable will not exist in future sessions.
For example, if you do something like:
session_start();
$_SESSION['14'] = "blah";
print_r($_SESSION);

It'll display:
Array ( [14] => "blah" )

But if on another page (with same session) you try
session_start();
print_r($_SESSION);

$_SESSION[14] will no longer exist.

Maybe everyone else already knows this, but I didn't realize it until messing around with a broken script for quite a while.
up
-2
yarco dot w at gmail dot com
9 years ago
You *MUST* notice that

session_register($var)

*IS NOT*

$_SESSION[$var] = $$var;

it is

if (!isset($_SESSION[$var]))
  $_SESSION[$var] = $$var;

when migrating from old style code.
up
-3
tecnico at overant dot com
6 years ago
If you have many websites with these functions in the source code (like me) you can include the following functions in some kind of include.php that you have:

function session_register($session)
{
  //
}

function session_unregister($session)
{
  unset($_SESSION[$session]);
}

In this way the PHP interpreter detects the functions and do not return the error, and the maintenance work is minimized.
up
-3
baldanders
15 years ago
If you are using sessions and use session_register()  to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This basically means that these objects can show up on any of your pages once they become part of your session.
up
-3
klein at sup4u dot de
8 years ago
in addition to function set_session_vars instead of replacing all $var with $_SESSION['var'],
you could get all set session-vars in prevoius scripts with this function

<?php
function get_session_vars() {
   
$nb_args=func_num_args();
   
$arg_list=func_get_args();
    for(
$i=0;$i<$nb_args;$i++) {
        global $
$arg_list[$i] = $_SESSION[$arg_list[$i]];
    }
}
?>
up
-3
martijn at brothersinart dot net
13 years ago
Please note that if you use a "|" sign in a variable name your entire session will be cleared, so the example below will clear out all the contents of your session.

<?php
session_start
();
$_SESSION["foo|bar"] = "foo";
?>

It took me quite some time finding out why my session data kept disappearing. According to this bugreport this behaviour is intended.
http://bugs.php.net/bug.php?id=33786
up
-5
guideng at unlv dot nevada dot edu
13 years ago
Make sure you put session_start() at the beggining of your script.

My sessions kept unsetting and I finally figured out why.

On my script, session_start() has to be said and uses cookies to set the session.

But I was outputting html prior to calling session_start(), which prevented it from succeeding becouse it uses the header function to place the cookies.

Once html has been outputed, session_start() can't use the header function to set cookies, hence session_start() fails and no session can be started.
up
-7
kavih7 at yahoo dot com
10 years ago
For those of you who use this function (session_register that is), even though the manual does specify that this function implicitly calls session_start(), I just wanted to reiterate that fact. It is also important to know that if you ever switch from session_register to using $_SESSION, make sure to call session_start before adding items to the $_SESSION variable, because unlike session_register, no implicit call to session_start is done.

Another reason I explain this is because I ran into a problem in which you can add items to the $_SESSION variable all you want, but if session_start is not called before adding them, they will not actually be saved to the session. Using the same code, though, and replacing the $_SESSION assignments with session_register without calling session_start WILL save that info to the session.

It would be nice to have PHP check for writes to the $_SESSION variable and complain with a warning if session_start hasn't been called.
To Top