PHP Error: Function name must be a string

php

Question

I added the following lines to the top of my PHP code, but it throws an error:

Fatal error: Function name must be a string in /home/reg.php on line 2

<?php
if ($_COOKIE('CaptchaResponseValue') == "false")
{
    header('location:index.php');
    return;
}
?>

I tried: $_COOKIE("CaptchaResponseValue"). The cookie is successfully set and is available. Why is it giving me an error when I am using $_COOKIE?

1
44
1/31/2019 1:03:54 AM

Accepted Answer

It should be $_COOKIE['name'], not $_COOKIE('name')

$_COOKIE is an array, not a function.

114
10/23/2009 6:42:20 AM

Using parenthesis in a programming language or a scripting language usually means that it is a function.

However $_COOKIE in php is not a function, it is an Array. To access data in arrays you use square braces ('[' and ']') which symbolize which index to get the data from. So by doing $_COOKIE['test'] you are basically saying: "Give me the data from the index 'test'.

Now, in your case, you have two possibilities: (1) either you want to see if it is false--by looking inside the cookie or (2) see if it is not even there.

For this, you use the isset function which basically checks if the variable is set or not.

Example

if ( isset($_COOKIE['test'] ) )

And if you want to check if the value is false and it is set you can do the following:

if ( isset($_COOKIE['test']) && $_COOKIE['test'] == "false" )

One thing that you can keep in mind is that if the first test fails, it wont even bother checking the next statement if it is AND ( && ).

And to explain why you actually get the error "Function must be a string", look at this page. It's about basic creation of functions in PHP, what you must remember is that a function in PHP can only contain certain types of characters, where $ is not one of these. Since in PHP $ represents a variable.

A function could look like this: _myFunction _myFunction123 myFunction and in many other patterns as well, but mixing it with characters like $ and % will not work.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon