Search code examples
phpsessionvariablessetmeta-tags

Cannot pass specific variable to session


I'm trying to do the following (I know it appears to be unnecessarily complicated, but I had to break the problem down into its bits):

page_a.php

$keywords = get_meta_tags($_SERVER['HTTP_REFERER']);
$author = $keywords['author']; //"nameofauthor"
$foo = "foo";
$keywords = array ( "author" => $author, "foo" => $foo);
$_SESSION['keywords'] = $keywords;

//echo $author on page_a.php would successfully print "nameofauthor", so the variable isn't empty

page_b.php

echo $_SESSION['keywords']['author']; //echoes ""
echo $_SESSION['keywords']['foo']; //echoes "foo"

What am I missing?

Thanks!


Solution

  • I found the problem to be a double-execution of the page containing the script.

    In the first run, the referer was taken from the remote site (the one I need to retrieve the meta-tags from).

    In the second run, the referer was taken from the script hosting site and hence, resulting in this run overwriting the tags with empty values (since no meta-tags are being used in the script itself).

    To avoid the latter, I added the following lines to check whether it is the first or second execution.

    $baseurl = parse_url($request->getBaseUrl()); //My framework's function to return the hosting system's base-url (e.g., example.com)
    $referer = strstr($_SERVER['HTTP_REFERER'], $baseurl['host']) ? $_SESSION['referer'] : $_SERVER['HTTP_REFERER'];
    $keywords = get_meta_tags($referer);
    

    Thanks for sharing your thoughts!