Categories
CURL PHP

Posting Binary File Via a Proxy Using PHP Curl

Don’t ask me why I had to do this, but at work today, I had the need to post files up to a remote server while running the php script behind our firewall. Basically, we needed to make files inside our firewall available on the internet. I found out that the native fopen command cannot easily be configured to post via a proxy server so I had to implement the curl solution with the help of a work mate (Thanks Dean!).

I’ve attached the code below for those who has the need to do the same thing as I. When looking at the code, take note of line 2. Most work accounts belong to a domain, but some don’t so for those not on a domain, make sure you remove DOMAIN\\. For those on a domain take note of the double slash \\ (single slash won’t work).

Happy coding!

<?php
define(“C_PROXY_SERVER_URL”,”proxy.server.com:8080″);
define(“C_PROXY_PASS”,”DOMAIN\\username:password”);
$upload_url = “http://someremotesite.com/uploader.php”;

$sample_file = “c:/Program Files/Apache Software Foundation/Apache2.2/htdocs/phpfileuploader/localuploads/FileZilla.zip”;

curl_add_file($post_array,”uploadedfile”,$sample_file);
curl_post_data($post_array, “p”, “lkjdw9087787asdhkldhasdjaksh987987jklasdf”);
curl_post_data($post_array, “file_id”, 201);
curl_post_data($post_array, “phase_id”, 201);

echo “Data to post:\n”;
print_r($post_array);
echo “\n”;
echo “upload response: \n”;
echo curl_post_request($upload_url, $post_array);

function curl_add_file(&$p_post_array, $p_name, $p_file)
{
if(!is_array($p_post_array))
$p_post_array = array();
if(!is_file($p_file) || empty($p_name) )
{
return FALSE;
}
if(!empty($mimetype))
{
$filename = “@” . $p_file . “;type=” . $mimetype;
}
else
{
$filename = “@” . $p_file;
}
$p_post_array[strtolower($p_name)] = $filename;
return TRUE;
}

function curl_post_data(&$p_post_array, $p_name, $p_data)
{
if(!is_array($p_post_array))
$p_post_array = array();
if(empty($p_name))
return FALSE;

$p_post_array[strtolower($p_name)] = $p_data;
return TRUE;
}

function curl_post_request($p_url, $p_postdata)
{
$curl_res = curl_init();
curl_setopt($curl_res, CURLOPT_URL, $p_url);
curl_setopt($curl_res, CURLOPT_HTTPPROXYTUNNEL, true);
curl_setopt($curl_res, CURLOPT_PROXY, C_PROXY_SERVER_URL);
curl_setopt($curl_res, CURLOPT_PROXYUSERPWD, C_PROXY_PASS);
curl_setopt($curl_res, CURLOPT_POST, true);
curl_setopt($curl_res, CURLOPT_POSTFIELDS, $p_postdata );
curl_setopt($curl_res, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl_res);
if($response === FALSE)
$output = curl_error($curl_res);
else
$output = $response;
curl_close ($curl_res);
return $output;
}
?>