How to load variations of a code based on user?

2019-09-04 08:58发布

问题:

I want to be able to server different variations of a code based on the user. So if USer A signs in i want them to see code/pages pertaining to their preferences.

I know we can do a php/mysql to save paths. But how do i serve the code on the same page. All users have the same page index.php, home.php, profile.php but i want to be able to use the same page to serve those requests by simply show the code that is specifc to them..

回答1:

Just a try...

You can store the preferences loaded from your database or what so ever, in session variables. Next step is to simply print those variables on the page. This way every user gets its own page.

Example:

echo "<p>Welcome ".$_SESSION['username']." to your domain!</p><br />";  
echo "<p>I heard you like ".$_SESSION['fav_food']." a lot.</p>";

This will put out:

Welcome Barney to you domain!  
I head you like chocolate coockies a lot.

You could also try to use Ajax, but I'm a noob in Ajax myself so I can't help you with that, but you could do some searching.

I hope it can help you!

UPDATE:

To set a session variable you can load a value from what ever your source is and store it like any other variable. Like:

$_SESSION['username'] = $queryresult['user'];

Make sure you enabled the session by starting each page with:

session_start();

I'll hope this is an answer to your question.

Where do you actually get the information of User a from? I suppose a database?



回答2:

Not entirely sure if this is what you're after, but maybe it'll help get you on the right path...

<?php
    // sample preferences, read from database
    $userPrefs = array(
        'block1' => true,
        'block2' => false,
        'block3' => true
    );

    $block1 = '<div id="block1">This is Block #1!</div>' . PHP_EOL;
    $block2 = '<div id="block2">This is Block #2!</div>' . PHP_EOL;
    $block3 = '<div id="block3">This is Block #3!</div>' . PHP_EOL;

    if ($userPrefs['block1'] == true) { echo $block1; }
    if ($userPrefs['block2'] == true) { echo $block2; }
    if ($userPrefs['block3'] == true) { echo $block3; }
?>

Output:

<div id="block1">This is Block #1!</div>
<div id="block3">This is Block #3!</div>