1

I have the error Only variables should be passed by reference on my APIController.php, I already read all the questions about this error but nothing fixed it.

My code :

$ip = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
    $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
    $ip = array_pop(end($ip));
}

Error.log :

[2016-12-06 15:43:00] production.ERROR: exception 'ErrorException' with message 'Only variables should be passed by reference' in /var/www/app/Http/Controllers/Api/ApiController.php:33
Stack trace:
#0 /var/www/app/Http/Controllers/Api/ApiController.php(33): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2048, 'Only variables ...', '/var/www/app/Ht...', 33, Array)

Thank you.

1 Answer 1

2

Try to save the end element of array into a variable then pass it into the method like this:

$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = end($arr); // <------- This will give you the IP (no need of using array_pop)

'ErrorException' Explanation: The problem is, that end() requires a reference, because it modifies the internal representation of the array (i.e. it makes the current element pointer point to the last element).

Hope this helps!

5
  • exception 'ErrorException' with message 'array_pop() expects parameter 1 to be array, string given' in /var/www/app/Http/Controllers/Api/ApiController.php:34
    – Pixel
    Dec 6, 2016 at 15:51
  • Yeah the error is quite correct, you should pass array inside array_pop() Dec 6, 2016 at 15:53
  • $ip = end($ip) Will give you the ip. No need for the array_pop() Dec 6, 2016 at 15:55
  • @Pixel - I've updated the answer, please check it out - The end() will get you the IP Dec 6, 2016 at 15:58
  • Thanks to my addition :P Dec 6, 2016 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.