PHP use socks5 proxy with fsockopen ssl - php

I'm trying to open a HTTPs page using php through a socks5 proxy, but I can't use curl, because I have to be able to read each line of the response.
To do that, I'm using this PHP class: http://www.phpkode.com/source/s/socksed/socksed.php, but if I start a connection on port 443, and send a HTTP POST request with params, nginx sends me back this message:
400 the plain http request was sent to https port
I tried to change that part of the code #fsockopen("tcp:// to #fsockopen("ssl://, but then I can't open the page.

If you're ok with using curl, the following should help achieve what you're after:
// create the curl buffered reader object with a connection to a socks5 proxy on localhost port 8888
$cbr = new \CurlBufferedReader(array(
CURLOPT_PROXY => 'socks5://127.0.0.1:8888',
// disable ssl certificate verification, you probably don't need this so I've commented it out
//CURLOPT_SSL_VERIFYPEER => false
));
// gets the body at the url up until the point specified by the callback function
$body = $cbr->get('https://stackoverflow.com/questions/24249029/php-use-socks5-proxy-with-fsockopen-ssl',
/**
* The callback function to determine whether to continue reading the body sent by the remote server
* #param string $body
*/
function (&$body) {
if (($off = strpos($body, "\nTo do that,")) !== false) {
// truncate body so that we have everything up until the newline before the string "To do that,"
$body = substr($body, 0, $off + 1);
}
return $off === false; // continue reading while true
});
echo $body;
And the related class:
class CurlBufferedReader {
private $body = false;
private $callback;
private $ch;
public function __construct(array $curlopts = array()) {
$this->ch = curl_init();
curl_setopt_array($this->ch, $curlopts + array(
// general curl options
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_RETURNTRANSFER => true,
// specific options to abort the connection early
CURLOPT_BUFFERSIZE => 8192,
CURLOPT_WRITEFUNCTION => array($this, 'writeFunction')
));
}
public function get($url, $callback = null) {
curl_setopt($this->ch, CURLOPT_URL, $url);
$this->callback = $callback;
if (!($success = $this->exec())) {
// errno 23 when aborted by the client
if ($this->getErrno() !== 23) {
$this->body = false;
}
}
return $this->body;
}
public function getBody() {
return $this->body;
}
public function getError() {
return curl_error($this->ch);
}
public function getErrno() {
return curl_errno($this->ch);
}
private function exec() {
$status = curl_exec($this->ch);
$this->callback = null;
return $status;
}
private function writeFunction($ch, $buffer) {
$this->body .= $buffer;
if ($this->callback && !call_user_func_array($this->callback, array(&$this->body))) {
$written = -1; // user callback requested abort
} else {
$written = strlen($buffer);
}
return $written;
}
}
It works by reading 8,192 bytes at a time from the remote server. A user function is called to read the total body received upon each read event. The user function must return false when it wishes to abort the connection. It's also important to note that $body is a reference. Therefore any changes you make to it will affect the string received by the CurlBufferedReader::get method.

Try this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_PROXYTYPE, 7);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $url);
$curl_scraped_page = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

Related

Php Goo.gl Url Shortener In Mysql_Fetch_Array

im trying to use Goo.gl class(url shortener) in my mysql query.
im getting 10 line from database via mysql_fetch_array; and need to create url for all lines.
as like this:
while ($f = mysql_fetch_array($q)) {
$short_url = $googl->shorten("http://www.example.com/$f[news]");
echo $short_url; }
but the script creates url, for only the first one.
do you have any ide, how can i use this script for multiple url convert (to create url for all mysql_query line).
this is the script i use:
class Googl
{
public $extended;
private $target;
private $apiKey;
private $ch;
private static $buffer = array();
function __construct($apiKey = null) {
# Extended output mode
$extended = false;
# Set Google Shortener API target
$this->target = 'https://www.googleapis.com/urlshortener/v1/url?';
# Set API key if available
if ( $apiKey != null ) {
$this->apiKey = $apiKey;
$this->target .= 'key='.$apiKey.'&';
}
# Initialize cURL
$this->ch = curl_init();
# Set our default target URL
curl_setopt($this->ch, CURLOPT_URL, $this->target);
# We don't want the return data to be directly outputted, so set RETURNTRANSFER to true
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
}
public function shorten($url, $extended = false) {
# Check buffer
if ( !$extended && !$this->extended && !empty(self::$buffer[$url]) ) {
return self::$buffer[$url];
}
# Payload
$data = array( 'longUrl' => $url );
$data_string = '{ "longUrl": "'.$url.'" }';
# Set cURL options
curl_setopt($this->ch, CURLOPT_POST, count($data));
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, Array('Content-Type: application/json'));
if ( $extended || $this->extended) {
return json_decode(curl_exec($this->ch));
} else {
$ret = json_decode(curl_exec($this->ch))->id;
self::$buffer[$url] = $ret;
return $ret;
}
}
public function expand($url, $extended = false) {
# Set cURL options
curl_setopt($this->ch, CURLOPT_HTTPGET, true);
curl_setopt($this->ch, CURLOPT_URL, $this->target.'shortUrl='.$url);
if ( $extended || $this->extended ) {
return json_decode(curl_exec($this->ch));
} else {
return json_decode(curl_exec($this->ch))->longUrl;
}
}
function __destruct() {
# Close the curl handle
curl_close($this->ch);
# Nulling the curl handle
$this->ch = null;
}
}$googl = new Googl();

