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);
}
4

1 回答 1

2

虽然无法确定,因为它不存在于代码中,但它被用于注入查询的 SQL 转义值......所以我的猜测是它已被定义为字符串转义函数之一的快捷别名. 例如

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

mysql_real_escape_string因为每次输入名字都会有点无聊。

转义可防止 SQL 注入攻击。参数化查询通常被认为是一种更可持续的解决方法,但在 PHP 中,这意味着更改为mysqli或 PDO 接口。

于 2012-04-21T09:58:38.387 回答