简体   繁体   中英

Prevent PHP Code from running more than once

I have seen all the answers on Stack Overflow regarding the question but none seem to be working for me. I have a login page, when you enter your details the next page (.php) gets called , it has php code which directs it to give error if login is failed or show content when correct. By successful login I get the apikey which is required for further GET/POST requests.

The problem is when I refresh the page or set the page as form action I get error as the code for login runs again, expecting inputs from a login form.

And as a result I can't even refresh the page , How to make sure that the login code (implemented in Curl in PHP ; using a REST API) is executed only once so that I get the apikey needed for subsequent calls ?

In the code below I want the first php script to get executed only one time so that I get the api key and the second php code can be executed upon page refresh.

<?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);
?>

This is sort of what I was talking about for creating a class. You can use the FetchAuth() to get your key and the regular Fetch() to run other commands. You can tailor it however you want, but if you have a good if/else set up, it's easier to run commands through methods. This one could be made smarter, with less duplication, but this is the idea.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM