Emoji to JSON encoded, post to web server - php

Please help me with my problem in posting a JSON decoded emoji character.
I have a UITextView, this text view may have a emoji character. I am posting the data to a web server with the UITextView.text presented as JSON, the problem is when the text has a an emoji, I am not able to get the data. What I do is:
$postData = file_get_contents("php://input") to get the data.
then I use
$post = json_decode($postData,true);
to decode the data and have a assoc array and insert the data in database.
here is a code snippet when I insert my data into database.
$postData = file_get_contents("php://input");
//$postData = '{"body":"characters here ","subject":"subject here","username":"janus","from_id":"185","to_id":"62"}';
$post = json_decode($postData,true);
$data=array(
'user_id_from'=>mysql_real_escape_string($post['from_id']),
'user_id_to'=>mysql_real_escape_string($post['to_id']),
'subject'=>mysql_real_escape_string($post['subject']),
'message'=>mysql_real_escape_string($post['body']));
$messages_obj->insert($data);
Without an emoji character found, it works fine. no problem. the problem is when an emoji character found, the data in $post (decoded data) is null.
I tried to use dummy data (line 2 in code snippet)
//$postData = '{"body":"characters here ","subject":"subject here","username":"janus","from_id":"185","to_id":"62"}';
and I succesfully inserted the emoji characters in database. I dont know why but It dont work the same when the data is from the device ($postData = file_get_contents("php://input"))
This is how I encode and post my data in client.
NSMutableDictionary *messageDetails = [[NSMutableDictionary alloc] init];
[messageDetails setObject:[loginItems objectForKey:#"user_id"] forKey:#"from_id"];
[messageDetails setObject:recipientID forKey:#"to_id"];
[messageDetails setObject:#"subject here" forKey:#"subject"];
[messageDetails setObject:newMessageField.text forKey:#"body"];
[messageDetails setObject:[loginItems objectForKey:#"username"] forKey:#"username"];
NSString *strPostData = [messageDetails JSONRepresentation];
[messageDetails release];
NSData *postData = [NSData dataWithBytes:[strPostData UTF8String] length:[strPostData length]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];

Once the data is sent to your php script you need to convert it to a multibyte string:
$content = mb_convert_encoding($content, 'UTF-8');
You can use this function:
function cb($content){
if(!mb_check_encoding($content, 'UTF-8')
OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
$content = mb_convert_encoding($content, 'UTF-8');
}
return $content;
}
Edit: The data was probably of type application/x-www-form-urlencoded for us and that function converted it correctly.

emoji characters are most likely transcoded in UNICODE, so it should be sufficient to just send, receive and manage your data in UTF-8.
When receiving with this
$postData = file_get_contents("php://input")
(I suppose that is a real URL), make sure your php script sends an Content-Encoding header (like the following, choose a MIME-type that suits you)
header("Content-Type: text/html; charset=utf-8");

Please follow following steps:
Convert Emoji characters to base64 and send to server.
On server side save base64 in database without decode.
When you want to display Emoji on Application then retrieve same base64 data from server.
Decode retrieve string and display on app.
Your Emoji character will display properly.

Related

SHA1 in Xcode and PHP with different result

I am doing some work in php try to encrypt a string by SHA1. However, I need to match the result to the result of someone else who has done in Xcode.
What he has written in Xcode is as following:
NSString *saltedPassword = [NSString stringWithFormat:#"%#%#",_myTextField.text,saltKey];
NSString *hashedPassword = nil;
unsigned char hashedPasswordData[CC_SHA1_DIGEST_LENGTH];
NSData *saltedData = [saltedPassword dataUsingEncoding:NSUTF8StringEncoding];
if (CC_SHA1([saltedData bytes], [saltedData length], hashedPasswordData)) {
hashedPassword = [[NSString alloc] initWithBytes:hashedPasswordData length:sizeof(hashedPasswordData) encoding:NSASCIIStringEncoding];
} else {
NSLog(#"ERROR: registerAction, should not be here");
abort();
}
I don't know Xcode very well. My understand of what he has done is:
concatenate the string with the key to get a new string, let's call it "string1".
encode the string1 as UTF-8,let's call the encodes string "string2"
use SHA1 to encrypt string2, length is 20 (CC_SHA1_DIGEST_LENGTH is 20,right?),let's call the encrypted string "string3"
encode "string3" as ASCII to get the final result.
So, based on my understanding above, I wrote the code in php as following:
$password.=$configs['key'];
$password=mb_convert_encoding($password, "UTF-8");
$codedPassword=sha1($password, $raw_output = TRUE);
$codedPassword=mb_convert_encoding($codedPassword, "ASCII");
echo($codedPassword);
$password is the string I want to encrypt.
But the result I got is different from the result from Xcode. We use the same key.
For example:
If the input is "123456", the output of Xcode is "Õÿ:>/
o×NVÛ²¿+(A7", the output of php is "|J? ?7b?a?? ?=?d???". (I am not sure if these are the exact string or the string itself contains some characters that cannot be displayed.)
Does anyone know how to change the php code to get the same result?(It would be perfect that your solution is about how to change the PHP code. Because I cannot change the Xcode for the moment. My job is to write the PHP code to match the Xcode's result.)
You seem to be describing:
NSData *saltedData = [saltedPassword dataUsingEncoding:NSUTF8StringEncoding];
as 'encode the string1 as UTF-8,let's call the encodes string "string2"' and doing:
$password=mb_convert_encoding($password, "UTF-8");
However that step is converting the string into a byte array, look at for instance the answers to this question String to byte array in php, it seems you should do something like this in that step:
$bytes = unpack("H*",$password);

"+" removed from string sent to server (Objective-C to PHP server)

I have a base64 string (for an in app iOS purchase) and trying to send it to my PHP server so it can validate with apple.
Problem is the string sent is not the string recieved. All the "+" marks inside my string are removed. How can I preserve my string just as it is in the client so my PHP server gets it raw.
Here is my client code
NSDictionary* post = #{#"receipt":[receipt base64EncodedStringWithOptions:0]};
//combines my post with an endpoint inside _post
for (NSString* k in _post)
{
NSLog(#"%# & %#",k,_post[k]);
postDataStr = [NSString stringWithFormat:#"%#&%#=%#", postDataStr,k,_post[k]];
}
_req = [NSMutableURLRequest requestWithURL:_url cachePolicy:0 timeoutInterval:15.0f];
[_req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[_req setHTTPMethod:#"POST"];
[_req setHTTPBody:[postDataStr dataUsingEncoding:NSUTF8StringEncoding]];
_data = [NSMutableData data];
[NSURLConnection connectionWithRequest:_req delegate:self];
And on my server its this
$appleReturnedReceipt = $this->getReceiptData($_REQUEST['receipt'], $_REQUEST['sandbox']);
When I trace out the string before and after the server touches it, all the "+" symbols are missing.
Any and all advice appreciated!
UPDATE
Thanks to the kind answer below doing this fixed the issue:
NSString* newPost = [(NSString*)_post[k] stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
You should url encode the values you want to send.

unable to retrieve json data in objective-c

I'm trying to retrieve json data from mysql database in iphone. This is my .php file.
I would like to retrieve this data so that I have some code in my .m
- (void)jsonParse{
NSString* path = #"http://phdprototype.tk/getResultData.php";
NSURL* url = [NSURL URLWithString:path];
NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary* resultDic = [dic objectForKey:#"maxid"];
NSString* recData = [resultDic objectForKey:#"recommendData"];
NSString* rData = [resultDic objectForKey:#"room"];
NSString* lData = [resultDic objectForKey:#"level"];
NSLog(#"recommendData = %#, room = %#, level = %#",recData,rData,lData);}
What I expect is to get data from recommendData, room, and level, but the debugger windows shows it did not get anything. This is what the debugger shows
2014-03-12 15:13:21.500 Semantic Museum[24289:907] recommendData = (null), room = (null), level = (null)
do I miss something??
Looks a problem with the server response headers.
I am seeing the Content-Type come back as
text/html
but it should be something like
application/json
This issue is coming because it's static text(try to View Source in your browser, it's returning extra parameter with JSON). If it's JSON, you need to check that from PHP the header value is set properly.

PHP echo received in Xcode. Are there hidden characters?

I have a PHP script on a server, all working fine for most of the thing I need it to do. I'm now setting up special user privileges for certain users.
I check if the logged in user is registered on a special user database, then return the name of their privleges or 'blank' using the following:
private function checkSpecialUser($userID)
{
$db = new DbConnect();
$result = $db->query("SELECT privelege FROM special_users WHERE userID = $userID");
if ($privName = $result->fetch_object())
{
echo $privName->privelege;
}
else
{
echo 'blank';
}
$db->close();
}
In Xcode, I have set up a simple function to return the string which is returned by the PHP script (I'll leave out the connection part since that all works fine):
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&requestError];
NSString *packName = (NSString *)[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
packName = [packName stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"packName is %#", packName);
if([packName isEqualToString:#"blank"])
{
NSLog(#"user is not special");
}
else
{
NSLog(#"User is special :-)");
}
return packName;
Now to the problem I have. If the user does not have special privileges then the first NSLog prints "packName is blank" which is exactly what I would expect. However, the if statement should then pick up that packName is equalToString "blank", which it doesn't. It always reaches 'else' and prints "User is special :-)".
I've double checked with users who ARE registered, and although it returns the string I would expect, again it doesn't trigger an equalToString response.
Do PHP echoes have hidden characters in them that I would need to remove, or am I somehow getting the value from the database incorrectly? In the database each row is simply a userID which is a varchar, and the name of their privilege which is also a varchar.
If anyone has any tips I'd be really grateful. Thanks.
Try, instead of sending back "blank", sending back nothing, or an empty string. Then, instead of matching the word "blank", test the length of the string. This will at least tell you if there are other characters in packName... you might remove more than just space whitespace, if I had to guess I'd say you've got a newline in there.

PHP blank space with 3DES Encrypt

I have a problem (server side) when i encrypt data from a client and i send to webserver with Post Method.
i Use this Method to Encrypt from a C# Client
public string Encrypt3DES(string strString)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = Encoding.GetBytes(this.Key);
DES.Mode = CipherMode.ECB;
DES.Padding = PaddingMode.Zeros;
ICryptoTransform DESEncrypt = DES.CreateEncryptor();
byte[] Buffer = encoding.GetBytes(strString);
return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
}
When i send ecrypted String to PHP if there was a + in that string, php read it with a blank space. If instead there'isnt any '+' i haven't any problem.
For Example this is a Encrypted String 4aY+na42iaPg+aep== in C# when i read in php it's
4aY a42iaPg aep== so if i decrypt if dont match with the correct word.
i use this script to start read method post
if (isset($_POST['doConvalid'])){
if ($_POST['doConvalid']=='Convalid')
{
foreach($_POST as $keys => $values) {
$data[$keys] =($values); // post variables are filtered
}
$cheking=$data['check'];
echo("Show checking = $checking"); //Here i read string with blank space instead +
Is there a way to fix it?
Yes base64 decodes + to space use this:
echo str_replace(" ","+",$_POST['string']);
http://en.wikipedia.org/wiki/Base64#URL_applications
You could replace the '+' with a different character (something not used by base64) for sending. Then replace that character back to '+' for decoding.

Categories