防止PHP代码多次运行

时间:2014-10-23 05:59:54

标签: javascript php html curl web

我已经看到Stack Overflow关于这个问题的所有答案,但似乎没有一个对我有用。 我有一个登录页面,当你输入你的详细信息时,下一页(.php)被调用, 它有php代码,指示它在登录失败时给出错误或在正确时显示内容。通过成功登录,我得到了进一步的GET / POST请求所需的apikey。

问题是当我刷新页面或将页面设置为表单操作时,我会收到错误,因为登录代码再次运行,期望从登录表单输入。

因此我甚至无法刷新页面,如何确保登录代码(在PHP中使用Curl实现;使用REST API)只执行一次以便我获得所需的apikey后续电话?

在下面的代码中,我希望第一个php脚本只执行一次,这样我就可以获得api密钥,第二个php代码可以在页面刷新时执行。

<?php 
  if( !defined('FOO_EXECUTED') ){    
$service_url = 'http://localhost/finals/task_manager/v1/login';
$curl = curl_init($service_url);
$curl_post_data = array(
         'email' => $_POST["iemail"],
        'password' => $_POST["ipassword"],
  );

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
    $info = curl_getinfo($curl);
    curl_close($curl);
    die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response,true);
$apiKey = $decoded["apiKey"];
if ($decoded['error'] == 'true') {

    echo $curl_response;

    die('Wrong Credentials. Try Again.');
}

echo 'response ok!';
var_export($decoded->response); define('FOO_EXECUTED', TRUE);}

?>
<?php

$service_url = 'http://localhost/finals/task_manager/v1/tasks';

$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $apiKey
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
    $info = curl_getinfo($curl);
    curl_close($curl);
    die('error occured during curl exec. Additioanl info: ' . var_export($info));
}

curl_close($curl);
$decoded1 = json_decode($curl_response,true);
if (isset($decoded1->response->status) && $decoded1->response->status == 'ERROR') {
    die('error occured: ' . $decoded1->response->errormessage);
}
echo 'response ok!';
var_export($decoded1->response);
?>

1 个答案:

答案 0 :(得分:0)

这就是我在创建课程时所说的。您可以使用FetchAuth()获取密钥,使用常规Fetch()运行其他命令。你可以根据需要定制它,但如果你有一个好的if / else设置,通过方法运行命令会更容易。这个可以变得更聪明,重复性更少,但这是个主意。

class cURLEngine
    {
        protected   $host;
        protected   $error;
        protected   $cURLInit;

        public  function Initialize($host= "",$error = 'error occured during curl exec. Additional info: ')
            {
                $this->host     =   $host;
                $this->error    =   $error;
                $this->cURLInit =   curl_init($this->host); 
            }

        public  function FetchAuth($data = array())
            {
                $curl   =   $this->cURLInit;
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                $execute = curl_exec($curl);
                if($execute === false) {
                        $info   =   curl_getinfo($curl);
                        curl_close($curl);
                        die($this->error.var_export($info));
                    }

                curl_close($curl);
                $response   =   json_decode($execute,true);

                return $response;
            }

        public  function Fetch($data = array())
            {
                $curl       =   $this->cURLInit;
                curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: ' . $_SESSION['apikey']));
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

                // If you have data to send, you can apply it in your $data array
                if(!empty($data) && is_array($data))
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

                $execute    =   curl_exec($curl);

                if ($execute === false) {
                    $info = curl_getinfo($curl);
                    curl_close($curl);
                    die($this->error . var_export($info));
                }

                curl_close($curl);
                $response = json_decode($execute,true);

                return $response;
            }
    }

// Initiate cURL Class
$cURL   =    new cURLEngine();

// Check for login
if(isset($_POST["iemail"]) && filter_var($_POST["iemail"], FILTER_VALIDATE_EMAIL)){
        // Fetch your login page
        $cURL->Initialize('http://localhost/finals/task_manager/v1/login');
        $response   =   $cURL->FetchAuth(array('email' => $_POST["iemail"],'password' => $_POST["ipassword"]));

        // If key is set, assign it the value or assign false (0)
        $apiKey     =   (isset($response['apiKey']))? $response['apiKey']:0;

        // Write failure
        if($apiKey == 0) {
                echo $response;
                die('Wrong Credentials. Try Again.');
            }
        else { ?>response ok!<?php
                $_SESSION['login']  =   true;
                $_SESSION['apikey'] =   $apiKey;
            }
    }

// Check if API Key is set
if(isset($_SESSION['apikey'])) {
        // Initialize the tasks url
        $cURL->Initialize('http://localhost/finals/task_manager/v1/tasks');
        // Fetch, you can send data by adding an array into this function
        $response   =   $cURL->Fetch();

        print_r($response);
    }