0

I'm creating an array for user levels and want to make them secure by adding a secret 10 digit string to the end of each of the user levels in the array UserLevels. I'm using the code below but I can't seem to add a string to an array when using the PHP term define.

My code is below:

//Change the 10 digits of the $secret definition to a randomised string
$secret = '0000000000';

define('UserLevels', array(
    'Owner'.$secret,
    'Admin'.$secret,
    'Staff'.$secret
));

I was going to make it hash / check the user levels to make them more secure then use something to check the hash later in each page.

1
  • Check this answer on a similar question posted today. Commented Jul 7, 2017 at 18:15

2 Answers 2

2

Check your PHP version.

The syntax you're using for defining an array constant should only work in PHP 7.

// Works as of PHP 5.6.0
const ANIMALS = array('dog', 'cat', 'bird');
echo ANIMALS[1]; // outputs "cat"

http://php.net/manual/en/language.constants.syntax.php

You can serialize the array to store the constant as a string then use unserialize to return it to an array when you need to access the values.

<?php

//Change the 10 digits of the $secret definition to a randomised string
$secret = '0000000000';

$user_levels = array(
    'Owner'.$secret,
    'Admin'.$secret,
    'Staff'.$secret
);

define('UserLevels', serialize($user_levels));
var_dump(UserLevels);
var_dump(unserialize(UserLevels));

https://eval.in/829457

Sign up to request clarification or add additional context in comments.

5 Comments

You beat me too it.
@Ryan Tuosto Oh okay. Do you know a work around then, using lower PHP versions ?
@BenWilson see updated answer
@RyanTuosto Oh nice! Do you know how I could call a certain user level using this ?
$user_levels = unserialize(UserLevels); $owner = $user_levels[0]; You might want to make it an associative array to begin with though so you could call something like $user_levels['owner'] instead.
0

If you dont use PHP 7

define('ARRAY_EXAMPLE', serialize(array(1, 2, 3, 4, 5)));

unserialize(ARRAY_EXAMPLE);

3 Comments

Thank you but can you explain what this actually is doing.
It's turning the array into a string that can be parsed back into an array later: eval.in/829456
@BenWilson Look Ryan examples

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.