if i use:
socket_read($socket, 1024);
I don't know what type of variable it returns. I want to make it to an int, but i don't know how.
The Server respons only a number (35).
If i echo it, i get 35. If i cast it to "(int)" i get 0. intval returns 0 too.
I have tried to cast it to string, and pick the first letter (3) but it returned 0. Substr doesn't work too.
I want to have an int value, so that i can calculate things with this value. I need an int to calculate the prozentage of this value from another value.
What can i do?
EDIT:
Fixed it in JAVA SERVER SOCKET CODE whith:
PrintWriter out = new PrintWriter(server.getOutputStream());
instead of using
DataOutputStream out = new DataOutputStream(server.getOutputStream());
Why not read the manual page. It returns a string.
Try print_r to find out the details of that string. Might be in binary?!
As you can see in the manual, socket_read always returns a string. You should try using var_dump() to check the real value of the variable.
Did you try to sum any number to that variable? In the autocast it may work.
Seems like the string contains additional whitespace that prevents PHP from converting it to a number.
Therefore I suggest you use the trim() function to remove whitespace before converting it to a number. Or you could use a regular expression to remove all non-numeric characters $out = preg_replace("/[^0-9]/g", "", $in)
If this still doesn't work and var_dump doesn't help you either, I'd suggest to sniff the network traffic using WireShark to inspect the packet coming from the server. If you're in control of what the server sends, use a decent serialization method like XML or JSON instead of inventing some protocol yourself.
Related
I'm including a remote file with file_get_contents() like so:
function checkData($serial) {
file_get_contents("http://example.com/page.php?somevar=".$serial."&check=1");
return $http_response_header;
}
This remote page performs some basic data manipulation, and looks up the serial number in a database (The input is sanitised and I'm using PDO, so I don't have to worry about SQL injections), and then returns a value in the response header. The input $serial is a get parameter - So completely controlled by the user. I'm wondering if there are any inputs to this function that would lead to undesirable behaviour, for example getting contents of another page other than the one desired.
Thanks in advance.
If the $serial variable is always going to be numeric you can apply intval() around the value to ensure the value will always be a number and not contain other non-numeric data for path traversal / RFC, etc.
E.G.
file_get_contents("http://example.com/page.php?somevar=".intval($serial)."&check=1");
Alternatively you can use preg_replace to strip unwanted characters, should you need alpha characters also.
http://php.net/manual/en/function.preg-replace.php
I'm very new to php .I want to convert the string to integer value.
I used following code to convert
$val='(100*2)';
echo (int)($val); //This will showing output as 0
But echo (int)((100*2)); /This will showing output as 200
Please help me any one to solve this .Thanks advance
(int)($val) evaluates to 0 because $val's value is not a numeric string (ie one that can be directly cast to a number).
If you really need this kind of functionality, try eval():
$val='(100*2)';
echo (int)($val); //This will showing output as 0
eval('$newval='.$val.';');
echo $newval;
But be warned: eval() can be dangerous!
From http://php.net/manual/en/function.eval.php:
Caution
The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
EDIT: Added .';' to eval parameter to make it a legit php instruction.
The most common suggestion will be - evaluate your string as PHP code, like:
$val = '(100*2)';
eval('$val = '.$val.';');
-but that's unsafe, eval should be avoided as long as possible.
Alternatively, there is bcParser for PHP, which can solve such issues. That's more safe than eval.
Finally, I doubt that you really need do such things - it seems you're solving some problem with wrong method (see XY-problem description)
You can do it using php eval function.
For that first you have to check for special characters and equation characters.
$val='(100*2)';
echo matheval($val);
function matheval($equation)
{
$equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation);
// fix percentage calcul when percentage value < 10
$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
// calc percentage
$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
// you could use str_replace on this next line
// if you really, really want to fine-tune this equation
$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
if ( $equation == "" )
{
$return = 0;
}
else
{
eval("\$return=" . $equation . ";" );
}
return $return;
}
I not recommended this, but you can use eval to suit your need
eval('$val = (100*2)');
echo intval($val);
Why not just:
$x=intval(100);// <- or an other value from the cleaned user input
$y=intval(2);
$val=$x*$y;
echo $val;
You are not giving a goal.
I can just explain why your code works like it does.
'(100*2)' is a String that cannot be converted to int, since it does contain other chars than numbers. Every String that cannot be converted will result in 0.
echo (int)(100*2) will work, because you use numbers and no strings. No need to convert, either, would work without the cast, just echo (100*2);
Remember PHP use loose typing. You will almost never need to convert types. This scenario is very set up.
echo 246810121416182022242628303234363840;
such
then it shows me value on brower as
2.4681012141618E+35
Please suggest me solution
wrap it in ""
echo "246810121416182022242628303234363840"
Use number_format(). For example:
echo number_format(246810121416182022242628303234363840,0,null,'');
Also, you can define custom thousands separator.
When dealing with very long integers in PHP, you're going to have trouble regardless of what you try to do.
From PHP's docs
If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead.
When given an int with value 246810121416182022242628303234363840, PHP interprets it as a float with value 2.4681012141618E+35. Even attempting to use number_format() as Timur suggests will result in printing '246810121416182028912708947168722944'.
Given that PHP can't be passing that value as you describe, you must be typing it in your code? If this is the case, your best bet for accurate echoing is to create a string instead of an int.
I'm a PHP newbie trying to find a way to use parse_str to parse a number of URLs from a database (note: not from the request, they are already stored in a database, don't ask... so _GET won't work)
So I'm trying this:
$parts = parse_url('http://www.jobrapido.se/?w=teknikinformat%C3%B6r&l=malm%C3%B6&r=auto');
parse_str($parts['query'], $query);
return $query['w'];
Please note that here I am just supplying an example URL, in the real application the URL will be passed in as a parameter from the database. And if I do this it works fine. However, I don't understand how to use this function properly, and how to avoid errors.
First of all, here I used "w" as the index to return, because I could clearly see it was in the query. But how do these things work? Is there a set of specific values I can use to get the entire query string? I mean, if I look further, I can see "l" and "r" here as well...
Sure I could extract those too and concatenate the result, but will these value names be arbitrary, or is there a way to know exactly which ones to extract? Of course there's the "q" value, which I originally thought would be the only one I would need, but apparently not. It's not even in the example URL, although I know it's in lots of others.
So how do I do this? Here's what I want:
Extract all parts of the query string that gives me a readable output of the search string part of the URL (so in the above it would be "teknikinformatör Malmö auto". Note that I would need to translate the URL encoding to Swedish characters, any easy way to do that in PHP?)
Handle errors so that if the above doesn't work for some reason, the method should only return an empty string, thus not breaking the code. Because at this point, if I were to use the above with an actual parameter, $url, passed in instead of the example URL, I would get errors, because many of the URLs do not have the "w" parameter, some may be empty fields in the database, some may be malformed, etc. So how can I handle such errors stably, and just return a value if the parsing works, and return empty string otherwise?
There seems to be a very strange problem that occurs that I cannot see during debugging. I put this test code in just to see what is going on:
function getQuery($url)
{
try
{
$parts = parse_url($url);
parse_str($parts['query'], $query);
if (isset($query['q'])) {
/* return $query['q']; */
return '';
}
} catch (Exception $e) {
return '';
}
}
Now, obviously in the real code I would want something like the commented out part to be returned. However, the puzzling thing is this:
With this code, as far as I see, every path should lead to returning an empty string. But this does not work - it gives me a completely empty grid in the result page. No errors or anything during debugging, and objects look fine when I step through them during debugging.
However, if I remove everything from this method except return ''; then it works fine - of course the field in the grid where the query is supposed to be is empty, but all the other fields have all the information as they should. So this was just a test. But how is it possible that code that should only be able to return an empty string does not work, while the one that only returns an empty string and does nothing else does work? I'm thoroughly confused...
The meaning of the query parameters is entirely up to the application that handles the URL, so there is no "right" parameter - it might be w, q, or searchquery. You can heuristically search for the most common variables (=guess), or return an array of all arguments. It depends on what you're trying to achieve.
parse_str already decodes urlencoding. Note that urlencoding is a way to encode bytes, not characters. It depends on what encoding the application expects. Usually (and in this example query), that should be UTF-8 everywhere, so you should be covered on 1.
Test whether the value exists, and if not, return the empty string, like this:
$heuristicFields = array('q', 'w', 'searchquery');
foreach ($heuristicFields as $hf) {
if (isset($query[$hf])) return $query[$hf];
}
return '';
The function returns null if the input is valid, and runs into errors (i.e., displays warning messages) when the URL is obviously invalid. The try...catch block has no effect.
It turned out the problem was with Swedish characters - if I used utf8_encode() on the value before returning it, it worked fine.
Can anyone please tell me why line 1 works (returns 35434), but line 2 doesn't (returns blank)?
echo $_FILES['userfile']['size'];
die ($_FILES['userfile']['size']);
Thanks!
die is equivalent to exit and you'll notice that exit takes either an integer or a string as an argument. In the case you pass an integer, then the program exits and returns that integer as its exit code.
$_FILES['userfile']['size'] is an integer, not a string, so instead of outputting the message to the screen, it returns the size as the return code of the program.
A simple solution is to concatenate to an empty string to let the PHP compiler you want a string instead of an integer:
die('' . $_FILES['userfile']['size']);
I answered this a few hours ago, anyway the other answers are right.
As a workaround (if you need to do that), casting the integer to a string will do the trick:
die(strval($_FILES['userfile']['size'])); // or
die((string) $_FILES['userfile']['size']);
die() only prints strings. (See manual) If you add some text in there it will work, for some reason. ;)