Execute a HTTP POST Using PHP CURL from one PHP to other.

I had a typical issue in my project where i had to pass request variables from one PHP to other with using FORM tag.
Example flow

  1. a.php gets parameters from client passes it to b.php
  2. b.php gets the params and had to pass those to c.php without people knowing.

It may seem easy but i had to scratch my hairs for a possible solution. (I am a begineer in PHP)

I thought about all of the possible solutions for solving this challenge and settled on this flow:

  1. User will submit the form, as usual from a.php.
  2. In the form processing b.php, I use CURL to execute a POST transmission to a c.php.

Code for b.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$post=array('a'=>'b','c'=>'d');
foreach($post as $key=>$value) { $post_string .= $key.'='.$value.'&'; }
rtrim($post_string,'&');
 
$ch = curl_init();
 
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,'c.php');
curl_setopt($ch,CURLOPT_POST,count($post));
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_string);
 
//execute post
$result = curl_exec($ch);
 
//close connection
curl_close($ch);

This solution worked quite well so I thought I’d share it with you. Here’s how you execute a POST using the PHP CURL library.

This entry was posted in PHP and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*