2012-04-21 106 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