base64_decode返回null

时间:2012-08-27 08:12:13

标签: php mysql base64 apple-push-notifications

好吧,所以我在我的应用中实现了一些推送通知。我写过一些应该与MySQL DB交互的PHP。

我想将SQL中的设备令牌存储为char(64),因为我已经相信这很好(我的意思是,它应该在以后以二进制形式发送)。

在iOS方面,我这样做:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *tokenString = [deviceToken base64EncodedString];  
    NSDictionary *jsonDic = [NSDictionary dictionaryWithObjectsAndKeys:tokenString, @"Token", [NSNumber numberWithBool:YES], @"IsiDevice", [NSNumber numberWithBool:YES], @"Active", nil];
    //... http request stuff
    // what might be important is that the POST body is encoded as UTF8 (content-type set appropriately)
}

base64的东西来自Matt Gallagher的NSData + Base64。现在,在PHP方面,会发生这种情况:

// $tokenEncoded is exactly the same string as I sent from the app (type is string)
$tokenEncoded = $jsonData['Token'];

// $token becomes null! (type is string)
$token = base64_decode($tokenEncoded);

来自php.net/manual on base64_decode的返回值:

  

返回原始数据或失败时返回FALSE。返回的数据可以是二进制的。

现在,我不知道更多的PHP然后我在过去的两天里自学了;但如果文档说它应该返回FALSE或原始数据,我发现返回的值是空字符串非常混乱(因为我非常确定原始数据不是空的!)。

当base64_decoded字符串变为null时,我附加它时显然是我的整个查询字符串。这不是一个非常有说服力的查询。

所以我的问题是,我猜:为什么base64_decode会返回不应该的东西?一旦我真正从base64_decode中获取数据,我应该如何将它包含在查询中,以便将其存储在我想要的数据库中(只需追加?)?

其他信息: 我正在使用Slim Framework。我正在这条路上做这一切。 $ jsonData取自身体,如:

$jsonBody = Slim::getInstance()->request()->getBody();
$jsonData = json_decode($jsonBody, true);

从应用程序中做了一些额外的测试,只是为了确保我的应用程序的base 64实现没有任何东西可以捏造:

DLOG(@"Device token as NSData: %@", deviceToken);
NSString *base64token = [deviceToken base64EncodedString];
DLOG(@"Device token as base64: %@", base64token);
DLOG(@"Device token back from base64: %@", [NSData dataFromBase64String:base64token]);

输出:

Device token as NSData: <65625f1c c33b9480 5a46f346 8b2877d0 95e92823 33e88e91 fd3a2abf febad972>

Device token as base64: ZWJfHMM7lIBaRvNGiyh30JXpKCMz6I6R/Toqv/662XI=

Device token back from base64: <65625f1c c33b9480 5a46f346 8b2877d0 95e92823 33e88e91 fd3a2abf febad972>

2 个答案:

答案 0 :(得分:1)

请将您的查询字符串写入php中的文件,这是最好的方法是测试您的编码令牌值是否正确。 例如

<?php
$querystring=$_REQUEST['YOUR_QUERY_STRING'];
file_put_contents("query_string.txt",$querystring);
?>

这会将整个查询字符串写入“query_string.txt”文件。然后打开文件。并检查base64编码值的值。 然后复制该值并使用类似的简单程序进行检查。

<?php
   echo base64_decode("YOUR_COPIED_VALUE");
// if this works fine there is no problem. you have to go through your php code.
?> 

答案 1 :(得分:0)

在我的情况下,如果我解码字符串格式不正确,它将返回null

echo base64_decode("i'm not encode, or wrong format");//null
echo base64_decode('bWVvdyBtZW93');//meow meow

这样再次检查字符串格式

但在某些情况下:有人缺少base64_decode和base64_encode,当他们想要编码一个字符串但他们使用base64_decode所以它显示为空

相关问题