Php session register deprecated

Php session register deprecated

Здравствуйте!Хочу сделать админку для сайта.Все сделал,но вылезает ошибка:
Deprecated: Function session_register() is deprecated in Z:\home\localhost\www\fl\start.php on line 25

$hostname = «localhost» ;
$username = «alex» ;
$password = «12345» ;
$dbName = «mydb» ;
$db = mysql_connect ( $hostname , $username , $password ) or die ( «Не могу создать соединение» );

mysql_select_db ( $dbName ) or die ( mysql_error ());
$result = mysql_query ( «SELECT * FROM user» );
$query = «SELECT log,pas FROM user WHERE 1» ;
$res = mysql_query ( $query ); $x = 0 ;
while( $arr = mysql_fetch_array ( $res ))
if (( $_POST [ «log» ]== $arr [ «log» ])&&( $_POST [ «pas» ]== $arr [ «pas» ]))
$x = 1 ;
>
>
if ( $x != 1 )
else
< session_start ();
session_register ( «a» );
$_SESSION [ ‘a’ ]= «123» ;
include( «head.php» ); $nbsp ;
include( «bottom.php» );
>
?>

В этой самой строке надо использовать не session_register, а регай сессия с помощью массива $_SESION[]. Выдаётся предупреждение, так как эта функция уже устарела. Советую в этой связи отключить режим register_globals, она может служить причиной взлома вашего сайта, не сейчас конечно, но в будущем всё возможно.

Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Function session_register bars2076 PHP 2 15.05.2011 12:41
Сессии (session_register) Викдон PHP 4 14.05.2011 18:28
Symbol «Resident» is deprecated _-Re@l-_ Общие вопросы Delphi 10 12.08.2010 16:22
сессии — session_register() is deprecated Dimarik PHP 4 11.07.2010 18:24
Deprecated: Function session_register() is deprecated Rusl92 PHP 4 05.07.2010 13:15
Читайте также:  Effective python 90 specific ways to write python better second edition brett slatkin

Источник

session_register

session_register() accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session.

You can also create a session variable by simply setting the appropriate member of the $_SESSION or $HTTP_SESSION_VARS (PHP < 4.1.0) array.

// 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.» ;
?>

If session_start() was not called before this function is called, an implicit call to session_start() with no parameters will be made. $_SESSION does not mimic this behavior and requires session_start() before use.

Данная функция была помечена УСТАРЕВШЕЙ начиная с версии PHP 5.3.0 и была УДАЛЕНА в версии PHP 5.4.0.

Список параметров

A string holding the name of a variable or an array consisting of variable names or other arrays.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примечания

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register() , it will not work in environments where the PHP directive register_globals is disabled.

Замечание: register_globals: важное замечание

Начиная с PHP 4.2.0, значением директивы PHP register_globals по умолчанию является off (выключено). Сообщество PHP рекомендует не полагаться на эту директиву, а использовать вместо этого иные средства, такие как superglobals.

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

If you are using $_SESSION (or $HTTP_SESSION_VARS ), do not use session_register() , session_is_registered() , and session_unregister() .

Замечание:

It is currently impossible to register resource variables in a session. For example, you cannot create a connection to a database and store the connection id as a session variable and expect the connection to still be valid the next time the session is restored. PHP functions that return a resource are identified by having a return type of resource in their function definition. A list of functions that return resources are available in the resource types appendix.

If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, assign values to $_SESSION . For example: $_SESSION[‘var’] = ‘ABC’;

Смотрите также

  • session_is_registered() — Определяет, зарегистрирована ли глобальная переменная в сессии
  • session_unregister() — Unregister a global variable from the current session
  • $_SESSION

Источник

Fix SESSION_REGISTER , SESSION_UNREGISTER Deprecated for PHP 5.3

