2012-04-21 107 views
1

以下代碼是使用google api訪問的一部分。 connectDb()後,有一條線

$q = sprintf("select * from users where google_user_id='%s' limit 1", r($me->id)); 

...// and more afterwards 

$q = sprintf("insert into users (google_user_id, google_email, google_name, google_picture, google_access_token, created, modified) values ('%s','%s','%s','%s','%s',now(),now());", 
    r($me->id), 
    r($me->email), 
    r($me->name), 
    r($me->picture), 
    r($me->access_token)); 

而我不知道什麼r($me->id)正在做什麼。什麼是「r」?

更詳細的代碼是在這裏:

// get profile 
$params = array(
    'client_id' => CLIENT_ID, 
    'client_secret' => CLIENT_SECRET, 
    'code' => $_GET['code'], 
    'redirect_uri' => SITE_URL.'redirect.php', 
    'grant_type' => 'authorization_code' 
); 
$url = 'https://accounts.google.com/o/oauth2/token'; 

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, $url); 
curl_setopt($curl, CURLOPT_POST, 1); 
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params)); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 

$rs = curl_exec($curl); 
curl_close($curl); 

$json = json_decode($rs); 

$url = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token='.$json->access_token; 
$me = json_decode(file_get_contents($url)); 

// enter into DB 

connectDb(); 

$q = sprintf("select * from users where google_user_id='%s' limit 1", r($me->id)); 
$rs = mysql_query($q); 
$user = mysql_fetch_assoc($rs); 

if (empty($user)) { 
    $q = sprintf("insert into users (google_user_id, google_email, google_name, google_picture, google_access_token, created, modified) values ('%s','%s','%s','%s','%s',now(),now());", 
     r($me->id), 
     r($me->email), 
     r($me->name), 
     r($me->picture), 
     r($me->access_token)); 
    $rs = mysql_query($q); 
    $q = sprintf("select * from users where id=%d", mysql_insert_id()); 
    $rs = mysql_query($q); 
    $user = mysql_fetch_assoc($rs); 
} 
+0

必須是'mysql_real_escape_string()'的包裝。應該使用PDO。 – kapa 2012-04-21 09:58:28

+0

我會說在腳本或包含文件中的某處定義的函數。這對於一個功能來說是一個很差的名字。 – Toto 2012-04-21 09:58:30

+0

這是一個PHP函數,我猜。不是本地函數,所以這個函數的代碼應該放在某個地方。檢查你的包含找到它或使用你的IDE。另外我想這個函數可能會包含一些原生的php函數,如「htmlspecialchars」或同一個家族。 – hornetbzz 2012-04-21 10:00:51

回答

2

雖然我們不能肯定,因爲它是不存在的代碼,它被用來注入查詢SQL轉義值...所以我的猜測是它已被定義爲字符串轉義函數之一的快捷方式別名。例如

function r($s) { 
    return mysql_real_escape_string($s); 
} 

因爲輸入名稱mysql_real_escape_string每次都會有點無聊。

轉義可防止SQL注入攻擊。參數化查詢通常被認爲是解決這個問題的更可持續的方式,但是在PHP中,這意味着更改爲mysqli或PDO接口。

+1

謝謝,我錯過了另一個文件,我發現函數r($ s){mysql}返回mysql_real_escape_string($ s); } – shin 2012-04-21 10:01:03

+0

因此,他們只是用一個不言自明的功能,如果有點冗長的名字,並用一個短而無用的名稱包裝它?可怕的編碼習慣。 – 2012-04-21 12:18:46

+1

基本上是的。我認爲一個非常常用的函數有這樣一個簡短的名字是沒有道理的,只要它聲明清楚 - 我經常使用'h'作爲'echo htmlspecialchars'的快捷方式。儘管如此,「r」仍然是一個奇怪的名字。不得不經常使用一個函數,以至於只需要給它一個小小的名字就可能是一個跡象,說明框架應該自動處理是錯誤的:在這種情況下,明確的參數化是更好的答案;在'htmlspecialchars'的情況下,這是一個失敗的模板語法,它不會被默認轉義。 – bobince 2012-04-24 14:41:03