0

Is it possible to access globals inside a function that was called via a URL - like this:

URL

example.com/download.php?fn=download&fname=file

Does the first example below not work because the function call goes straight to the download() function without reading the rest of the php script? (i.e. where $var1, $var2 are declared).

download.php

<?php

$var1 = 'foo';
$var2 = 'bar';

global $current_user;  // from elsewhere

if ($_GET['fn'] == "download")
    if (!empty($_GET['fname']))
        download($_GET['fname'], $current_user);

function download($fname, $current_user)
{
    // Access the global variables in this scope
    global $var1; 
    global $var2;

    $output = $fname . $var1 . $var2;

    echo $output  // no output here...
}

But this works with the same URL as above:

<?php

global $current_user;  // from elsewhere

if ($_GET['fn'] == "download")
    if (!empty($_GET['fname']))
        download($_GET['fname'], $current_user);

function download($fname, $current_user)
{
    // Access the global variables in this scope
    $var1 = 'foo'; 
    $var2 = 'bar';

    $output = $fname . $var1 . $var2;

    echo $output  // "filefoobar"
}

Is there a way of doing this, or do I just have to declare my variables in the function and skip using global? (I know global is often ill-advised etc...)

decvalts
  • 743
  • 10
  • 23
  • I can't see why that shouldn't work. Is that the exact code you are using? – Eborbob Sep 04 '15 at 14:41
  • From your latest edit something's not right - you claim that the `$fname` variable isn't being printed now. Seems most likely that your download function isn't being called at all. – Eborbob Sep 04 '15 at 14:43
  • The only explanation would be that `$var1` is not actually `global`. It depends on how your script is actually executed. See the duplicate. If that doesn't help, add more information to un-duplify it. – deceze Sep 04 '15 at 15:04

0 Answers0