theorise
theorise

Reputation: 7425

Simple PHP function and variable confusion

I have a couple of simple PHP functions I am using. One to detect wether the user is on an iPhone, and one to resize images if they are.

<?php 

/* User agent function */
function userAgent(){
    $browser = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    if ($browser == true)  { $var = 1; }
    return $var;
}

/* Image resize function */
function imageResize($width, $height) { 

    $var = userAgent($var);

    if($var == 1){
        $width = round($width / 2); 
        $height = round($height / 2); 
    }else{
        $width = round($width);
        $height = round($height);
    }

    echo "width=\"$width\" height=\"$height\""; 
} 

?>

The problem is, if I manually change the $var to 0 or 1 in the userAgent() function, the images do not resize, but if I change the $var to == 0 in the imageResize() function, they do.

Why is the variable not carrying across from the first, to the second function, or am I doing something else wrong?

Upvotes: 0

Views: 128

Answers (3)

Pekka
Pekka

Reputation: 449435

strpos never returns true. You will need to test for $browser != false, otherwise your function will never recognize an iPhone.

However, your code is unnecessarily complicated, and returning an integer is not really useful here. I would recommend a simplified rewrite:

// Make it return `true` or `false` instead of `1`, also make it universal
function isAgent($string)
 {
    return (strpos($_SERVER['HTTP_USER_AGENT'],$string) !== false);
 }


/* Image resize function */
function imageResize($width, $height) { 

    if(isAgent("iPhone")){
        $width = round($width / 2); 
        $height = round($height / 2); 
    }else{
        $width = round($width);
        $height = round($height);
    }
    // Consider using CSS
    echo "style=\"width: {$width}px; height: {$height}px;\""; 
} 

Upvotes: 5

Andrei Serdeliuc ॐ
Andrei Serdeliuc ॐ

Reputation: 5878

It seems you are only returning $var if the user agent is iPhone, otherwise you are trying to return an undefined variable (within your userAgent function)

try:

function userAgent(){
    $browser = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $var = 0;

    if ($browser !== false)  { $var = 1; }
    return $var;
 }

Upvotes: 3

xtofl
xtofl

Reputation: 41509

Do you expect the $var argument to be processed by the userAgent function? In that case, you need to specify it as an argument.

function userAgent( $var ) {
...

Otherwise, you may want to initialize the $var in the function body. It's a wise strategy to keep your if-then-elses symmetrical:

if( $browse ) {
   $var = 1;
} else {
   $var = 0;
}

And you can write this a bit more succinct like

function userAgent() {
   $browser = .....
   return $browser ? 1 : 0;
}

Upvotes: 0

Related Questions