Numeric values in php session variable

Asked

Viewed 89 times

1

session variables in php only adopt string values or can I pass numeric values to this type of variable? I have a form with login, password and a select option with a numeric value. I can pass the value of this select to a session variable?

1 answer

2

In session you can pass almost everything, ie you can add:

session_start();

$_SESSION['int'] = 1;
$_SESSION['float'] = 0.1;
$_SESSION['string'] = 'str';
$_SESSION['object'] = new FooBar;

Of course in the case of a class only the values will be saved in the session, when trying to access the next page, however if the class exists it will be possible to use as if it had instantiated.

The only that cannot be added is the Closure, if you do this:

session_start();

$_SESSION['closure'] = function () {};

Or this:

session_start();

$foo = array(
    'foo' => 1,
    'baz' => 'str',
    'bar' => function () {}
);

$_SESSION['closure'] = $foo;

You’re gonna make a mistake like:

Fatal error: Uncaught Exception 'Exception' with message 'Serialization of 'Closure' is not allowed' in [no active file]:0 Stack trace: #0 {main} thrown in [no active file] on line 0

About the form

I have a form with login, password and a select option with a numeric value. I can pass the value of this select to a session variable?

Data passed via HTTP will always be "string" when received in PHP, if you want to convert them you can use things like:

  • $x = intval($_POST['...']) or $x = (int) $_POST['...'];,
  • $x = (float) $_POST['...'];

And then record in session

  • An observation would be if using JSON, example json_decode($_POST['json']) will keep the type sent without further conversion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.