Php Server error caused by return ?:"http"

257 Views Asked by At

I'm a novice php and I'm stuck on a problem I was hoping someone could offer me help with.

When I upload a .php with the following contents to my server and load it in a chrome browser there doesn't seem to be any problem.

<?php

 class AppInfo {
   public static function getHome () {
   return ($_SERVER['HTTP_X_FORWARDED_PROTO'])."://" . $_SERVER['HTTP_HOST'] . "/";
 }  

}

However when I upload a .php file containing the very similar code below (the difference is the presence of ?:"http"), chrome returns a server error (pasted below the code)

<?php
class AppInfo {
  public static function getHome () {
    return ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?: "http") . "://" .    $_SERVER['HTTP_HOST'] . "/";
 }
}

Error:

Server error The website encountered an error while retrieving "Url" It may be down for maintenance or configured incorrectly.

2

There are 2 best solutions below

1
On

You should change it to

return ($_SERVER['HTTP_X_FORWARDED_PROTO'] ? $_SERVER['HTTP_X_FORWARDED_PROTO'] : "http") . "://" .    $_SERVER['HTTP_HOST'] . "/";

So this would mean that if ($_SERVER['HTTP_X_FORWARDED_PROTO'] is there use it else use http.

2
On

I believe you are trying to use what's called the ternary operator. This operator expects the following syntax:

(comparison statement) ? (what to do if true) : (what to do if false)

The documentation states that you may omit the middle clause (the 'what to do if true' clause), only if you're using PHP 5.3 or later. In my opinion, this is bad practice. I'm not aware of any other programming languages that allow that shortcut, and it only makes reading your code that much more difficult (especially if you're reading it a year or more after you wrote it). It's best to write code that is (where possible) backwards compatible; it will be that much more portable as a result.

Update: I read a little about the ternary operator on Wikipedia, and a few other languages do have shortcuts like this (a GNU extension for C exists, for example). I still think using the shortcut is bad; the case where statement evaluation results in side effects springs to mind.