A Short PHP Function to Post to Any URL

I recently released a small C# library to assist in the creation of small APIs. Shortly after I found need to interact with it through PHP. So i quickly coded up this short function that allows for posting variables to the server and getting a response.

So lets just get to the code…

function postToPage($pageURL, $variableArray){
     //Set up the curl
     $ch = curl_init($pageURL);
     //The curl is set to POST the variable data
     curl_setopt($ch, CURLOPT_POST ,1);
     //We do not want a header returned
     curl_setopt($ch, CURLOPT_HEADER ,0);
     //we need the data to be returned instead of immediately echoed
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

     //create the fields string
     $fields = "";
     $first = true;
     foreach($variableArray as $name => $value){
            $fields .= "&";
        $first = false;
        $fields .= $name . "=" . $value;

     //set the post fields
     curl_setopt($ch, CURLOPT_POSTFIELDS , $fields);

     //execute the curl
     $data = curl_exec($ch);


     return $data;

The function takes two parameters. First the url of the page that is being posted to and second an associative array of values to post. Thats it! the function posts the data to the page and returns the response. Keep in mind that this function is using curl so the curl plugin needs to be installed into your php installation. Now lets take a look at using this with the provided example that comes with the C# simple web api library.

$numbers = array();
$numbers["value1"] = 7;
$numbers["value2"] = 11;
$result = postToPage("http://localhost:5000/multiply", $numbers);
echo $result;

All we do here is define the associative array that will hold our post data and send it to the api’s multiply function. The variable “$result” ends up being 77, which gets echoed to the page.

Hope it helps!