简体   繁体   中英

How do i set another variable in PHP

hope you are fine.

Im currently having a (bad code;P) PHP Script that let me fetch the user input from the URL. Its been used internal, so we are not looking for old or outdated commands;P.

<?php

$user = $_GET['user'];

$gesamt = file_get_contents("bier_$user.txt");

if (in_array($_GET['user'], ['administrator1', 'administrator2'])) {
    echo "$user: Biere insgesamt: $gesamt"; die;
} else {
    echo "Keine Berechtigung, Junge."; die;
    die; 
}

My Question is: If i use script.php?user=administrator1 in the URL, can this be changed within the Script to "Alexander" instead of "administrator1"?

Something like (i dont know what function needs to be used here)

administrator1 = Alexander administrator2 = Thomas

That's be great! $user should be the name instead of admin1 or admin2

Thanks!

Yes, this is trivial. Your goal is simply to take one value, and fetch another related value based on the first value. Applications and code do this all day long, every day.

In this case you could use an if statement, a switch statement or perhaps an associative array which acts like a dictionary to map from one value to the other. Or if this information is already associated together in a database (eg in a table of user records), you could look it up in there. There are multiple ways you could do it.

Here are two very simple examples, the first using if statements (just to show how trivial it can be), and the second (less repetitive / tedious one) using an associative array. Obviously this approach requires you to know all the possible values in advance when writing the code, which is why using a database (even just a JSON file would do as a basic data source) would be more flexible, but this will serve to give you the general concept:

Example 1:

$user = $_GET['user'];
$username = null;

if ($user == "administrator1") $username = "Alexander";
else if ($user == "administrator2") $username = "Thomas";

Example 2:

$userList = [
  "adminstrator1" => "Alexander",
  "administrator2" => "Thomas"
];

$user = $_GET["user"];
$username = $userList[$user];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM