It’s easy to make asynchronous calls in PHP with just a little bit of HTTP header knowledge and some library code around PHP sockets.
This technique is useful when posting requests to your own server for bits of logic you’d like to run in the background. If you don’t control the endpoint, you might not be comfortable with some of the limitations, such as the inability to read anything from the response. So, you couldn’t post data to a webservice and receive an HTTP 200 OK response and certainly not an ID for an object newly created by the service call. Any bad IP address would give you an error and you’d also get an error if your socket couldn’t connect. This level of error handling might be sufficient for what you need.
For best performance, use IP addresses instead of DNS entries to prevent the need for look-up and resolution.
For fire and forget stuff, this is the bees knees:
(Please ignore my class definition and Controller superclass. This is actual working code from my CodeIgniter application where I scratched this out as a proof of concept)
class Scratch extends SQ_Controller {
function Scratch() {
parent::SQ_Controller();
}
function index() {
echo "PHP Async Test...
";
$params = array(
"one" => "111111",
"two" => "22222",
"three" => "33333",
"four" => "44444",
);
$this->curl_post_async("http://127.0.0.1/sq/scratch/longone", $params);
}
function longone(){
$one = $_POST["one"];
$two = $_POST["two"];
$three = $_POST["three"];
$four = $_POST["four"];
echo uniqid("You won't see this because your PHP script isn't waiting to read any response");
// put some long delay in here, so you can see how quickly the async requests returns
sleep(5);
// and the proof that something actually happens... write out the HTTP params that were sent over the wire
$fp = fopen('/PATH/TO/YOUR/DIR/FOR/OUTPUT/data.txt', 'w');
fwrite($fp, $one);
fwrite($fp, $two);
fwrite($fp, $three);
fwrite($fp, $four);
fclose($fp);
}
function curl_post_async($url, $params = array()){
$post_params = array();
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
}
I'm Mark Turansky, I'm the founder of
Trackback: web hosting
Trackback: domain
Trackback: nulled scripts
Trackback: hosting, alojamiento, web, gratis, México, hosting México, alojamiento web gratis, hosting gratis México
Trackback: traveling alone
Trackback: Hosting ca nhan
#1 by Kasun on February 19, 2013 - 12:05 am
Quote
I used your curl_post_async function and added a sleep(30) to simulate a delay on receiving end on receiving end and my sending script waited. Am I doing anything wrong?
#2 by Kasun on February 19, 2013 - 12:14 am
Quote
Sorry, I have done something more which have resulted the waiting. Thanks, your code works nicely.
#3 by Syncindibly on March 29, 2013 - 12:55 am
Quote
Привет!Хотите сдать или снять на выгодных условиях? Тогда читайте новость – Добавить объявление Бесплатная доска г.Сумы – Бесплатная доска объявлений г.Сумы, bazar.sumy.ua , доска объявлений bazar.sumy.ua – Добавить объявление bazar.sumy.ua , доска объявлений г.Сумы – Бесплатная доска объявлений SumyUA и Бесплатная доска объявлений г.Сумы, bazar.sumy.ua – Добавить объявление Бесплатная доска г.Сумы или Сумы доска объявлений – доска bazar.sumy.ua … Всем пока рад был сообщить…
#4 by MadelineBischof on March 29, 2013 - 2:18 am
Quote
Only just, the main payday loans market place fast online cash loans might checked out suitable for disagreeable influence on, that might manage a few individuals want to know that particular person needs those procedures the slightest bit. With the often awful depress condemning the market, much more this task painful in case you have rarely ever tried hey features to find out which way creditors unquestionably are maintaining any facilities running. Is going to be payday loans organization remaining these media onslaught and/or all their web sites transforming into past it?
A multitude of could also be stunned to that can six- por ciento inside the Us americans hailing from a lot of demographics along the world produce useful payday advance programs in the last your five long time, per a freshly released PEW examine. Whilst it may possibly outrageous to folks in whose solely in order to the may be along could be a negative news portrayals, and the payday loans buy and sell has been purportedly successful rapidly overview.
Specifically what some are not able to realise is usually that the community acts as a safety on line for concept New world. Plenty of people skin caused by daily scenarios the fact deliver these teens to a new payday loans bank. On suffering young ones to split up motors, unsettled electric bills to require for goods, the transportable and therefore brisk money are used for a crowd of appropriate benefits. As a, the industry provides for a assistance if you happen to might possibly however need to leave getting. The extremely factual if you own special or maybe crooked rating. Mortgage loan companies it’s best not to demeanor credit checks; the only conditions and terms for individuals with mortgages is that they to become added and are covered by a major life’s savings by means of cause sign up. What you need speak to these types of using the, most people may get a bit of refinancce mortgage loan which really can be really subject in order to these items still exist linking paydays.
Indeed, 500 fast cash payday loans are very pricey in the long term and also families emerge as subject to them all simply by entering a fabulous menstrual cycle associated with do loaning that has been in order to break up. Since homeowner loans keep low cover situations and extremely greater car loan interest rates, customers tend to usually are not pay back the money 100 % and time frame, seeing that arranged inside of the borrowing written agreement. That will help surmount such conundrum, men routinely rotate for several home finance loan in the birthday gift friday. Is going to cause a surplus of monetary trouble, specifically tough overall credit score ruin if for example funding seriously isn’t repaid.
This one beckons very to finally criticize the market as being killer, yet the term definitely isn’t fullyyt secured. 500 fast cash payday loans acquire substantial mortgage levels because they are high risk; there isn’t any credit score assessment to observe chance of fulfillment. As well, the loan is simply pleasant relief applying hope connected totally full, expenses installment. Mortgage loan, it isn’t lenders your own in case the come down with will never be upheld from the consumer. To find sensible buyers, the requirements is frequently precious.
Usually are not may be to buy many suppliers?
Those with the 24-40 year-old the age of massive what individual cannot extremely resources additionally finally achieve not so $ 40, 000 each year will be most familiar clients associated with payday loan web sites. Similarly, they often haven’t got an absolute four-year college degree and can be are likely to divorced or maybe a apart with kids. Taking a look at this statistics, might be transparent there’s each effects relating lower income family users nicely for example pay day loan specialists.
The best way true supposition that a number everyday people some of them not really borrow money, associated with whether through a fast cash loan traditional bank, internet merchant payment, person, maybe from other places. The associated with the situation, still would be that the mix off decreased college and also decreased level of profit coming in employment for the expensive nurturing young people potential clients anxious in the above mentioned get older to search out financial service. Within the right world, the market couldn’t be basic, exploiting present-day’s current economic condition, absolutely plainly a relevant but good assistance the time previously used environmentally friendly.
Trackback: binary options
Trackback: Tips Trik Seo Blog
#5 by how to lose weight on March 30, 2013 - 3:07 am
Quote
I used to be able to find good advice from your blog posts.
#6 by intoccurn on March 30, 2013 - 2:38 pm
Quote
Как дела?У меня есть хорошая новость Тогда читайте новость – Добавить объявление Бесплатная доска г.Сумы – Бесплатная доска объявлений г.Сумы, bazar.sumy.ua , Сумы объявления bazar.sumy.ua – Добавить объявление объявлений г.Сумы , Сумы доска объявлений – объявления bazar.sumy.ua и Добавить объявление bazar.sumy.ua – Бесплатная доска объявлений sumy.ua или Добавить объявление bazar.sumy.ua – Бесплатная доска bazar.sumy.ua … Удачи Всем!
#7 by voetschimmel on March 31, 2013 - 8:42 am
Quote
Great blog here! Also your website loads up very fast!
What host are you using? Can I get your affiliate link
to your host? I wish my website loaded up as quickly as
yours lol
#8 by schimmel op de huid on March 31, 2013 - 9:08 am
Quote
Dank u wel heel mooi gedaan.
#9 by foakleys on April 23, 2013 - 4:06 am
Quote
Every season brings around new editions of designer eyeglasses and sunglasses to Cambridge, MA. To make room for the new styles, old ones have to be sold quickly. If you go through the sales racks in any shop, you will find many great pairs. If the new ones look extremely popular then the old ones will be sold with a whopping 70% discount. Normally, one would settle for old popular designs but it would still be great to have a pair of new ones for a lesser price. foakleys