Javascript 防止PHP代码多次运行

Javascript 防止PHP代码多次运行,javascript,php,html,curl,web,Javascript,Php,Html,Curl,Web,我已经看到了关于Stack Overflow的所有关于这个问题的答案,但似乎没有一个对我有用。 我有一个登录页面,当您输入详细信息时,会调用下一个页面(.php), 它有php代码,指示它在登录失败时给出错误,或者在正确时显示内容。通过成功登录,我获得了进一步get/POST请求所需的apikey 问题是,当我刷新页面或将页面设置为表单操作时,当登录代码再次运行时,我会收到错误消息,需要登录表单的输入 因此,我甚至无法刷新页面,如何确保登录代码(在PHP中用Curl实现;使用RESTAPI)只执

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

问题是,当我刷新页面或将页面设置为表单操作时,当登录代码再次运行时,我会收到错误消息,需要登录表单的输入

因此,我甚至无法刷新页面,如何确保登录代码(在PHP中用Curl实现;使用RESTAPI)只执行一次,以便获得后续调用所需的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);
?>

这就是我所说的创建类的方法。您可以使用
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);
    }
类引擎
{
受保护的$主机;
受保护的$错误;
受保护的$cURLInit;
公用函数初始化($host=”“,$error='在curl执行期间发生错误。其他信息:'))
{
$this->host=$host;
$this->error=$error;
$this->cURLInit=curl\u init($this->host);
}
公共函数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\u exec($curl);
如果($execute==false){
$info=curl\u getinfo($curl);
curl_close($curl);
die($this->error.var_export($info));
}
curl_close($curl);
$response=json_decode($execute,true);
返回$response;
}
公共函数Fetch($data=array())
{
$curl=$this->cURLInit;
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Authorization:'.$_SESSION['apikey']);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
//如果要发送数据,可以将其应用到$data数组中
if(!empty($data)&&is_数组($data))
curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
$execute=curl\u exec($curl);
如果($execute==false){
$info=curl\u getinfo($curl);
curl_close($curl);
die($this->error.var_export($info));
}
curl_close($curl);
$response=json_decode($execute,true);
返回$response;
}
}
//初始化cURL类
$cURL=新的cURLEngine();
//检查登录名
if(设置($\u POST[“iemail”])和过滤变量($\u POST[“iemail”]),过滤验证电子邮件){
//获取您的登录页面
$cURL->Initialize($cURL)http://localhost/finals/task_manager/v1/login');
$response=$cURL->FetchAuth(数组('email'=>$\u POST[“iemail”],'password'=>$\u POST[“ipassword”]);
//如果设置了键,则为其赋值或赋值为false(0)
$apiKey=(isset($response['apiKey'])?$response['apiKey']:0;
//写入失败
如果($apiKey==0){
回音$应答;
死亡('凭据错误。请重试');
}

else{?>响应ok!
if(isset($\u POST/$\u GET))://执行我的代码endif;
。如果不希望该页面能够刷新并再次提交页面,则只需使用
标题('Location:'.$\u SERVER['PHP\u SELF'])
重定向回页面并清除任何$\u GET/$\u POST变量。@Ohgodwhy登录代码只能运行一次,其他php代码可以运行任何时间。使用登录代码我可以获得用于其他php代码的apikey。使用isset将在开始时绕过登录代码,对吗?在成功登录时设置一个变量。
$\u会话['loggedIn']=true;
然后在该页面中,
if(true!=$\u会话['loggedIn'])://登录和获取api密钥的代码else://登录endif后可用的其他函数;
@Ohgodwhy谢谢您检查我更新的代码。成功登录后,我应该在第一个php代码的末尾设置变量,对吗?我曾尝试过类似的方法,使用类似于define(V,TRUE)的东西但它不起作用。你能检查一下我缺少的东西吗?一件可能对你有帮助的事情(包括前面提到的条件)是创建一个
cURL
类,你可以重用它,而无需反复手动编写
cURL
命令。这将为你节省一些时间和将来的头痛。。。