cURL login into ebay.co.uk [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I've been trying for some time now to use cURL to login to eBay.co.uk. The cookies are being set and the post data is being sent correctly however I am not sure that the cookie file is being read again or even set correctly for that matter since I'm getting a page from eBay that says I need to enable cookies in my browser.
Here is the cURL class I'm using:
class Curl {
private $ch;
private $cookie_path;
private $agent;
public function __construct($userId) {
$this->cookie_path = dirname(realpath(basename($_SERVER['PHP_SELF']))).'/cookies/' . $userId . '.txt';
$this->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
}
private function init() {
$this->ch = curl_init();
}
private function close() {
curl_close ($this->ch);
}
private function setOptions($submit_url) {
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
curl_setopt($this->ch, CURLOPT_USERAGENT, $this->agent);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookie_path);
curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookie_path);
}
public function curl_cookie_set($submit_url) {
$this->init();
$this->setOptions($submit_url);
$result = curl_exec ($this->ch);
$this->close();
return $result;
}
public function curl_post_request($referer, $submit_url, $data) {
$this->init();
$this->setOptions($submit_url);
$post = http_build_query($data);
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($this->ch, CURLOPT_REFERER, $referer);
$result = curl_exec ($this->ch);
$this->close();
return $result;
}
public function curl_clean() {
// cleans and closes the curl connection
if (file_exists($this->cookie_path)) {
unlink($this->cookie_path);
}
if ($this->ch != '') {
curl_close ($this->ch);
}
}
}
Here is the test script, the login details are for a throwaway account, so feel free to test with them:
$curl = new Curl(md5(1)); //(md5($_SESSION['userId']));
$referer = 'http://ebay.co.uk';
$submit_url = "http://signin.ebay.co.uk/aw-cgi/eBayISAPI.dll";
$data['userid'] = "VitoGambino-us";
$data['pass'] = "P0wqw12vi";
$data['MfcISAPICommand'] = 'SignInWelcome';
$data['siteid'] = '0';
$data['co_partnerId'] = '2';
$data['UsingSSL'] = '0';
$data['ru'] = '';
$data['pp'] = '';
$data['pa1'] = '';
$data['pa2'] = '';
$data['pa3'] = '';
$data['i1'] = '-1';
$data['pageType'] = '-1';
$curl->curl_cookie_set($referer);
$result = $curl->curl_post_request($referer, $submit_url, $data);
echo $result;
Here is what the cookie files contents are:
# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.
www.ebay.co.uk FALSE / FALSE 0 JSESSIONID BDE9B23B829CA7DF2CC4D5880F5173A6
.ebay.co.uk TRUE / FALSE 0 ebay %5Esbf%3D%23%5Ecv%3D15555%5E
.ebay.co.uk TRUE / FALSE 1431871451 dp1 bu1p/QEBfX0BAX19AQA**53776c5b^
#HttpOnly_.ebay.co.uk TRUE / FALSE 0 s CgAD4ACBRl4pbYjJjZDk1YTAxM2UwYTU2YjYzYzRhYmU0ZmY2ZjcyODYBSgAXUZeKWzUxOTYzOGI5LjMuMS43LjY2LjguMC4xuMWzLg**
.ebay.co.uk TRUE / FALSE 1400335451 nonsession CgADLAAFRlj/jMgDKACBa/DpbYjJjZDk1YTAxM2UwYTU2YjYzYzRhYmU0ZmY2ZjcyODcBTAAXU3dsWzUxOTYzOGI5LjMuMS42LjY1LjEuMC4xhVUTMQ**
.ebay.co.uk TRUE / FALSE 1526479451 lucky9 4551358
I was able to figure it out.
eBay uses a pretty tricky method for logging in. It's a combination of cookies, hidden fields and a javascript redirect after successful login.
Here's how I solved it.
Newly modified class:
class Curl {
private $ch;
private $cookie_path;
private $agent;
// userId will be used later to keep multiple users logged
// into ebay site at one time.
public function __construct($userId) {
$this->cookie_path = dirname(realpath(basename($_SERVER['PHP_SELF']))).'/cookies/' . $userId . '.txt';
$this->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
}
private function init() {
$this->ch = curl_init();
}
private function close() {
curl_close ($this->ch);
}
// Set cURL options
private function setOptions($submit_url) {
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
curl_setopt($this->ch, CURLOPT_USERAGENT, $this->agent);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookie_path);
curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookie_path);
}
// Grab initial cookie data
public function curl_cookie_set($submit_url) {
$this->init();
$this->setOptions($submit_url);
curl_exec ($this->ch);
echo curl_error($this->ch);
}
// Grab hidden fields
public function get_form_fields($submit_url) {
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
$result = curl_exec ($this->ch);
echo curl_error($this->ch);
return $this->getFormFields($result);
}
// Send login data
public function curl_post_request($referer, $submit_url, $data) {
$post = http_build_query($data);
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($this->ch, CURLOPT_REFERER, $referer);
$result = curl_exec ($this->ch);
echo curl_error($this->ch);
$this->close();
return $result;
}
// Show the logged in "My eBay" or any other page
public function show_page( $submit_url) {
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
$result = curl_exec ($this->ch);
echo curl_error($this->ch);
return $result;
}
// Used to parse out form
private function getFormFields($data) {
if (preg_match('/(<form name="SignInForm".*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('Form not found.');
}
}
// Used to parse out hidden field names and values
private function getInputs($form) {
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
// Destroy cookie and close curl.
public function curl_clean() {
// cleans and closes the curl connection
if (file_exists($this->cookie_path)) {
unlink($this->cookie_path);
}
if ($this->ch != '') {
curl_close ($this->ch);
}
}
}
The actual code in use:
$curl = new Curl(md5(1)); //(md5($_SESSION['userId']));
$referer = 'http://ebay.com';
$formPage = 'http://signin.ebay.com/aw-cgi/eBayISAPI.dll?SignIn';
// Grab cookies from main page, ebay.com
$curl->curl_cookie_set($referer);
// Grab the hidden form fields and then set UsingSSL = 0
// Login with credentials and hidden fields
$data = $curl->get_form_fields($formPage);
$data['userid'] = "";
$data['pass'] = "";
$data['UsingSSL'] = '0';
// Post data to login page. Don't echo this result, there's a
// javascript redirect. Just do this to save login cookies
$formLogin = "https://signin.ebay.com/ws/eBayISAPI.dll?co_partnerId=2&siteid=3&UsingSSL=0";
$curl->curl_post_request($referer, $formLogin, $data);
// Use login cookies to load the "My eBay" page, viola, you're logged in.
$result = $curl->show_page('http://my.ebay.com/ws/eBayISAPI.dll?MyeBay');
// take out Javascript so it won't redirect to actualy ebay site
echo str_replace('<script', '<', $result);
I used some of the code posted here, thanks to drew010!

Faking Post Request with PHP Curl - Rejection

I am trying to build a script that posts information into the RoyalMail tracking system and extracts the output.
What I currently have is getting an error from their server - see the link, somehow it is detecting that I am not using their website as per normal and throwing me an error.
Things I think I have taken into account:
Using an exact copy of their form by parsing it beforehand (the post parameters)
Saving the cookies between each request
Accepting redirect headers
Providing a refer header that is actually valid (the previously visited page)
Does anyone know anything else I need to check or can figure out what I am doing wrong?
A full copy of the source is at EDIT: please see my answer below
Websites usually use 2 ways to detect if you are a human or a bot: HTTP REFERER and USER AGENT. I suggest you use Curl it specified user agent and referer (replace 'http://something/' with real URL of a page you would normally visit before navigating to the url you want to download with PHP):
<?php
$url = 'http://track2.royalmail.com/portal/rm/track';
$html = file_get_contents2($url, '');
$post['_dyncharset'] = 'ISO-8859-1';
$post['trackConsigniaPage'] = 'track';
$post['/rmg/track/RMTrackFormHandler.value.searchCompleteUrl'] = '/portal/rm/trackresults?catId=22700601&pageId=trt_rmresultspage';
$post['_D:/rmg/track/RMTrackFormHandler.value.searchCompleteUrl'] = '';
$post['/rmg/track/RMTrackFormHandler.value.invalidInputUrl'] = '/portal/rm/trackresults?catId=22700601&pageId=trt_rmresultspage&keyname=track_blank';
$post['_D:/rmg/track/RMTrackFormHandler.value.invalidInputUrl'] = '';
$post['/rmg/track/RMTrackFormHandler.value.searchBusyUrl'] = '/portal/rm/trackresults?catId=22700601&pageId=trt_busypage&keyname=3E_track';
$post['_D:/rmg/track/RMTrackFormHandler.value.searchBusyUrl'] = '';
$post['/rmg/track/RMTrackFormHandler.value.searchWaitUrl'] = '/portal/rm/trackresults?catId=22700601&timeout=true&pageId=trt_timeoutpage&keyname=3E_track';
$post['_D:/rmg/track/RMTrackFormHandler.value.searchWaitUrl'] = '';
$post['/rmg/track/RMTrackFormHandler.value.keyname'] = '3E_track';
$post['_D:/rmg/track/RMTrackFormHandler.value.keyname'] = '';
$post['/rmg/track/RMTrackFormHandler.value.previousTrackingNumber'] = '';
$post['_D:/rmg/track/RMTrackFormHandler.value.previousTrackingNumber'] = '';
$post['/rmg/track/RMTrackFormHandler.value.trackingNumber'] = 'ZW791944749GB';
$post['_D:/rmg/track/RMTrackFormHandler.value.trackingNumber'] = '';
$post['/rmg/track/RMTrackFormHandler.track.x'] = '50';
$post['/rmg/track/RMTrackFormHandler.track.y'] = '14';
$post['_D:/rmg/track/RMTrackFormHandler.track'] = '';
$post['/rmg/track/RMTrackFormHandler.value.day'] = '19';
$post['_D:/rmg/track/RMTrackFormHandler.value.day'] = '';
$post['/rmg/track/RMTrackFormHandler.value.month'] = '5';
$post['_D:/rmg/track/RMTrackFormHandler.value.month'] = '';
$post['/rmg/track/RMTrackFormHandler.value.year'] = '2012';
$post['_D:/rmg/track/RMTrackFormHandler.value.year'] = '';
$post['_DARGS'] = '/portal/rmgroup/apps/templates/html/rm/rmTrackResultPage.jsp';
$url2 = 'http://track2.royalmail.com/portal/rm?_DARGS=/portal/rmgroup/apps/templates/html/rm/rmTrackAndTraceForm.jsp';
$html2 = file_get_contents2($url2, $url, $post);
echo $html2;
function file_get_contents2($address, $referer, $post = false)
{
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $address);
curl_setopt($c, CURLOPT_USERAGENT, $useragent);
curl_setopt($c, CURLOPT_HEADER, 0);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
if ($post)
{
$postF = http_build_query($post);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $postF);
}
curl_setopt($c, CURLOPT_COOKIEJAR, 'cookie.txt');
//curl_setopt($c, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($c, CURLOPT_REFERER, $referer);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
if (!$data = curl_exec($c))
{
return false;
}
return $data;
}
The above updated code returned me:
Item ZW791944749GB was posted at 1 High Street RG17 9TJ on 19/05/12 and is being progressed through our network for delivery.
So it seems it works.
I have now fixed it, the problem was with PHP curl and following redirects, it seems that it doesn't always post the request data and sends a GET request when following.
To deal with this I disabled curl follow location with curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); and then built a follow location system myself that works recursively. Essentially it extracts the location header from the response, checks for a 301 or a 302 and then runs the method again as required.
This means the information will definitely be POSTED again.
I also improved the user agent string, simply copying my current one on the basis it won't be blocked for a long while as in 2012 it is in active use!
Here is a final copy of the curl class (in case the link dies - been down voted for that in the past) which is working:
/**
* Make a curl request respecting redirects
* Also supports posts
*/
class pegCurlRequest {
private $url, $postFields = array(), $referer = NULL, $timeout = 3;
private $debug = false, $postString = "";
private $curlInfo = array();
private $content = "";
private $response_meta_info = array();
static $cookie;
function __construct($url, $postFields = array(), $referer = NULL, $timeout = 3) {
$this->setUrl($url);
$this->setPost($postFields);
$this->setReferer($referer);
$this->setTimeout($timeout);
if(empty(self::$cookie)) self::$cookie = tempnam("/tmp", "pegCurlRequest"); //one time cookie
}
function setUrl($url) {
$this->url = $url;
}
function setTimeout($timeout) {
$this->timeout = $timeout;
}
function setPost($postFields) {
if(is_array($postFields)) {
$this->postFields = $postFields;
}
$this->updatePostString();
}
function updatePostString() {
//Cope with posting
$this->postString = "";
if(!empty($this->postFields)) {
foreach($this->postFields as $key=>$value) { $this->postString .= $key.'='.$value.'&'; }
$this->postString= rtrim($this->postString,'&'); //Trim off the waste
}
}
function setReferer($referer) {
//Set a referee either specified or based on the url
$this->referer = $referer;
}
function debugInfo() {
//Debug
if($this->debug) {
echo "<table><tr><td colspan='2'><b><u>Pre Curl Request</b><u></td></tr>";
echo "<tr><td><b>URL: </b></td><td>{$this->url}</td></tr>";
if(!empty(self::$cookie)) echo "<tr><td><b>Cookie String: </b></td><td>".self::$cookie."</td></tr>";
if(!empty($this->referer)) echo "<tr><td><b>Referer: </b></td><td>".$this->referer."</td></tr>";
if(!empty($this->postString)) echo "<tr><td><b>Post String: </b></td><td>".$this->postString."</td></tr>";
if(!empty($this->postFields)) {
echo "<tr><td><b>Post Values:</b></td><td><table>";
foreach($this->postFields as $key=>$value)
echo "<tr><td>$key</td><td>$value</td></tr>";
echo "</table>";
}
echo "</td></tr></table><br />\n";
}
}
function debugFurtherInfo() {
//Debug
if($this->debug) {
echo "<table><tr><td colspan='2'><b><u>Post Curl Request</b><u></td></tr>";
echo "<tr><td><b>URL: </b></td><td>{$this->url}</td></tr>";
if(!empty($this->referer)) echo "<tr><td><b>Referer: </b></td><td>".$this->referer."</td></tr>";
if(!empty($this->curlInfo)) {
echo "<tr><td><b>Curl Info:</b></td><td><table>";
foreach($this->curlInfo as $key=>$value)
echo "<tr><td>$key</td><td>$value</td></tr>";
echo "</table>";
}
echo "</td></tr></table><br />\n";
}
}
/**
* Make the actual request
*/
function makeRequest($url=NULL) {
//Shorthand request
if(!is_null($url))
$this->setUrl($url);
//Output debug info
$this->debugInfo();
//Using a shared cookie
$cookie = self::$cookie;
//Setting up the starting information
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 Safari/536.11" );
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
//register a callback function which will process the headers
//this assumes your code is into a class method, and uses $this->readHeader as the callback //function
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$this,'readHeader'));
//Some servers (like Lighttpd) will not process the curl request without this header and will return error code 417 instead.
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
//Referer
if(empty($this->referer)) {
curl_setopt($ch, CURLOPT_REFERER, dirname($this->url));
} else {
curl_setopt($ch, CURLOPT_REFERER, $this->referer);
}
//Posts
if(!empty($this->postFields)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postString);
}
//Redirects, transfers and timeouts
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
//Debug
if($this->debug) {
curl_setopt($ch, CURLOPT_VERBOSE, true); // logging stuffs
curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
}
//Get the content and the header info
$content = curl_exec($ch);
$response = curl_getinfo($ch);
//get the default response headers
$headers = curl_getinfo($ch);
//add the headers from the custom headers callback function
$this->response_meta_info = array_merge($headers, $this->response_meta_info);
curl_close($ch); //be nice
//Curl info
$this->curlInfo = $response;
//Output debug info
$this->debugFurtherInfo();
//Are we being redirected?
if ($response['http_code'] == 301 || $response['http_code'] == 302) {
$location = $this->getHeaderLocation();
if(!empty($location)) { //the location exists
$this->setReferer($this->getTrueUrl()); //update referer
return $this->makeRequest($location); //recurse to location
}
}
//Is there a javascript redirect on the page?
elseif (preg_match("/window\.location\.replace\('(.*)'\)/i", $content, $value) ||
preg_match("/window\.location\=\"(.*)\"/i", $content, $value)) {
$this->setReferer($this->getTrueUrl()); //update referer
return $this->makeRequest($value[1]); //recursion
} else {
$this->content = $content; //set the content - final page
}
}
/**
* Get the url after any redirection
*/
function getTrueUrl() {
return $this->curlInfo['url'];
}
function __toString() {
return $this->content;
}
/**
* CURL callback function for reading and processing headers
* Override this for your needs
*
* #param object $ch
* #param string $header
* #return integer
*/
private function readHeader($ch, $header) {
//This is run for every header, use ifs to grab and add
$location = $this->extractCustomHeader('Location: ', '\n', $header);
if ($location) {
$this->response_meta_info['location'] = trim($location);
}
return strlen($header);
}
private function extractCustomHeader($start,$end,$header) {
$pattern = '/'. $start .'(.*?)'. $end .'/';
if (preg_match($pattern, $header, $result)) {
return $result[1];
} else {
return false;
}
}
function getHeaders() {
return $this->response_meta_info;
}
function getHeaderLocation() {
return $this->response_meta_info['location'];
}
}
Well first of all, you are talking about the Royal Mail. So I'm not sure if this simple little trick would trip them up...
But what you could try is spoofing your user agent with a quick ini_set() -
ini_set('user_agent', 'Mozilla/5.0 (X11; CrOS i686 1660.57.0) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.46 Safari/535.19'
That's an Ubuntu chrome user agent string.
The cURL user agent string would look quite different. For example:
curl/7.15.5 (i686-redhat-linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
It's a long shot - but they might be rejecting requests that are not originating from recognized browsers.

Paypal NVP with php error

I am trying to get up and running using Paypal's NVP interface for my website to process my custom cart. I've downloaded their sample code (here) and have tried to run unaltered without success. Any function I choose (e.g. express checkout sale) gives the curl_errno() error: Error Number: 3 Error Message: No URL set! I have tried this both on localhost and on my hosted site.
hash_call() is the function processing the call to Paypal. The code which calls hash_call() is also included below.Their code that sets urls is:
$returnURL =urlencode($url.'/ReviewOrder.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);
$cancelURL =urlencode("$url/SetExpressCheckout.php?paymentType=$paymentType" );
I thought the cancelURL line looked off and modified it to:
$cancelURL =urlencode($url.'/SetExpressCheckout.php?paymentType='.$paymentType );
Neither have worked. Any help would be appreciated. I've never worked with curl.
require_once 'CallerService.php';
session_start();
if(! isset($_REQUEST['token'])) {
/* The servername and serverport tells PayPal where the buyer
should be directed back to after authorizing payment.
In this case, its the local webserver that is running this script
Using the servername and serverport, the return URL is the first
portion of the URL that buyers will return to after authorizing payment
*/
$serverName = $_SERVER['SERVER_NAME'];
$serverPort = $_SERVER['SERVER_PORT'];
$url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);
$currencyCodeType=$_REQUEST['currencyCodeType'];
$paymentType=$_REQUEST['paymentType'];
$personName = $_REQUEST['PERSONNAME'];
$SHIPTOSTREET = $_REQUEST['SHIPTOSTREET'];
$SHIPTOCITY = $_REQUEST['SHIPTOCITY'];
$SHIPTOSTATE = $_REQUEST['SHIPTOSTATE'];
$SHIPTOCOUNTRYCODE = $_REQUEST['SHIPTOCOUNTRYCODE'];
$SHIPTOZIP = $_REQUEST['SHIPTOZIP'];
$L_NAME0 = $_REQUEST['L_NAME0'];
$L_AMT0 = $_REQUEST['L_AMT0'];
$L_QTY0 = $_REQUEST['L_QTY0'];
$L_NAME1 = $_REQUEST['L_NAME1'];
$L_AMT1 = $_REQUEST['L_AMT1'];
$L_QTY1 = $_REQUEST['L_QTY1'];
/* The returnURL is the location where buyers return when a
payment has been succesfully authorized.
The cancelURL is the location buyers are sent to when they hit the
cancel button during authorization of payment during the PayPal flow
*/
$returnURL =urlencode($url.'/ReviewOrder.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);
$cancelURL =urlencode($url.'/SetExpressCheckout.php?paymentType='.$paymentType );
/* Construct the parameter string that describes the PayPal payment
the varialbes were set in the web form, and the resulting string
is stored in $nvpstr
*/
$itemamt = 0.00;
$itemamt = $L_QTY0*$L_AMT0+$L_AMT1*$L_QTY1;
$amt = 5.00+2.00+1.00+$itemamt;
$maxamt= $amt+25.00;
$nvpstr="";
/*
* Setting up the Shipping address details
*/
$shiptoAddress = "&SHIPTONAME=$personName&SHIPTOSTREET=$SHIPTOSTREET&SHIPTOCITY=$SHIPTOCITY&SHIPTOSTATE=$SHIPTOSTATE&SHIPTOCOUNTRYCODE=$SHIPTOCOUNTRYCODE&SHIPTOZIP=$SHIPTOZIP";
$nvpstr="&ADDRESSOVERRIDE=1$shiptoAddress&L_NAME0=".$L_NAME0."&L_NAME1=".$L_NAME1."&L_AMT0=".$L_AMT0."&L_AMT1=".$L_AMT1."&L_QTY0=".$L_QTY0."&L_QTY1=".$L_QTY1."&MAXAMT=".(string)$maxamt."&AMT=".(string)$amt."&ITEMAMT=".(string)$itemamt."&CALLBACKTIMEOUT=4&L_SHIPPINGOPTIONAMOUNT1=8.00&L_SHIPPINGOPTIONlABEL1=UPS Next Day Air&L_SHIPPINGOPTIONNAME1=UPS Air&L_SHIPPINGOPTIONISDEFAULT1=true&L_SHIPPINGOPTIONAMOUNT0=3.00&L_SHIPPINGOPTIONLABEL0=UPS Ground 7 Days&L_SHIPPINGOPTIONNAME0=Ground&L_SHIPPINGOPTIONISDEFAULT0=false&INSURANCEAMT=1.00&INSURANCEOPTIONOFFERED=true&CALLBACK=https://www.ppcallback.com/callback.pl&SHIPPINGAMT=8.00&SHIPDISCAMT=-3.00&TAXAMT=2.00&L_NUMBER0=1000&L_DESC0=Size: 8.8-oz&L_NUMBER1=10001&L_DESC1=Size: Two 24-piece boxes&L_ITEMWEIGHTVALUE1=0.5&L_ITEMWEIGHTUNIT1=lbs&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType."&PAYMENTACTION=".$paymentType;
/* Make the call to PayPal to set the Express Checkout token
If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment. If an error occured, show the
resulting errors
*/
$resArray=hash_call("SetExpressCheckout",$nvpstr);
*********************************************************************************
/**
* hash_call: Function to perform the API call to PayPal using API signature
* #methodName is name of API method.
* #nvpStr is nvp string.
* returns an associtive array containing the response from the server.
*/
function hash_call($methodName,$nvpStr)
{
//declaring of global variables
global $API_Endpoint,$version,$API_UserName,$API_Password,$API_Signature,$nvp_Header, $subject, $AUTH_token,$AUTH_signature,$AUTH_timestamp;
// form header string
$nvpheader=nvpHeader();
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
//WARNING: this would prevent curl from detecting a 'man in the middle' attack
$ch = curl_init();
//curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
//curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt ($ch, CURLOPT_CAINFO, "c:/xampp/apache/cacert.pem");
//in case of permission APIs send headers as HTTPheders
if(!empty($AUTH_token) && !empty($AUTH_signature) && !empty($AUTH_timestamp))
{
$headers_array[] = "X-PP-AUTHORIZATION: ".$nvpheader;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_array);
curl_setopt($ch, CURLOPT_HEADER, false);
}
else
{
$nvpStr=$nvpheader.$nvpStr;
}
//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
//Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
if(USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);
//check if version is included in $nvpStr else include the version.
if(strlen(str_replace('VERSION=', '', strtoupper($nvpStr))) == strlen($nvpStr)) {
$nvpStr = "&VERSION=" . urlencode($version) . $nvpStr;
}
$nvpreq="METHOD=".urlencode($methodName).$nvpStr;
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
//getting response from server
$response = curl_exec($ch);
//convrting NVPResponse to an Associative Array
$nvpResArray=deformatNVP($response);
$nvpReqArray=deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch)) {
// moving to display page to display curl errors
$_SESSION['curl_error_no']=curl_errno($ch) ;
$_SESSION['curl_error_msg']=curl_error($ch);
$location = "APIError.php";
header("Location: $location");
} else {
//closing the curl
curl_close($ch);
}
return $nvpResArray;
}
Try this class,
<?php
class ZC_Paypal
{
public $API_USERNAME;
public $API_PASSWORD;
public $API_SIGNATURE='xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
public $API_ENDPOINT;
public $USE_PROXY;
public $PROXY_HOST;
public $PROXY_PORT;
public $PAYPAL_URL;
public $VERSION;
public $NVP_HEADER;
public $SSLCERTPATH;
function __construct($PROXY_HOST, $PROXY_PORT, $IS_ONLINE = FALSE, $USE_PROXY = FALSE, $VERSION = '51.0', $api_url)
{
/*$this->API_USERNAME = $API_USERNAME;
$this->API_PASSWORD = $API_PASSWORD;
$this->API_SIGNATURE = $API_SIGNATURE;*/
//$this->API_ENDPOINT = 'https://api-3t.sandbox.paypal.com/nvp';
$this->API_ENDPOINT = $api_url;
$this->USE_PROXY = $USE_PROXY;
if($this->USE_PROXY == true)
{
$this->PROXY_HOST = $PROXY_HOST;
$this->PROXY_PORT = $PROXY_PORT;
}
else
{
$this->PROXY_HOST = '127.0.0.1';
$this->PROXY_PORT = '808';
}
if($IS_ONLINE == FALSE)
{
$this->PAYPAL_URL = 'https://api-3t.sandbox.paypal.com/nvp';
}
else
{
$this->PAYPAL_URL = 'https://api-3t.paypal.com/nvp';
}
$this->VERSION = $VERSION;
}
function hash_call($methodName,$nvpStr,$uname,$pwd,$api_url,$sslcerpath)
{
$this->API_ENDPOINT = $api_url;
$this->API_PASSWORD = $pwd;
$this->API_USERNAME = $uname;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->API_ENDPOINT);
//curl_setopt($ch, CURLOPT_SSLCERT, $sslcerpath);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
if($this->USE_PROXY)
{
curl_setopt ($ch, CURLOPT_PROXY, $this->PROXY_HOST.":".$this->PROXY_PORT);
}
$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($this->VERSION)."&PWD=".urlencode($this->API_PASSWORD)."&USER=".urlencode($this->API_USERNAME)."&SIGNATURE=".urlencode($this->API_SIGNATURE).$nvpStr;
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
$response = curl_exec($ch);
$nvpResArray=$this->deformatNVP($response);
$nvpReqArray=$this->deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch))
{
die("CURL send a error during perform operation: ".curl_errno($ch));
}
else
{
curl_close($ch);
}
return $nvpResArray;
}
function deformatNVP($nvpstr)
{
$intial=0;
$nvpArray = array();
while(strlen($nvpstr))
{
$keypos= strpos($nvpstr,'=');
$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
$keyval=substr($nvpstr,$intial,$keypos);
$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
$nvpArray[urldecode($keyval)] =urldecode( $valval);
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
}
return $nvpArray;
}
function __destruct()
{
}
}
and call above class like,
....
$currencyCode="USD";
//$paymentAction = urlencode("Sale");
$paymentAction = urlencode("Authorization");
$nvpRecurring = '';
$methodToCall = 'doDirectPayment';
$nvpstr='&PAYMENTACTION='.$paymentAction.'&AMT='.$amount.'&CREDITCARDTYPE='.$creditCardType.'&ACCT='.$creditCardNumber.'&EXPDATE='.$padDateMonth.$expDateYear.'&CVV2='.$cvv2Number.'&FIRSTNAME='.$firstName.'&LASTNAME='.$lastName.'&STREET='.$address1.'&CITY='.$city.'&STATE='.$state.'&ZIP='.$zip.'&COUNTRYCODE='.$country.'&CURRENCYCODE='.$currencyCode.$nvpRecurring;
$paypalPro = new ZC_Paypal( '', '', FALSE, FALSE,'51.0',Zend_Registry::get("admin_paypal_pro_url"));
$resArray = $paypalPro->hash_call($methodToCall,$nvpstr,Zend_Registry::get("admin_paypal_user_name"), Zend_Registry::get("admin_paypal_password"),Zend_Registry::get("admin_paypal_pro_url"),Zend_Registry::get("admin_paypal_ssl_path"));
$ack = strtoupper($resArray["ACK"]);
//echo '<pre>'; print_r($resArray); exit;
if($ack!="SUCCESS")
{
if(!in_array($resArray["L_LONGMESSAGE0"], array('Internal Error', 'CURL send a error during perform operation: 6')))
echo $resArray["L_LONGMESSAGE0"];
else
echo 'Transaction Failed, Try again later.';
}
else{
// if success .....
}
pass credential in respective variable,i am using zend, so try to use core php here...

