[thelist] Global variables in functions?

Kelly Hallman khallman at wrack.org
Wed Aug 20 01:28:59 CDT 2003


On Tue, 19 Aug 2003, Ralph Guzman wrote:
> This should do it:
> 
> $url = 'http://server/script.php?'.$_SERVER[QUERY_STRING];
> $output = file_get_contents ($url)
> 
> function body($output){
>   if(!$output){
>      return false;
>   } else { 
>      echo $output; } }

Isn't that pretty reflexive?  Looks like a wrapper for echo.
I see that you ammended your post saying that it should return $output 
instead of using echo.  However, I still fail to see how it's much 
different than if ($o) { echo $o; }, unless other code was added...

Also, in my last post, I'd like to point out:

> function body($url) {
>     $output = file_get_contents($url);
>     return $output; }
>
> $url = 'index.html';
> echo body($url);

$url in the function and $url outside the function are totally separate 
variables.  They don't need to be named the same, and it was a poor choice 
for me to do so in my example code.

Here's an improved function, which uses a rudimentary regex to return only 
what's between the body tags, or nothing. I tested the regex, but it could 
be jinxed by something like <body onload="if (x > 5) { alert(); }">

function body($url) {
    $output = file_get_contents($url);
    $regex = '/^.*?<body.*?>(.*)<\/body.*$/i';
    if (preg_match($regex,$output,$match)) { return $match[1]; } }

$fetchurl = 'index.html';
if ($bod = body($fetchurl)) { echo $bod; }
else { echo "No body section!"; }

-- 
Kelly Hallman
http://wrack.org/




More information about the thelist mailing list