JSON.php decode behavior different between servers - php

I have the following problem : On my local development server PHP 5.3.10 / Apache 2 every things goes right. When I run the same code with the production server PHP Version 5.2.13 / Apache 2 the code fail but on certain conditions not always.
More details :
The context : I have a dojox.data.grid table on the screen that can be updated. The modified data is correctly passed to the server as a JSON string. Like this :
data = {
"deletedItems":{}
,"newItems":{}
,"modifiedItems":{
"2890":{"idFacture":"2890"
,"idClient":"175"
,"idAffaire":"1323"
,"idContrat":"2234"
,"raisonSociale":"xxxxxx"
,"nomAffaire":"xxxxxx"
,"nrFacture":"xxxxx"
,"dateFacture":"2012-12-06"
,"montantFacture":"160000.00"
,"pourcentageFacture":"64.88"
,"pourcentageCalcule":"32.44"
,"noteFacture":""
,"dateTransfert":""
,"aTransferer":true
,"typeDocument":"Facture"
,"factureSoldee":false
,"montantTotalHeures":"0.00"
,"pourcentageTotalHeures":"0.00"
,"montantTotalMateriel":"0.00"
,"pourcentageTotalMateriel":"0.00"
,"montantTotalSousTraitance":"160000.00"
,"pourcentageTotalSousTraitance":"40.94"
}
,"2892":{"idFacture":"2892"
,"idClient":"50"
,"idAffaire":"1649"
,"idContrat":"2713"
,"raisonSociale":"xxxxx"
,"nomAffaire":"xxxxx"
,"nrFacture":"xxxxx"
,"dateFacture":"2012-12-07"
,"montantFacture":"12004.50"
,"pourcentageFacture":"0.00"
,"pourcentageCalcule":"41.94"
,"noteFacture":""
,"dateTransfert":""
,"aTransferer":true
,"typeDocument":"Facture"
,"factureSoldee":false
,"montantTotalHeures":"12004.50"
,"pourcentageTotalHeures":"41.95"
,"montantTotalMateriel":"0.00"
,"pourcentageTotalMateriel":"0.00"
,"montantTotalSousTraitance":"0.00"
,"pourcentageTotalSousTraitance":"0.00"
}
}
}
You can see that the data contains three elements "deletedItems" (empty), "createdItems" (empty) and "modifiedItems".
In the php code i have the following commands :
$srvJson = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$data = $srvJson->decode($data);
Where $data is filled like above. Normally after that last statement the folowing PHP variables are set :
$data["deletedItems"]
$data["createdItems"]
$data["modifiedItems"]
Here is the problem : if on the production server there are a lot of modified rows (about > 30) in the table, the modified data is correctly passed to the serveur BUT $data["modifiedItems"] is not set ??? If I just modify the dataset for a few rows $data["modifiedItems"] is well set.
I can modify the whole data set piece per piece, but not the whole dataset in one time.
I suppose this is a question of server settings but what ?
I would appreciate any suggestion.
Best regards,
Roger
PS : Sorry for my english

