【发布时间】:2014-12-27 20:15:37
【问题描述】:
我已经成功实现了一个使用 twitter 登录页面,该页面显示了一个重定向到 twitter 的登录按钮,允许用户登录并批准我的应用程序,然后重定向回来。
我的问题是:有什么方法可以将其更改为函数调用结构吗? 理想情况下,通过单击index.php 的按钮调用的函数会打开一个弹出窗口,他们可以在其中登录twitter,授权应用程序,然后关闭它,而index.php本身已经收到函数的返回。
如果可能的话,我是否只需将process.php 的整个代码(减去包含)放入函数中,然后调用它?
例如,index.php 上的呼叫
$name_twitter = get_twitter_handle();
函数是
function get_twitter_handle(){
//the code of process.php
return $screen_name
}
以下是我的代码,可以完美运行,但不是函数调用格式。
Process.php 的代码
<?php
session_start();
include_once("config.php");
include_once("inc/twitteroauth.php");
if (isset($_REQUEST['oauth_token']) && $_SESSION['token'] !== $_REQUEST['oauth_token']) {
// if token is old, distroy any session and redirect user to index.php
session_destroy();
header('Location: ./index.php');
}elseif(isset($_REQUEST['oauth_token']) && $_SESSION['token'] == $_REQUEST['oauth_token']) {
// everything looks good, request access token
//successful response returns oauth_token, oauth_token_secret, user_id, and screen_name
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token'] , $_SESSION['token_secret']);
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
if($connection->http_code=='200')
{
//redirect user to twitter
$_SESSION['status'] = 'verified';
$_SESSION['request_vars'] = $access_token;
// unset no longer needed request tokens
unset($_SESSION['token']);
unset($_SESSION['token_secret']);
header('Location: ./index.php');
}else{
die("error, try again later!");
}
}else{
if(isset($_GET["denied"]))
{
header('Location: ./index.php');
die();
}
//fresh authentication
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
//received token info from twitter
$_SESSION['token'] = $request_token['oauth_token'];
$_SESSION['token_secret'] = $request_token['oauth_token_secret'];
// any value other than 200 is failure, so continue only if http code is 200
if($connection->http_code=='200')
{
//redirect user to twitter
$twitter_url = $connection->getAuthorizeURL($request_token['oauth_token']);
header('Location: ' . $twitter_url);
}else{
die("error connecting to twitter! try again later!");
}
}
?>
Index.php 代码
<?php
session_start();
include_once("config.php");
include_once("inc/twitteroauth.php");
?>
<html>
<head>
<title>Verify Twitter Handle</title>
</head>
<body>
<?php
if(isset($_SESSION['status']) && $_SESSION['status']=='verified')
{ //Success, redirected back from process.php with verified status.
//retrive variables
$screenname = $_SESSION['request_vars']['screen_name'];
echo $screenname;
echo '<br>';
}else{
//login button
echo '<a href="process.php"><img src="images/sign-in-with-twitter-l.png" width="151" height="24" border="0" /></a>';
}
?>
</body>
</html>
【问题讨论】:
-
为什么要这样做,创建函数时遇到了什么问题?
-
我需要这样做,因为这是我的业务需求。不幸的是,由于重定向等原因,我不确定如何在这种情况下创建函数。也不确定返回将如何或在何处发生..寻求一些帮助!