You have to clear $_SESSION array. Even better, is there an alternative that achieves the same function that I require, if unset() isn’t the correct one Solution 1: You can unset specific session vars using , but mind this part from the manual: (from: http://php.net/manual/en/function.session-unset.php )

Fix SESSION_REGISTER , SESSION_UNREGISTER Deprecated for PHP 5.3

I change my Code For Update To PHP 5.3 . For Fix This, i Remove SESSION_REGISTER() From My Code And Change SESSION_UNREGISTER() To unset() ; this worked for me. this is true way ? This is a sure way ? PHP Manual ( SESSION_REGISTER and SESSION_UNREGISTER )

SESSION_REGISTER("UID");$_SESSION[UID]=$res->fields[uid]; SESSION_REGISTER("EMAIL");$_SESSION[EMAIL]=$res->fields[email]; SESSION_REGISTER("USERNAME");$_SESSION[USERNAME]=$res->fields[username]; SESSION_REGISTER("IS_ACTIVE");$_SESSION[IS_ACTIVE]=$res->fields[is_active]; 
$_SESSION[UID]=$res->fields[uid]; $_SESSION[EMAIL]=$res->fields[email]; $_SESSION[USERNAME]=$res->fields[username]; $_SESSION[IS_ACTIVE]=$res->fields[is_active]; 

Old Code (SESSION_UNREGISTER) :

$_SESSION["UID"] = ''; session_unregister("UID"); $_SESSION["EMAIL"] = ''; session_unregister("EMAIL"); $_SESSION["USERNAME"] = ''; session_unregister("USERNAME"); 
unset($_SESSION["UID"]); unset($_SESSION["EMAIL"]); unset($_SESSION["USERNAME"]); session_destroy(); 

That’s will work fine, just make sure you have your array keys quoted:

$_SESSION['UID']=$res->fields['uid']; $_SESSION['EMAIL']=$res->fields['email']; $_SESSION['USERNAME']=$res->fields['username']; $_SESSION['IS_ACTIVE']=$res->fields['is_active']; 

Php — Call to undefined function session_register(), Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

Replacing session_unregister with unset()

I’m moving a legacy system which I didn’t create from one server (php 5.2) to a newer one (php 5.3) and a lot of the system uses session_unregister. I appreciate this is now deprecated in 5.3 so should I go ahead and replace all cases with unset($_session[‘myVar’]) or will this cause something to break?

Even better, is there an alternative that achieves the same function that I require, if unset() isn’t the correct one

You can unset specific session vars using unset($_SESSION[‘yourvar’]); , but mind this part from the manual:

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. http://php.net/manual/en/function.session-unregister.php

But if you need to «Free all session variables». Use

Php — Function session_register() is deprecated, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

PHP — Does session_unset unregister $_SESSION vars?

Does session_unset() unregister all the $_SESSION vars, or do you have to manually clear each variable registered into the $_SESSION array with unset() ?

I’m confused about this because the PHP documentation says:

Only use session_unset() for older deprecated code that does not use $_SESSION.

If $_SESSION is used, use unset() to unregister a session variable

Yes it removes all sessions vars.

session_unset — Free all session variables

To remove all session vars, you can also use:

Sometimes you might have problems even if using both session_unset and session_destroy. You have to clear $_SESSION array.

session_unset(); session_destroy(); $_SESSION = array(); 

Replacing session_register() in PHP, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

How to avoid deprecation warning by replacing session_unregister with $SESSION[] after upgrading to PHP 5.3?

I just installed PHP 5.3 and am weeding out consequent » deprecated » warnings.

It says session_unregister() is deprecated in:

session_unregister($serverWideUniqueIdCode); 

and the replacement seems to be $_SESSION[].

So what would be the syntax with $_SESSION[] to express the same thing?

Quoting the doc (take a look at that page, it says quite some interesting stuff 😉 ) :

session_unregister() unregisters the global variable named name from the current session.

To remove an entry from an array, you can use unset . So, instead of

Which, in your case, I guess, means :

unset($_SESSION[$serverWideUniqueIdCode]); 

Still, you probably don’t want to call unset on the whole $_SESSION variable. Quoting the doc a second time :

Note: If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use unset() to unregister a session variable. Do not unset() $_SESSION itself as this will disable the special function of the $_SESSION superglobal.

PHP — session_unset() Function, Sessions or session handling is a way to make the data available across various pages of a web application. The session_unset() function releases all the …

Источник

Php session register deprecated

Всем привет. Мучаюсь 8ой час подряд. Суть такова: нужно настроить просто скрипт на веб сервер для управления пользователями. Скачал скрипт, поставил на денвер.
Суть проблемы: Скрипт походу старый, вылетает ошибка:
Deprecated: Function session_register() is deprecated in Z:\home\localhost\www\2\config. php on line 71
Нагуглил, оказалось функция стара, ее не используют. Заменил
session_register(«login»);
на
$_SESSION[‘login’]=$login;
Отлично, получяилось. В базе при регистрации пользователи добавляются.
Однако, следующий скрипт который проверяет на данный момент под каким пользователем мы зарегестрированы перестает работать..Если вводить неправильным логин/пасс — он выдает ошибку. Если правильные — вообще никаких реакций. Тоесть такое ощущение, что он сессию никуда не передает дальше. Огромная просьба помогите пожалуйста переписать скриптик, чтобы он работал без ошибок, и если не сложно можете сделать так чтобы пароли хранились в md5?
Скрипт можно взять здесь sendspace.com/file/rjqwhd
Заранее благодарю.

switch($status) <
case «yes»:
if(!$_SESSION[‘loggedIn’])<
//143 echo «123»;
header(«Location: login. php «);
exit;
>
break;

case «no»:
if($_SESSION[‘loggedIn’]) header(«Location: members. php ?».session_name().»=».session_id());
>
break;
>

Добавил сюда 123. Действительно вылазит 123 с ошибкой:
Warning: Cannot modify header information — headers already sent by (output started at Z:\home\localhost\www\3\functions. php :143) in Z:\home\localhost\www\3\functions. php on line 144

Нужно добвить это во все скрипты к которым происходит обращение через браузер и в которых используется сессионная переменная.

kirik, добавил session_start(); во все скрипты. НЕ помогло, хотя думал, что нужно добавить только в 1. Потому что его все инклудят потом. Я в пхп полный ноль, во вторник диплом защищать. Если не затруднит, не мог бы помочь немного с результатом?
P.s. покопался насчет header’a у меня почти везде html код, вконце скрипта. Пробелов нету..ругается на саму строку со словом header..

Вся фишка в том, что ДО замены session_register на $_SESSION, в принципе сессии работали кое-как. Но вылетали ошибки. А сейчас ошибок нету, а сессии не работают

// sessio_register экранируем, так как на него может ругаться
@session_register( 'loggedIn' );

// Заполняем сесионную переменную
$_SESSION['loggedIn'] = true;

Источник

Оцените статью