S.M. Nat S.M. Nat - 5 days ago 7
PHP Question

Can not acces array value in php

Have an php array made from POST data

$this->log->write(print_r($array , true));


Array
(
[accept] => */*
[accept-encoding] => gzip, deflate
[signature] => 37df88b6f845c21b1cda84cf3d3b94b0b15759b74f7387ceb0e9c8a6247c211f
[connection] => keep-alive
[content-length] => 610
[user-agent] => python-requests/2.10.0
)

$this->log->write(var_export($array , true).'var_export');

array (
'accept' . "\0" . '' => '*/*',
'accept-encoding' . "\0" . '' => 'gzip, deflate',
'signature' . "\0" . '' => '37df88b6f845c21b1cda84cf3d3b94b0b15759b74f7387ceb0e9c8a6247c211f',
'connection' . "\0" . '' => 'keep-alive',
'content-length' . "\0" . '' => '610',
'user-agent' . "\0" . '' => 'python-requests/2.10.0',
)var_export


The problem I can not access array value with
$array['signature'];
it is empty.

Sorry question looks nub but it is not. Work with arrays before and no problem. Have tried this as well
$array["signature"];
$array->signature;
empty returned.
Please help

Answer

As you can see, your keys are append somehow with \0 (which is end string character in C if my memory is good)

Thats why when you try to gather key signature there is nothing, because the key is signature\0

So, you have two solutions, first is calling $array['signature' . "\0"] second is doing an array key sanitizing.

Like this :

$keys = array_map(function($key){ return trim($key); }, array_keys($array));
$array = array_combine($keys, array_values($array));
  • Step 1: trim all keys
  • Step 2: re-associating sanitized keys to values

EDIT

Found out why ... at least if you are using PHP7

In fact if you return an array from a function, this will add null bytes at the end of each array key. See github issue https://github.com/CopernicaMarketingSoftware/PHP-CPP/issues/248 Btw I guess your PHP7 version is old :p keep in mind to update it ;)

Comments