Unable to convert string to integer in PHP - php

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;
?>

Related

What is the analogue of struct.pack() in php?

I have a variable id = 1615239032
In python i do
struct.pack('<i', id)
Result is
x\x97F`
In php i do
pack('i', $id)
But result is
x▒F`
How to get the same in php?
You already get the same as in Python. It gets corrupted when you try to display it.
If you convert the binary data to something else, for instance their hexadecimal represantions, you'll see that they are the same:
echo bin2hex("x\x97F`");
echo "<br>";
echo bin2hex(pack("i", 1615239032));
Result:
78974660
78974660

Does python json output values have maximum length for json_decode (php) to handle?

I am trying to write a php code that takes coefficients from a html form, sends them to a python algorithm that returns a json object. That object is a list of player names, basically {"Ji" : "Firstname Lastname"} for i from 1 to 15.
The python code (interface.py) I have to create this json is :
import json
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]=joueur['nom']
out=json.dumps(output)
print(out)
best_team is a list of player dictionnaries with data on them. My player names don't involve any non ASCII characters or whatever.
My php code is the following :
$command = "python interface.py";
$command .= " $coeff1 $coeff2 $coeff3 $coeff4 $coeff5 $coeff6 $coeff7 $coeff8 $coeff9 $coeff10 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
$data = fread($pid, 256);
$data= json_decode($data) ;
echo $data->J1;
flush();
ob_flush();
echo "<script>window.scrollTo(0,99999);</script>";
usleep(100000);
}
pclose($pid);
I call the coefficients from the html and then send back the results via a js file.
But I just get the following error : Notice: Trying to get property of non-object.
Nothing wrong with the js file because if I try instead :
$string = '{"foo": "bar", "cool": "attributlong"}';
$result = json_decode($string);
echo $result ->cool;
It works.
Also if I have instead in my python file :
out={"foo":"bar","word":"longerthaneightcharacters"}
out=json.dumps(out)
print(out)
It works as well (replacing J1 by word in php code of course).
And funny enough, if i have in python:
output={}
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]="short"
output["J%s"%(i)]=str(output["J%s"%(i)])
out=json.dumps(output)
print(out)
It works, and if I replace "short" by "longerthaneightcharacters" it doesn't work anymore.
So basically my question is, why is there a maximum number of characters in my output loop and how can I bypass it ? Thanks, I am very confused.

Pass By Reference to COM Object in PHP

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 />";

json_decode Preservation of Type

I'm using the json_decode function to decode (and verify a postback from a payment processor). the json object received looks as follow
{
"notification":{
"version":6.0,
"attemptCount":0,
"role":"VENDOR",
.....
"lineItems":[
{
"itemNo":"1",
"productTitle":"A passed in title",
"shippable":false,
"recurring":false,
"customerProductAmount":1.00,
"customerTaxAmount":0.00
}
]
},
"verification":"9F6E504D"
}
The verification works as follows, one takes the notification node and append a secret key. The first eight characters of the SHA1 hash of this string should match the content of the validation node.
However, I noticed that whilst using json_decode, the double value 6.0, 0.00 etc are truncated to integers (6, 0 ,etc). This messes up the string (in terms of it not generating the correct SHA1-hash). Do note, I cannot use the depth limit to prevent decoding of the notification branch, since I need to support PHP 5.0. How can I tackle this issue. The (defect) validation code I wrote is:
public function IPN_Check(){
$o = (json_decode($this->test_ipn));
$validation_string = json_encode($o->notification);
}
I tried the following:
<?php
var_dump(json_decode('
{
"notification":{
"version":6.0,
"attemptCount":0
}
}
'));
and got this output:
object(stdClass)#1 (1) {
["notification"]=>
object(stdClass)#2 (2) {
["version"]=>
float(6)
["attemptCount"]=>
int(0)
}
}
PHP does make a difference between float and int, maybe you could do something like gettype($o->notification[$i]) == 'float' to check whether you need to add a zero using a string.
UPD.
PHP does make a difference between float and int, but json_encode() - may not. To be sure, that you encode all values as they are - use json_encode() with JSON_PRESERVE_ZERO_FRACTION parameter, and all your float/double types will be saved correctly.
It looks like ClickBank they always send it in the same format with only the two top level fields "notification" and "verification". So you can just use substr to remove the first 16 characters ({"notification":) and the last 27 characters (,"verification":"XXXXXXXX"}) from the raw JSON and then proceed from there:
$notification = substr($json, 16, -27);
$verification = strtoupper( substr( hash('sha1', $notification . $secret), 0, 8) );

Android: Unbelievable StringIndexOutOfBoundsException

I send a get request to a php script on webserver that returns 3 lines of text. I handle the response from the server like this:
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
Than I parse the lines like this:
line = "";
while ((line = rd.readLine()) != null) {
String a = line.substring(0, line.indexOf('_'));
String b = line.substring(line.indexOf('_') + 1);
}
And this keeps throwing a StringIndexOutOfBounds exception and I can't really see why. Im already using a similar method elsewhere in my project (with a different PHP script returnig different lines of text and with a different parsing) and it works perfectly fine. When I Log the returned lines to see if they are properly returned from the server, they are the same lines that PHP script sends.
And here is the fun part. When I was growing pretty desperate, I tried to measure the line using:
int l = line.length();
and this returned 11 with my line. Than, when I simply tried to display something using:
line.charAt(5);
it threw a StringIndexOutOfBoundsException: 5. I realy don't know what is wrong with this. Does anyone have an idea? Thanks!
EDIT
This is the PHP script
$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query)) {
print("{$row['id']}\n{$row['number']}\n");
}
This is my java code:
while ((line = rd.readLine()) != null) {
Log.v("connection - user list", line); //This line logs: 1_485963
//But this doesent work
String a = line.substring(0, line.indexOf('_'));
String b = line.substring(line.indexOf('_') + 1);
}
Most likely indexOf returns -1 and line.substring(0, -1); throws StringIndexOutOfBoundsException
EDIT
Could it be that you might be reading an invisible character/line after 1_485963 line?
Assume input is like this:
1_485963\n\n
Then in the log you would see only 1_485963 but the 2nd time loop runs it would crash.
First try to debug. OR else try this
I am pretty sure that line.indexOf('_') is not available in given string
1) first print log of the string and check '_' character is available.
try this to avoid StringIndexOutOfBoundsException
while ((line = rd.readLine()) != null) {
if (line.indexOf('_') != -1) {
String a = line.substring(0, line.indexOf('_'));
String b = line.substring(line.indexOf('_') + 1);
}else{
// means that index is not found
}
}
And finally you told string len = 11
and when printing char at position 5 is throw error.
check what u r doing in between printing len of the string and printing char at postion 5.
FINALLY some times you might get junk character from the buffer input stream. becoz its passing from n/w. check that also.
Maybe I'm getting old and blind but how does this
print("{$row['id']}\n{$row['number']}\n");
produce
1_485963
Surely
print("{$row['id']}_{$row['number']}\n");
is what you need.
Apologies if that is not valid PHP as the syntax of that
has always refused to stick in my brain.

Categories