array_key_exsists not working as expected PHP

78 Views Asked by At

Hi i am using array_key_exists in php , here is my code

$action_array = array(
    'add_post_ajax'=>'posts'
);


if ($_SERVER['REQUEST_METHOD'] === 'POST') 
{ 
     echo $_POST['action'];
    if(array_key_exists($_POST['action'],$action_array))
    {
        $class = $action_array[$_POST['action']];
    }
    else 
    {
        echo "wrong data";
    }
}

echo $_POST['action']; display add_post_ajax , then it prints wrong data

strange , please help me , am i doing anything wrong here

UPDATE

I also tried to trim

if(array_key_exists(trim($_POST['action']),$action_array))

still the same result :/

here is my ajax request

xmlhttp.send("action='add_post_ajax' &name=" + name + "&email=" + email + "&post=" + post);

echo $_POST['action'] gives me add_post_ajax but var_dump($_POST['action']) gives me a wired result

<pre class='xdebug-var-dump' dir='ltr'><small>string</small> <font color='#cc0000'>'&#39;add_post_ajax&#39; '</font> <i>(length=16)</i>
</pre>

What is it :o

1

There are 1 best solutions below

0
On BEST ANSWER

Your problem is single quotes.

Your $_POST['action'] uses 'add_post_ajax' but you're checking for add_post_ajax

When you send this:

xmlhttp.send("action='add_post_ajax' ...

you receive this:

 &#39;add_post_ajax&#39; (length=16)

add_post_ajax is 14 characters long, the extra two characters are &#39;; it's the html character for a single quote.