從我的應用程序發送請求到網站上的PHP腳本。向PHP腳本發送請求時出現錯誤符號
在我的應用程序中,我配置了一個如下所示的字符串:name=John&pass=apricot&constKey=12345
。
然後我對該字符串使用散列並接收類似下面的內容:blablabla25
。現在它是localKey。
然後我發送最終字符串name=John&pass=apricot&localKey=blablabla25
到PHP腳本。
在我的PHP腳本中,我使用除localKey(name=John&pass=apricot
)之外的字符串並添加存儲在PHP文件中的constKey。我再次獲得字符串name=John&pass=apricot&constKey=12345
。那很好。
然後我將該字符串進行散列並將其與localKey進行比較,即localkey blablabla25
。如果按鍵相同,那麼一切都很好。在大多數情況下,它工作正常。
但有時我會發送,例如:text=I'm happy.That's why I'm dancing
。我收到錯誤,因爲當我在Swift中對字符串進行哈希處理時,它看起來是一樣的。當我在PHP中對該字符串進行散列 - 撇號被替換爲類似的東西時 - \\\'
這裏是我的Swift和PHP文件代碼的一部分。
post = post + "key=\(sign)"
post = post.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
post = post.stringByReplacingOccurrencesOfString("+", withString: "%2B")
let postData = post.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let postLength = "\(postData?.length)"
let url: NSURL = NSURL(string: "http://google.com/admin.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.URL = url
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded" , forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData
和PHP文件
$key = NULL;
if (isset($POST['key'])) $key = mysql_real_escape_string($_POST['key']);
if (!$key)
{
exit();
}
$login = NULL;
$pass = NULL;
//////////////////////////////////////////////////////////////////////////////////////////
$pars = array();
foreach ($_POST as $par => $val)
{
$pars[$par] = mysql_real_escape_string($val);
}
ksort($pars);
$str = "";
foreach ($pars as $pr => $vl)
{
if ($pr != 'key') $str .= $pr . '=' . $vl;
}
$str .= genkey;
$sign = md5($str);
if (strcmp($key, $sign) !== 0)
{
retError(err_unknown, 'Unknown error');
exit();
}
我知道今天MD5是不好的,但是這不是問題的地步。
PHP更新的代碼
$key = NULL;
if (isset($_POST['key'])) $key = $_POST['key'];
if (!$key)
{
exit();
}
$login = NULL;
$pass = NULL;
//////////////////////////////////////////////////////////////////////////////////////////
$pars = array();
foreach ($_POST as $par => $val)
{
$pars[$par] = $val;
}
ksort($pars);
$str = "";
foreach ($pars as $pr => $vl)
{
if ($pr != 'key') $str .= $pr . '=' . $vl;
}
$str .= genkey;
$sign = md5($str);
if (strcmp($key, $sign) !== 0)
{
exit();
}
字符串,我發送給PHP腳本:
'Suggs
'H
Fgdfh'dg'hd'hgd
字符串,這是在PHP中:
\\'Suggs\n\\'H\nFgdfh\\'dg\\'hd\\'hgd
因此,新生產線是\n
和撇號是\\'
而當我在快速散列字符串沒有\n
和\\'
。這就是爲什麼哈希是不同的。 我可以簡單地刪除字符串中的新行和撇號,但它不是最好的解決方案,我想是
可能有助於添加您正在使用的PHP版本。 – miken32
是的,你是對的。下次我會:) –
在那個筆記上,你真的需要升級。現在PHP 5.3已經過了兩年了! – miken32