简体   繁体   中英

Send AJAX-like post request using PHP only

I'm currently working on some automatization script in PHP (No HTML!). I have two PHP files. One is executing the script, and another one receive $_POST data and returns information. The question is how from one PHP script to send POST to another PHP script, get return variables and continue working on that first script without HTML form and no redirects. I need to make requests a couple of times from first PHP file to another under different conditions and return different type of data, depending on request. I have something like this:

<?php // action.php  (first PHP script)
/* 
    doing some stuff
*/
$data = sendPost('get_info');// send POST to getinfo.php with attribute ['get_info'] and return data from another file
$mysqli->query("INSERT INTO domains (id, name, address, email)
        VALUES('".$data['id']."', '".$data['name']."', '".$data['address']."', '".$data['email']."')") or die(mysqli_error($mysqli));
/* 
    continue doing some stuff
*/
$data2 = sendPost('what_is_the_time');// send POST to getinfo.php with attribute ['what_is_the_time'] and return time data from another file

sendPost('get_info' or 'what_is_the_time'){
//do post with desired attribute
return $data; }
?>

I think i need some function that will be called with an attribute, sending post request and returning data based on request. And the second PHP file:

<?php // getinfo.php (another PHP script)
   if($_POST['get_info']){
       //do some actions 
       $data = anotherFunction();
       return $data;
   }
   if($_POST['what_is_the_time']){
       $time = time();
       return $time;
   }

   function anotherFunction(){
   //do some stuff
   return $result;
   }
?>

Thanks in advance guys.

Update: OK. the curl method is fetching the output of php file. How to just return a $data variable instead of whole output?

You should use curl . your function will be like this:

function sendPost($data) {
    $ch = curl_init();
    // you should put here url of your getinfo.php script
    curl_setopt($ch, CURLOPT_URL, "getinfo.php");
    curl_setopt($ch,  CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec ($ch); 
    curl_close ($ch); 
    return $result; 
}

Then you should call it this way:

$data = sendPost( array('get_info'=>1) );

I will give you some example class , In the below example you can use this as a get and also post call as well. I hope this will help you.!

 /*
  for your reference . Please provide argument like this,
  $requestBody = array(
                    'action' => $_POST['action'],
                    'method'=> $_POST['method'],
                    'amount'=> $_POST['amount'],
                    'description'=> $_POST['description']
                   );
 $http = "http://localhost/test-folder/source/signup.php";
 $resp = Curl::postAuth($http,$requestBody);
 */   

class Curl {
// without header
public static function post($http,$requestBody){
    
     $curl = curl_init();
        // Set some options - we are passing in a useragent too here
        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $http ,
            CURLOPT_USERAGENT => 'From Front End',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $requestBody
        ));           
        // Send the request & save response to $resp
        $resp = curl_exec($curl);
        // Close request to clear up some resources           
        curl_close($curl);
        return $resp;
}
// with authorization header
public static function postAuth($http,$requestBody,$token){
    if(!isset($token)){
        $resposne = new stdClass();
        $resposne->code = 400;
        $resposne-> message = "auth not found";
       return json_encode($resposne);
    }
     $curl = curl_init();
      $headers = array(                
            'auth-token: '.$token,
        );
        // Set some options - we are passing in a useragent too here
        curl_setopt_array($curl, array(
            CURLOPT_HTTPHEADER  => $headers ,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $http ,
            CURLOPT_USERAGENT => 'From Front End',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $requestBody
        ));
        
       
        // Send the request & save response to $resp
        $resp = curl_exec($curl);
        // Close request to clear up some resources           
        curl_close($curl);
        return $resp;
}

}

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