Mr_Thomas
Mr_Thomas

Reputation: 869

Using JSON instead of text within a PHP array

I have the following in my PHP to control access to a page:

<?php
    $array = array(
                   'Joe User',
                   'Tom Coffee',
                   'Edith McBurger',
                   'Dan Theman'
    );
    if (in_array($_SESSION['user_name'], $array)) {
    echo '<a href="page2link.php">Link Page</a><br>';
    }

?>

It works fine but I'd rather edit a JSON or other small text file instead of editing the whole page just to alter this list.

How do I write this so the list of names is in an external file and my PHP refers to that file?

Upvotes: 0

Views: 42

Answers (2)

revo
revo

Reputation: 48751

Create a .txt file, write one name on separate lines. Then use file function to open the file. file() creates an array base on each line. Then you can use the rest of your snippet to authenticate.

auth.txt

Joe User
Tom Coffee
Edith McBurger
Dan Theman

auth.php

<?php
    $array = file('auth.txt', FILE_IGNORE_NEW_LINES);
    if (in_array($_SESSION['user_name'], $array))
    {
        echo '<a href="page2link.php">Link Page</a><br>';
    }
?>
  • You can use fopen('auth.txt', "a+") and fwrite() to dynamically write on file later, too.

Upvotes: 0

Idan Magled
Idan Magled

Reputation: 2216

you can write an JSON file and then just json_decode it like this:

your text file:

{

"name":"idan"

}

your php code//

<?php

$string = file_get_contents("/your file location");
$json = json_decode($string,true);

echo  $json['name']; //and it will output the value "idan"

Upvotes: 1

Related Questions