Since it is not valid JSON (checked with http://jsonlint.com/) the results of json_decode() in PHP 5.3.10 and PHP 5.2.13 are different!
While 5.3 returns nothing 5.2.13 returns the initial string. Probably your code has somewhere some error corrections...
See the different results of the different PHP version on 3v4l.org!
When us remove data = from your JSON does not throw errors..

Based on your above issue, you can check following things on server
magic_quotes are open or closed on server similiar to local server
Does Services_JSON is compitable to PHP 5.3
Services_JSON is pear php library so please check that it is working properly with all extension of php
http://pear.php.net/bugs/search.php?cmd=display&package_name%5B%5D=Services_JSON
Or you can use the default php json library for encode and decode
May this will help you

Related

Send data from VBA (excel) to php and vice versa

Basically I want to communicate with a MYSQL server using php as the middle-ware.
I cannot connect directly to the database due to drivers needing to be installed and our IT will not allow drivers to be installed on our company computers.
I understand how to insert data using vba ->php->mysql but I cannot figure out how to get data from mysql to excel. vba->php->mysql->php->vba.
I want to do a query and send the results to vba excel.
Here is the VBA Code that works but it also sends multiple spaces back as well. Im not sure if this is the correct way to do this.
Private Sub ExtractPHP()
Dim item As String
Dim objHTTP As Object
Dim URL As String
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost/php/requestdata.php"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencode"
objHTTP.send ("")
Worksheets("hiddendata").Range("k4").Value = Replace(objHTTP.responseText, " ", "")
End Sub
The PHP code is as follows.
<?php
$con = mysqli_connect("localhost","root","","php") or die("Connection was not created!");
$select = "select name FROM users where id=5";
$run = mysqli_query($con,$select);
$value = mysqli_fetch_array($run);
$result = $value["name"];
echo $result;
?>
Result that is placed in the excel file has multiple spaces below the text. Is this the correct way to communicate between excel and mysql?
I am not sure about the VBA method and what exactly you need to do but one solution would be to write requestdata.php to parse the result of your query into a .csv file and then load that into Excel via VBA. Parsing the result array into the .csv plain text format is made even more trivial by the fact that PHP already has a function fputcsv($file, $records) to use (documentation).
i can help you 10% cause i programming in several languages but nothing vba/excell .I programming in php too...anyway my answer for you is :
Let say you create in C: a new folder and you create a runme.bat file there.
Using one methods to run a external .bat file and to grab external result from that runme.bat more or less like in
Execute a command in command prompt using excel VBA
Wait for shell command to complete
you can use like me a method to run from that batch php cli:
you can drop runme.php in that folder as well:
<?php
if(isset($argv[1])){
echo($argv[1]);
//here you can drop some mysql
}
?>
then you should understand how to reconfiger php ini to connect to mysql ,some problems you can dare are
PHP: mysql_connect() won't work via command line
if you put a command like this one i already check via windows cmd and works
c:\xampp\php>php "c:\test\runme.php" yep2
and you are getting "yep2"
as c:\test\ 's runme.bat version :
rem #echo off
set parameter=%1
set PHP_BIN="c:\xampp\php\php.exe"
set script=%cd%\runme.php
%PHP_BIN% %script% %parameter%
and for test we call it in cmd : runme yep2
with the result: yep2
then with the batch modiffied you can fill data in mysql let's say you will call that not runme.php but putmysqldata.php .
at this point creating another file php to read from mysql (even you use only one file php to write or read by calling it by different parameter) so you will be able to read from mysql
so isn't easy if you don't know much vba or how to do it.
following these steps i think if you know some vba more than me you can figure out the shortest way.

Azure Functions with PHP

I'm trying out Azure Functions using PHP.
Getting the request information is not working for me.
I've not been able to find any documentation at all with the information of how to use Azure Functions with PHP code.
According to the only couple of examples, it seems that in order to retrieve the input information you need to first get the content of the req variable (or whatever name you assign in the function configuration).
That has the path of the file containing the request information (in theory).
$input_path = getenv('req');
So far, if I check the content of it, I get something like this:
D:\local\Temp\Functions\Binding\e2b6e195-02f7-481b-a279-eef6f82bc7b4\req
If I check if the file exists it says true, but the file size is 0.
Do anyone knows what to do here? Anyone with an example? Does anyone know where the documentation is?
Thanks
Ok, unfortunately there's pretty limited documentation out there for php as you have discovered.
At present, looking at the code might be the best doc. Here is the InitializeHttpRequestEnvironmentVariables function that adds request metadata to the environment for the script languages (node, powershell, php, python).
Important environment variables are:
REQ_ORIGINAL_URL
REQ_METHOD
REQ_QUERY
REQ_QUERY_<queryname>
REQ_HEADERS_<headername>
REQ_PARAMS_<paramname>
I'm assuming you've made a GET request, in which case there is no content (req is an empty file), but you will see that these other environment variables contain request data. If you were to make a POST request with a body then req would have data.
here is a full example parsing a GET request in PHP with an Azure Function :)
https://www.lieben.nu/liebensraum/2017/08/parsing-a-get-request-in-php-with-an-azure-function/
snippet from source:
<?php
//retrieve original GET string
$getReqString = getenv('REQ_QUERY');
//remove the ? for the parse_str function
$getReqString = substr($getReqString,1,strlen($getReqString));
//convert the GET string to an array
$parsedRequest = array();
parse_str($getReqString,$parsedRequest);
//show contents of the new array
print_r($parsedRequest);
//show the value of a GET variable
echo $parsedRequest["code"];
?>

Accessing Object in PHP

