So I'm hoping someone can help and I'm sure this is probably something simple I'm missing. I'm using PHP to access a .net API for a third party software.
Based on the very minimalist documentation on the API I have a working vbsript that connects to the object, performs a login and then does a query which results in the output of the query being dumped to a message box.
Here's the vbscript sample:
'Test device status
Set xxx = CreateObject("The.API.Object.Goes.Here")
'Login
Result = Xxx.LoginToHost("xxx.xxx.xxx.xxx","8989","Administrator","")
if (Result = true) then
MsgBox("OK")
else
MsgBox("Error - " & Xxx.LastError)
WScript.Quit
end if
'Get Status
Result = Xxx.GetDeviceStatus("", out)
if (Result = true) then
MsgBox(out)
else
MsgBox("Error - " & Xxx.LastError)
end if
'Logout
Result = Xxx.Logout()
if (Result = true) then
MsgBox("Logout OK")
else
MsgBox("Error - " & Xxx.LastError)
end if
The Xxx.GetDeviceStatus has two perimeters, the first being a device target or if left blank returns all devices, the second is the string variable to dump the result in.
When the script executes, the second message box contains a list of all devices as I would expect.
In PHP I have:
$obj = new DOTNET("XxxScripting, Version=1.0.XXXX.XXXXXX, Culture=neutral, PublicKeyToken=XXXXXXXXXXXXXXXX","Here.Goes.The.Api");
$obj->LoginToHost('xxx.xxx.xxx.xxx','8989','Administrator','');
$result = $obj->GetDeviceStatus('','out');
echo $result."<br />";
echoing result gives 1 because the value of result is a boolean value and GetDeviceStatus is successful. What I can't figure out is how to get the value of 'out' which is the actual query result.
Any help would be greatly appreciated.
The second parameter of GetDeviceStatus() method call according to the VBScript should pass a variable that will be populated with the output.
However in the PHP example you are just passing the string 'out' which isn't equivalent to what is being done in the VBScript.
Instead try passing a PHP variable to the method and then echoing that variable to screen, like this;
$result = $obj->GetDeviceStatus('', $out);
if ($result)
echo $out."<br />";
After a bit of digging it appears according to the PHP Reference that you need to pass By Reference variables to COM using the VARIANT data type.
Quote from ferozzahid [at] usa [dot] com on PHP - COM Functions
"To pass a parameter by reference to a COM function, you need to pass VARIANT to it. Common data types like integers and strings will not work for it."
With this in mind maybe this will work;
$out = new VARIANT;
$result = $obj->GetDeviceStatus('', $out);
if ($result)
echo $out."<br />";
Related
Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.
I have some Session values that I am constantly changing via Ajax calls. I can't seem to get a handle on the POST data to process it and set the values.
What I am passing to it here is an array of strings like is shown in my code below.
Here is where AJAX calls:
var sessionValues = [];
str = {"PID": "1", "Level": "Main", "MenuName": "Kitchen", "State": "CHECKED"}
sessionValues.push(str);
var postObj = {"sessionData": sessionValues};
$.ajax({
type: 'POST',
data: {'data': postObj},
url: 'setSession.asp'
}).done(function(response){
console.log(response);
})
I have this working fine in a PHP version of the program but my ASP version is not grabbing the data. Here is my PHP ver and the ASP ver as best as I could convert it.
<-- php setSession.php works fine -->
$data = $_POST['data'];
foreach ($data['sessionData'] as $key => $value) {
$projectProduct = "1";
$level = $value["Level"];
$menuName = $value["MenuName"];
$state = $value["State"];
$_SESSION['PID:'.$projectProduct][$level][$menuName]['menu_state'] = $state;
echo "[PID:".$projectProduct."][".$level."][".$menuName."][".$state."]<br>";
}
0 =>>>>> Array<br>[PID:1][Main][Kitchen][CHECKED]
Here I want to do the same thing in ASP
' setSession.asp
data = Request.Form("data")
For Each part In data("sessionData")
projectProduct = part("PID")
level = part("Level")
menuName = part("MenuName")
state = part("State")
Session("PID:" & projectProduct).Item(level).Item(menuName).Remove("menu_state")
Session("PID:" & projectProduct).Item(level).Item(menuName).Add "menu_state", state
response.write("[PID:" & projectProduct&"]["&level&"]["&menuName&"]["&state&"]<br>")
Next
outputs blank
It looks like it never has any data but doesn't throw any errors. Am I reading the POST object correctly?
[edit]
Here is the RAW POST data captured from Fiddler:
data%5BsessionData%5D%5B0%5D%5BPID%5D=1&data%5BsessionData%5D%5B0%5D%5BLevel%5D=Main&data%5BsessionData%5D%5B0%5D%5BMenuName%5D=Kitchen&data%5BsessionData%5D%5B0%5D%5BState%5D=CHECKED
here I used a URL Decode on that string-
data[sessionData][0][PID]=1&data[sessionData][0][Level]=Main Level Plan&data[sessionData][0][MenuName]=Kitchen&data[sessionData][0][State]=CHECKED
This looks like I should be able to loop through the strings now by using
For Each part In Request.Form("data[sessionData]")
but nothing happens. I added a simple loop to look at the request.form and here is what it is seeing:
for each x in Request.Form
Response.Write(x)
Next
' outputs -> data[sessionData][0][PID]data[sessionData][0][Level]data[sessionData][0][MenuName]data[sessionData][0][State]
I guess what this comes down to is just reading through and processing that string correctly, or multiple if more than one is sent. Correct?
The RAW output definitely helps work out what is going on.
What is happening is jQuery is translating the JSON structure into HTTP POST parameters but during the process, it creates some overly complex key names.
If you break down the key value pairs you have something like
data[sessionData][0][PID]=1
data[sessionData][0][Level]=Main Level Plan
data[sessionData][0][MenuName]=Kitchen
data[sessionData][0][State]=CHECKED
As far as Classic ASP is concerned the this is just a collection of string key and value pairs and nothing more.
The correct approach to work out what these keys are is to do what you have done in the question, but with some minor alternations.
For Each x In Request.Form
Response.Write(x) & "=" & Request.Form(x) & "<br />"
Next
Which when outputted as HTML will look similar to the break down shown above.
Armed with the knowledge of what the keys are you should be able to reference them directly from the Request.Form() collection.
Dim pid: pid = Request.Form("data[sessionData][0][PID]")
Response.Write pid
Output:
1
I’m trying to send the results of Vb script to a PHP variable,
The code get the CN name in AD.
My Vb code is below:
Set objADSysInfo = CreateObject("ADSystemInfo")
strUser = objADSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUser)
objUser.CN
How can I send the code to my PHP file as a variable once the webpage is loaded?
You can use an ADO Recordset as a wrapper
Set objADSysInfo = CreateObject("ADSystemInfo")
strUser = objADSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUser)
objUser.CN
ret = send2PHP("yourpage.php?data=", strUser)
function send2PHP(phpURL, data)
on error resume next ' if your php page returns a valid recorset you can omit 'on error
set rsPHP = wscript.createobject("adodb.recordset")
'here you must serialize "data" to be a valid uri value (not done here) '
rsPHP.open phpURL & data ,,,, 256 ' this statment (and the following ones) '
if not rsPHP.eof then send2PHP = rsPHP(0) ' fails if you do not return a valid recordset '
rsPHP.close ' form php script, but at least you '
set rsPHP = nothing ' have the "data" within the php anyway '
end function
I have an some PHP that looks like this:
$exec[0] = shell_exec("cat /etc/msm.conf | grep JAR_PATH");
$exec[1] = shell_exec("msm server list");
if(strstr($exec[1],'[ ACTIVE ] "mc-srv" is running. Everything is OK.') !== FALSE){
$exec[1] = 'mc online';
}else{
$exec[1] = 'mc offline';
}
$exec[2] = shell_exec("sudo ts status");
if($exec[2] == 'Server is running'){
$exec[2] = 'ts online';
}else{
$exec[2] = 'ts ofline';
}
echo json_encode($exec,JSON_FORCE_OBJECT);
An AJAX request gets sent to the page and the json is returned.
If I use console.log(JSON.parse(data)) I see this in the console Object {0: "DEFAULT_JAR_PATH="server.jar"↵", 1: "mc online", 2: "ts ofline"} however I can not access any of its methods even if i use an associative array.
but If i create a new object and print that to the console it (in chrome atleast) looks exactly the same in terms of syntax highlighting exect I can access it via obj.method.
What am I doing wrong here?
Based on how the object is being output in the console, it looks like it's being parsed okay by JSON.parse and is valid.
In which case, you should be able to access each method like this:
var obj = JSON.parse(data);
console.log( obj['0'] ); // returns "DEFAULT_JAR_PATH="server.jar""
console.log( obj['1'] ); // returns "mc online"
obj.0 won't work in this case because the method names are numbers.
inspite of the all the efforts that i gave on typecasting using (int) and intval() function. I am still not able to convert string to integer.
Whenever I use these function the string gets converted to 0
Here's my code snippet :
$resolution = "<script type='text/javascript'>
document.write('#'+screen.width+'#');</script >";
$screen=str_replace("#","",$resolution);
echo $wid = (int)$screen;
echo $s = 98 * $wid;
The output of the typecast is 0.
I even tried to print the data using var_dump but it also shows as int(0)
Your logic is flawed.
You are mixing server and client code.
Server generates code (php) and then passes the results to the client.
Client then receives the generated results and parses the javascript.
<?php
// this is server code, resolution will be just a string to the server
$resolution = "<script type='text/javascript'> document.write('#'+screen.width+'#');</script>";
// you are now removing the # from the above string but keeping it all intact
$screen=str_replace("#","",$resolution);
// converting it to int returns a stupid value (zero?)
echo $wid = (int)$screen;
echo $s = 98 * $wid;
?>