OiO.lk Blog PHP php associative array to javascript array not recognized as JS Array
PHP

php associative array to javascript array not recognized as JS Array


I have a series of PHP API scripts that in almost all cases returns an associative array to the calling app.

PHP:

$returnInfo = array() ;
$returnInfo[] = array("success"=>true,"key1"=>"value1","key2"=>"value2",...) ;

//Then at the end of the API:
sendResponse(200,json_encode($returnInfo)) ;

function sendResponse($status, $body) {
    $status_header="HTTP/1.1 " .$status. ' ' .getStatusCodeMessage($status);
    header($status_header);
    header('Content-type: application/json');
    echo $body;
}

After recently upgrading from PHP 7.3 to 8.2 my app began reporting inconsistent errors when making calls to the PHP API. Most of the time the same API call works just fine, then occasionally it fails. From within the app, the HTTP call checks for response 200 AND if the returned data is an ARRAY or OBJECT. In all failures, my app actually reports 200 Successful response was received. Then, based on if the response.data is an ARRAY or OBJECT then do X or Y.

The app is only occasionally reporting an error when the data is an ARRAY.

function objArray(val,type) {
  //type = 1 = object
  //       2 = array
  if (type == 1) {
    return (!!val) && (val.constructor === Object) ;
  } else if (type == 2) {
    return (!!val) && (val.constructor === Array) ;
  }
}

var baseUrl = "https://api.example.com/apiFile.php" ;
var req = {
  method: 'POST',
  url: baseUrl,
  timeout:httpTimeout,
  headers: headers,
  data: JSON.stringify(dataObj)
}

 return $http(req)
.then(function(response){
  if (response.status == 200 && objArray(response.data,2)) {
     ...
     ... do stuff with response 
     ...
  } else {
    var err = resError(req,response) ;
    err.callBack = "Success" ;
    throw err ;
  }

When app receives data correctly, I then return response.data[0] to the original calling function for the app (and user) to continue on.

But when the throw err ; happens, it calls another api script to send the details of the error to my server. The error captured is (with some other custom messaging):

   status = 200
   statusText = SUCCESS RESPONSE ERROR: OK
   callBack = Success

Because the API is returning a 200 I know the response.status == 200 is true, but then it must mean that objArray(response.data,2) is NOT returning TRUE – causing the else part of the response process to then throw an error.

This only began after upgrading from PHP 7.3 to PHP 8.2. So what has changed…or has gotten more strict and/or less forgiving…in PHP 8.2 that is causing my app to sometimes see the response.data as not an array?



You need to sign in to view this answers

Exit mobile version