I've some strange issues with some php code.
if ($user->userType=='admin'){
If I use the above command, the php engine just stop interpreting and display the code in plain text on my browser. On the other hand if I use the below method it works:
if ($user['userType']=='admin'){
Again here also:
$_SESSION['currentUser']->id
If I use the above code it just displays the rest of code as plain text:
id); // fail user }else{ $authentication="failed"; $noAuthPresentation="loginForm"; }
Why this is happening? It's a big project and I don't want to change every line where there is an occurrence of ->.
Do I need to change some setting somewhere? I'm using WAMP server with php 5.5.12.
Any help ? Thanks!
You're mixing up types, user is an array, and not an object. Something in your php config is doing something strange to your error display it seems. Right click on the page that has the errors, and view source if possible.
Does login.php contain html and php code by chance?

Get windows title using php doesn't work on browser call

My problem is I need to fetch FOOBAR2000's title because that including information of playing file, so I create a execute file via Win32 API(GetWindowText(), EnumWindows()) and it's working good.
TCHAR SearchText[MAX_LOADSTRING] = _T("foobar2000");
BOOL CALLBACK WorkerProc(HWND hwnd, LPARAM lParam)
{
TCHAR buffer[MAX_TITLESTRING];
GetWindowText(hwnd, buffer, MAX_TITLESTRING);
if(_tcsstr(buffer, SearchText))
{
// find it output something
}
return TRUE;
}
EnumWindows(WorkerProc, NULL);
Output would look like "album artis title .... [foobar2000 v1.1.5]"
I created a php file like test.php, and use exec() to execute it.
exec("foobar.exe");
then in console(cmd) I use command to execute it
php test.php
It's working good too, same output like before.
Now I use browser(firefox) to call this php file(test.php), strange things happened.
The output only foobar2000 v1.1.5, others information gone ...
I think maybe is exec() problem? priority or some limitation, so I use C# to create a COM Object and register it, and rewrite php code
$mydll = new COM("FOOBAR_COMObject.FOOBAR_Class");
echo $mydll->GetFooBarTitle();
still same result, command line OK, but browser Fail.
My question is
Why have 2 different output between command line and browser. I can't figure it out.
How can I get correct output via browser.
or there is a easy way to fetch FOOBAR2000's title?
Does anyone have experience on this problem?
== 2012/11/28 edited ==
follow Enno's opinion, I modify http_control plug-in to add filename info, original json info is "track title".
modify as following
state.cpp line 380 add 1 line
+pb_helper1 = pfc::string_filename(pb_item_ptr->get_path());
pb_helper1x = xml_friendly_string(pb_helper1);
# 1: when firefox opens the php and it gets executed, it the context depends on the user which runs the php-container (apache), this is quite different from the commandline call which gets executed in your context
# 2 and 3: there seems to be more than one way for getting the title: use the foobar-sdk and create a module which simply reads the current title per api, then write your result in an static-html-document inside your http-root-folder OR use the http-client inside the sdk, with it, you do not need a wabserver, even better use a already implemented module: for instance foo_upnp or foo-httpcontrol
Good luck!
If your webserver runs as a service, in windows you need to enable "allow desktop interaction" for the service. Your php script runs as a child of the webserver process when requested via browser.

Ajax issues, Invalid JSON

I'am building simple Ajax application (via jquery). I have strange issue. I found where the problem is, but I don't know how to solve it.
This is simple server-side php code:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
On the client side, the error "Invalid JSON" is thrown.
I have discovered that if I delete require function, everything work fine.
Just for information, the "some.php" is an empty php file. There is no error when I open direct php files.
So, conclusion: I cant use require or include function if I want to use ajax?
Use Firebug to see what you're actually getting back during the AJAX call. My guess is that there's a PHP error somewhere, so you're getting more than just JSON back from the call (Firebug will show you that). As for your conclusion: using include/require by itself has absolutely no effect on the AJAX call (assuming there are no errors).
Try changing:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
To:
<?php
$return = array(
'pageContent' => 'test'
);
echo json_encode($return);
?>
The problem might have to do with $return not being declared as an array prior to use.
Edit: Alright, so that might not be the problem at all. But! What might be happening is you might be echoing out something in the response. For example, if you have an error echoing out prior to the JSON, you'd be unable to parse it on the client.
if the "some.php" is an empty php file, why do you require it at all?!
require function throws a fatal error if it could't require the file. try using include function instead and see what happens, if it works then you probably have a problem with require 'some.php';
A require call won't have any effect. You need to check your returned output in Firebug. If using Chrome there is a plugin called Simple REST Client. https://chrome.google.com/extensions/detail/fhjcajmcbmldlhcimfajhfbgofnpcjmb through which you can quickly query for stuff.
Also, it's always good to send back proper HTTP headers with your response showing the response type.
It's most likely the BOM as has been discussed above. I had the same problem multiple times and used Fiddler to check the file in hex and noticed an extra 3 bytes that didn't exist in a prior backup and in new files I created. Somehow my original files were getting modified by Textpad (both in Windows). Although when I created them in Notepad++ I was fine.
So make sure that you have your encoding and codepages set up properly when you create, edit, and save your files in addition to keeping that consistent across OSes if you're developing on windows let's say and publishing to a linux environment at your hosting provider.

Categories