PHP cURL required only to send and not wait for response

I need a PHP cURL configuration so that my script is able to send requests and ignore the answers sent by the API.
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
//curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);
$result = curl_exec($ch);
echo $result;
curl_close ($ch);
I tried adding:
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
//curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);
But its not working properly and the API webserver is not receiving the requests.
The reason for this is I am sending large amount of requests to the API therefore my script is very slow because it waits for each and every request.
Any help is appreciated.
Sender file example ./ajax/sender.php
Script sending POST -> it makes full request to host, but it doesn't wait on answer from server : CURLOPT_HEADER(0) we dont needs headers from server) and CURLOPT_RETURNTRANSFER (false) we don't needs data from server.CURLOPT_TIMEOUT - Extra procteted : We waiting after sent only 1ms on respond server, this is extra quaranty to not wait any more ms if server keep us. ### NOTE ### HTTP1.1 has one package max 16kb. HTTP2 has 36kb one pacakge. If POST are more biggest, server will be send with many packages in series = $SIZE%16kb
$url = 'https://127.0.0.1/ajax/received.php';
$curl = curl_init();
$post['test'] = 'examples daata'; // our data todo in received
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_POST, TRUE);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_USERAGENT, 'api');
//curl_setopt($curl, CURLOPT_TIMEOUT, 1); //if your connect is longer than 1s it lose data in POST better is finish script in recevie
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_FORBID_REUSE, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($curl, CURLOPT_DNS_CACHE_TIMEOUT, 100);
curl_setopt($curl, CURLOPT_FRESH_CONNECT, true);
curl_exec($curl);
curl_close($curl);
Received file example ./ajax/received.php
ignore_user_abort(true); //if connect is close, we continue php script in background up to script will be end
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
header("Content-Length: 1");
### we just close connect above if webbrowser, or request waiting on answer ( we know we set CURLOP to not wait) ###
ob_end_clean(); //just flush all content if exists to request. If server still waiting on answer.
//HERE all script doing in background: Example
$this->db->query('UPDATE new_hook_memory SET new=new+1 WHERE id=1');
EDIT 2019 if you using fastcgi just finish fastcgi and browser close connection but script still will be working up to end.
How finish script: PHP mod_fcgi with fastcgi_finish_request();
For Apache2:
ob_end_flush();
flush();
For php-fpm
fastcgi_finish_request(); $this->db->query('UPDATE new_hook_memory SET new=new+1 WHERE id=1');
Old version:
These two solutions work well for me
( Of course it has been a long time, but I don't think this question is outdated )
using file_get_contents:
//url of php to be called
$url = "example.php/test?id=1";
//this will set the minimum time to wait before proceed to the next line to 1 second
$ctx = stream_context_create(['http'=> ['timeout' => 1]]);
file_get_contents($url,null,$ctx);
//the php will read this after 1 second
using cURL:
//url of php to be called
$url = "example.php/test?id=1";
$test = curl_init();
//this will set the minimum time to wait before proceed to the next line to 100 milliseconds
curl_setopt_array($test,[CURLOPT_URL=>$url,CURLOPT_TIMEOUT_MS=>100,CURLOPT_RETURNTRANSFER=>TRUE]);
curl_exec($test);
//this line will be executed after 100 milliseconds
curl_close ($test);
in both case the called php must set ignore_user_abort(true).
And the result will not be printed in both case, but be careful with the timeout you will set, it needs to be greater than the time that the called php needs to start yielding results.
If possible you can run wget in background (using exec)
There was some frustration in finding a solution that actually works, so I ended up building a service based on fsockopen() that can handle both GET and POST requests, without being blocking.
Below is the service class:
class NonBlockingHttpClientService {
private $method = 'GET';
private $params = [];
private $port = 80;
private $host;
private $path;
private $post_content;
public function isPost(): bool
{
return ($this->method === 'POST');
}
public function setMethodToPost(): NonBlockingHttpClientService
{
$this->method = 'POST';
return $this;
}
public function setPort(int $port): NonBlockingHttpClientService
{
$this->port = $port;
return $this;
}
public function setParams(array $params): NonBlockingHttpClientService
{
$this->params = $params;
return $this;
}
private function handleUrl(string $url): void
{
$url = str_replace(['https://', 'http://'], '', $url);
$url_parts = explode('/', $url);
if(count($url_parts) < 2) {
$this->host = $url_parts[0];
$this->path = '/';
} else {
$this->host = $url_parts[0];
$this->path = str_replace($this->host, '', $url);
}
}
private function handleParams(): void
{
if(empty($this->params)) return;
if($this->isPost()) {
$this->post_content = http_build_query($this->params);
} else {
/*
if you want to specify the params as an array for GET request, they will just be
appended to the path as a query string
*/
if(strpos($this->path, '?') === false) {
$this->path .= '?' . ltrim($this->arrayToQueryString($this->params), '&');
} else {
$this->path .= $this->arrayToQueryString($this->params);
}
}
}
private function arrayToQueryString(array $params): string
{
$string = '';
foreach($params as $name => $value) {
$string .= "&$name=" . urlencode($value);
}
return $string;
}
public function doRequest(string $url): bool
{
$this->handleUrl($url);
$this->handleParams();
$host = $this->host;
$path = $this->path;
$fp = fsockopen($host, $this->port, $errno, $errstr, 1);
if (!$fp) {
$error_message = __CLASS__ . ": cannot open connection to $host$path : $errstr ($errno)";
echo $error_message;
error_log($error_message);
return false;
} else {
fwrite($fp, $this->method . " $path HTTP/1.1\r\n");
fwrite($fp, "Host: $host\r\n");
if($this->isPost()) fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
if($this->isPost()) fwrite($fp, "Content-Length: " . strlen($this->post_content) . "\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
if($this->isPost()) fwrite($fp, $this->post_content);
return true;
}
}
}
It can be used like this:
$req = new NonBlockingHttpClientService();
$req->setMethodToPost(); //default is GET, so just omit this for GET requests
$req->setParams([
'test2' => 'aaaa', //if parameters are specified both with setParams() and in the query string, for GET requests, params specified with setParams() will take precedence
'test3' => 'bbbb',
'time' => date('H:i:s')
]);
$req->doRequest('test.localhost/some_path/slow_api.php?test1=value1&test2=value2');
And the slow_api.php file, can be something like this.
<?php
error_log('start');
sleep(10);
error_log(print_r($_REQUEST, 1) . 'end');
I find it easier to monitor (tail -f) the error log in order to see what is happening.
How can you tell if the request succeeded or not? You need to wait for at least the status code from the server to determine that. If latency is the issue, look at the curl multi API to perform multiple requests in parallel. You should be able to set a write callback function to abort reception of returned data once the status code has been returned.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
curl_exec($ch);
curl_close($ch);
That works well for me.
Tested on PHP 7.1.14 Windows
A bit late now but the solution to this for anyone interested is that CURLOPT_RETURNTRANSFER needs to be set to TRUE, not false. That way the curl_exec function returns a value immediately rather than waiting for the request to complete before returning - i.e. it acts asynchronously rather than synchronously.
Example:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
If you use Linux, you can use shell_exec in your PHP and send the result of curl to dev/null. By this method, you don't receive any answer and after sending PHP goes to the next line and Linux executes your command in the background. You should use this method if the answer is not important to you.
This is an example:
shell_exec("curl 'http://domian.com/message?text=$text' > /dev/null 2>/dev/null &")
Note: You can add any curl option like header or post method or proxy as your need.

Categories