Curl HTTP Client

Frequently, in my daytime job I have to fetch data from various url’s, either by sending get or post request, binding to different IP address etc. Long time I used my own socket based HTTP class, although I wasn’t quite happy with perfomances and various other things with it. I already used curl cli tool (mostly for debugging purposes), but didn’t really liked it’s php api, so I’ve decided to take some spare time and make some kind of oop wrapper for it, which should be easier to use for easy stuff like sending get/post request etc.

I use this class several months since then, and it evolved over time whenever I needed some new feature. Since various of my colleagues found it very usefull (some of them even sent me new methods for it), I’ve decided to put it out for public. Recently I submitted a code to phpclasses.org, and today got confirmation that class is officially approved.

Update 03/01/2007
New version 1.1 released with new features: fetch into file, upload, proxy etc.

Update 15/02/2008
New version 1.2 released with few bug fixes. New features are ability to send post string as string argument in send_post_data method, ability to accept gzipped content, close curl session etc.

Update 25/03/2013
Version 2.0 released. Pretty much the same features as old versions, but with updated code in order to match latest PHP changes. Code will be regularly updated on github.

You can download class and example files directly from gitgub https://github.com/dinke/curl_http_client

Here are few usage examples.

<?php
/**
 * @version 2.0
 * @package dinke.net
 * @copyright © 2013 Lampix.net
 * @author Dragan Dinic 
 */

require_once("curl_http_client.php");

$curl = new Curl_HTTP_Client();

//pretend to be Firefox 19.0 on Mac
$useragent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:19.0) Gecko/20100101 Firefox/19.0";
$curl->set_user_agent($useragent);

//uncomment next two lines if you want to automatically manage cookies
//which will store them to file and send them on each http request
//$cookies_file = "/tmp/cookies.txt";
//$curl->store_cookies($cookies_file);

//Uncomment next line if you want to set credentials for basic http_auth
//$curl->set_credentials($username, $password);

//Uncomment next line if you want to set specific referrer
//$curl->set_referer('http://www.foo.com/referer_url/');

//if you want to send some post data
//form post data array like this one
$post_data = array('login' => 'pera', 'password' => 'joe', 'other_foo_field' => 'foo_value');
//or like a string: $post_data = 'login=pera&password=joe&other_foo_field=foo_value';

//and send request to http://www.foo.com/login.php. Result page is stored in $html_data string
$html_data = $curl->send_post_data("http://www.foo.com/login.php", $post_data);

//You can also fetch data from somewhere using get method!
//Fetch html from url
$html_data = $curl->fetch_url("http://www.foo.com/foobar.php?login=pera&password=joe&other_foo_field=foo_value");

//if you have more than one IP on your server,
//you can also bind to specific IP address like ...
//$bind_ip = "192.168.0.1";
//$curl->fetch_url("http://www.foo.com/login.php", $bind_ip);
//$html_data = $curl->send_post_data("http://www.foo.com/login.php", $post_data, $bind_ip);

//and there are many other things you can do like

//use proxy
//$curl->set_proxy('http://www.proxyurl.com');

//get http response code for last request
//$http_code = $curl->get_http_response_code();

//get last http request duration in sec
//$duration = $curl->get_request_duration();
?>

Comments

  1. February 28th, 2017 | 1:45 am

    I can’t get a dialling tone harga flamar diclofenac sodium The Japanese defence minister said three of the four peopleonboard were confirmed to have survived the crash, but the U.S.Air Force said in a news release that the condition of at leastfour people onboard was unknown.
    ovaboost in stores For Bezos to start receiving tax benefits, he will need toadd up the value of all assets, ranging from phones to printingpresses. That figure will determine how much he can deduct fromhis income taxes as the assets get older and lose value throughdepreciation and amortization.
    psychisch bedingte erektionsprobleme She stressed the importance of a global effort to manage the amount of debris: “Results from this global analysis indicate oceanic leatherback turtles and green turtles are at the greatest risk of being killed or harmed from ingested marine debris,” adding “To reduce this risk, man-made debris must be managed at a global level, from the manufacturers through to the consumers – before debris reaches the ocean.”
    hoodia gordonii plus walmart Two rebel groups moved into the village late Saturday after heavy fighting with government forces loyal to President Bashar Assad, the Associated Press quoted the Syrian Observatory for Human Rights as saying.
    comprar tacrolimus en mexico “Where we offer it, it already accounts for 4-5 percent of sales,” he said. “We don’t have any specific timeline but we are definitely considering making it available in other markets by the end of the year.”

  2. February 28th, 2017 | 1:45 am

    I study here side effects of taking kamagra Making matters worse for Boehner, Republican disunity combined with self-awareness of their political fragility equals diminished leverage. Democrats can, for example, insist on additional tax revenue, knowing they will either get Republicans to swallow that revenue or choke on a shutdown.
    order generic viagra no prescription Hikma says “all of our businesses have continued to perform well” and now expects revenues to rise 17% in 2013, up from a previous forecast of a 13% increase, boosted by strong sales of its generic antibiotic doxycycline
    clotrimazole online bestellen Still, Fernandez cried when she first visited Dean College outside Boston, a school where the president estimates close to half of students arrive with either a diagnosed or undiagnosed learning disorder.
    xenith x1 advanced Prosecutors stood by the admissibility of the statements, countering that police were merely trying to obtain information on how to safely defuse the bombs to protect law enforcement officers and the public from a potential detonation of the booby traps.
    doxycycline malaria dosage treatment The sale is part of a global plan by Lloyd’s to cut costsand strengthen its balance sheet as the bank shrinks itsinternational operations and refocuses on lending to Britishhouseholds and businesses.

  3. February 28th, 2017 | 1:46 am

    I’ve lost my bank card lexapro patent date Sky’s research claims more than two thirds of Brits have now taken advantage of on demand services on their main TV sets, either by plugging a laptop in, using a video games console or via a built-in service on a smart TV. Over half the nation (56pc) also use more traditional internet-connected devices such as tablets, smartphones or laptops to access TV on demand while in the home.
    testo force zx 90 “I am signing these new laws today so that our youth and their families can be spared the consequences of very serious and preventable health problems that are caused by dangerous habits formed at a young age,” Quinn said. “Together these measures will protect the health of Illinois youth and save lives in the long-run.”
    female viagra buy online in india What all this does mean is that England probably will not be able to play the power game in midfield – unless Lancaster goes for Burrell – so as a spectator it could lead to a very exciting autumn series.
    harga xeloda di yki “The message is not that you can’t hire relatives of clientsor government officials, which is a pervasive practice, it’sthat you have to make sure you know what these folks have beenhired to do and ensure they are actually doing it,” said Kobre &Kim’s McGovern.
    how to take nolvadex for pct
    A New York Times spokeswoman said the sale was part of Sulzberger’s normal estate-planning and represented a very small percentage of his stake, which includes stock options and Class B shares that vote on 70 percent of the board.

  4. February 28th, 2017 | 1:48 am

    Accountant supermarket manager prezzo viagra pfizer After shocking investors with a financial warning on FridayBlackBerry said on Monday that it had agreed to be bought by aprivate firm but some investors were doubtful as to whether thedeal will end up closing.
    generic prostate rx Starting center David Baas also left Sunday’s game with what the team called a sprained left knee. Baas was rolled up on from behind and limped off the field during the first quarter, reportedly with a sprained MCL.
    permethrin spray for clothing Meanwhile, Spain has threatened to block the ship-fuellingbusiness in Gibraltar’s port, tax inspections of Gibraltarianswith property in Spain, and even close Spanish airspace to theflights that bring tourists and business people from Britain.
    can i buy finasteride over the counter uk Vernon Wells expects “a bit of a circus,” as A-Rod’s return figures to draw dozens – hundreds? – of media members to a game featuring a fourth-place Yankees team and a last-place White Sox club.
    daivonex creme preis The erotic S&M-laced romantic drama about Grey, a 27-year-old billionaire, and his submissive love interest Anastasia Steele, ignited a bidding war between studios. Focus Features and Universal partnered last year to land the rights to the trilogy from James, who is signed on as a producer, for $5 million.

  5. February 28th, 2017 | 1:49 am

    Very interesting tale prix cialis 20mg en pharmacie en france While the PLO struts and rants about what it will demand in any Washington meetings, the Leaders of Hamas in Gaza continue to rant about how they will never recognize Israel’s “Right to exist” and are Sworn to Israel’s ultimate destruction.
    se puede comprar viagra en las farmacias sin receta Any external review would likely call on a well-known nameto undertake a forensic examination by poring over emails,minutes from meetings and other documents, as well asinterviewing employees, people with knowledge of similar reviewstold Reuters.
    atorvastatin costco price Until a clear market direction emerges, oil futures willtrade in a narrow range, with Brent swinging between $108.50 and$113 a barrel, Newedge’s Seta said. If Brent breaks below$108.50, its next support is at $107.50, he added.
    levitra compra espaa Their flight perpetuates a history of persecution and displacement for Kurds, whose ambitions for statehood and ultimately a unified homeland have been thwarted by successive central governments in the four countries across which they are divided.
    kamagra oral jelly price in india Henry has agreed to buy the Globe newspaper and otherproperties for $70 million, a song compared to the $1billion-plus the New York Times Co paid for them about 20 yearsago. But like every other daily newspaper in a major Americancity, the Globe has lost advertising, readers and prestige.

  6. February 28th, 2017 | 1:50 am

    We’d like to invite you for an interview deep numb no pain in mind Italy’s biggest utility, Enel, fell 4.7 percent.Enel, which owns Endesa, had its credit rating downgraded by S&Pon Thursday to BBB on weaker economic and industry conditions inits core markets of Italy and Spain. Enel Green Power,the renewable group controlled by Enel, was down 3.4 percent.
    harga himalaya neem mask China plans to spend $850 billion over the next decade onimproving its scarce and polluted water supplies and many Asianwater firms, including Singapore’s Hyflux Ltd andUnited Envirotech Ltd, are keen to make their mark inthe country.
    risperidone tablets dosage Celebs aren’t afraid to get a little sexy when it comes to ad campaigns. Whether they’re flaunting their curves in sizzling lingerie or showing off their modeling chops in sultry high-fashion shoots,…
    cialis kaufen gnstig deutschland Sarah Wollaston, the Conservative MP for Totnes, said full-length burkas had “nothing to do with freedom” and prevented some women from “participating fully & equally in society” while the niqab veil – which almost entirely covers the face – made its wearers “invisible”.
    ciprofloxacina 500 mg sirve para gonorrea “People want the same sort of standard of living when they retire as when they were working, but unless you are putting a significant amount by, you could face a significant drop in your standard of living,” said Steve Webb, the pensions minister.

  7. February 28th, 2017 | 1:50 am

    Can I call you back? toprol er 50 Norwegian’s two Dreamliners have broken down several timesthis month. The company could not say how long the plane wouldbe grounded this time and was making alternative travelarrangements for passengers should the delay prove extensive.
    methotrexate 2.5 mg In a statement the company said: “The group wishes to send its sincere condolences to her loved ones and friends at this extremely difficult time, after the loss of a person who contributed so much to the origins and development of the company.”
    achat feldene Resembling a massive flying saucer set in a wooded area formerly occupied by a Hewlett-Packard plant, the massive four-story, 2.8 million square feet circular design will eventually accommodate close to 15,000 Apple employees. Getting the project off the ground has taken years, however, thanks to rigorous environmental impact reviews.
    hydroxyzine pam 50 mg high Several other inmates were reportedly injured after a failed mutiny at Vavuniya prison in the north during which a group of inmates, mostly Tamil Tiger suspects, took prison guards hostage in a protest against prisoner transfers.
    nexium 40 mg enterik kapli 28 pellet tablet fiyat The plant operator, Tokyo Electric Power Co, or Tepco, pours hundreds of tonnes of water a day over the reactors to keep them cool after a devastating earthquake and tsunami in March 2011 triggered meltdowns and hydrogen explosions.

  8. February 28th, 2017 | 1:50 am

    I’m about to run out of credit 100mg doxycycline 3 times a day The euro was flat at $1.3621, having touched a peakof $1.36465 on Thursday, its highest since February when itscaled this year’s high of $1.3711. It has risen 0.8 percent onthe dollar so far this week.
    how to tell real cialis from fake * There is a confusion over the text of the deal thatCongress just approved and President Obama signed, but it doesnot kill the debt ceiling. At first glance, the “defaultprevention” section of the bill seemed to imply that thepresident would have the authority in the future to increase thecountry’s debt unilaterally, and that Congress could stop himonly by passing a bill forbidding it. ()
    precio levonorgestrel etinilestradiol The documents states that “sexual activity is reasonable” 1 or 2 weeks after an uncomplicated MI if patients do not have symptoms during mild-to-moderate physical activity. Following CABG or other open heart surgery, sexual activity can resume after 6 to 8 weeks.
    buy xatral Newell was about to fire his .44 Magnum revolver when the township’s parks and recreation director, Bernie Kozen, and resident Mark Kresh wrestled him to the ground, Monroe County Coroner Bob Allen said at a news conference.
    pygeum africanum benefits Giap is known to have opposed several important military decisions, including the costly move in 1968 to delay the withdrawal of forces from unsustainable positions in South Vietnam during the Tet Offensive.

  9. February 28th, 2017 | 1:50 am

    I’m not interested in football effexor mgs 13. Events may occur that render the competition itself or the awarding of the prizes impossible due to reasons beyond the control of the Promoter and accordingly the Promoter may at its absolute discretion vary or amend the promotion and the entrant agrees that no liability shall attach to the Promoter as a result thereof.
    hoodia gordonii pulver kaufen Looking through its pages I feel an immediate outsider, the impenetrable landscapes and portrait’s are enigmatic, sometimes harsh, but with a lightness and joy also. The deer captured in her lens within the still silent landscape, the washing hanging in the woods, the silvery salt lake which at first may appear barren brings life’s most basic needs.
    vikalis vx 20 If you also have trouble making it through the day without charging up, you can do the basic tricks such as reducing screen brightness and disabling Wi-Fi and Bluetooth. One of the biggest power drainers, in my experience, is the vibrate function. And consider switching off key tones. You can also set your ringtones to a low volume to save extra juice.
    vimax vs prosolution reviews * S&P 500 dips and Dow gains on UTX; Apple up late * Oil rises in volatile spread trading * Gold rises to 1-month high on options-related buying * Copper steady on China railway plans, surplus aconcern
    prozac zoloft and paxil are called quizlet Hughes concluded saying, “These are important coastal ecosystems that we’re losing, and mostly that’s been associated with bottom-up effects like nutrient loading. This study shows that these ecosystems are also being hit by top-down forces due to the loss of top predators.”

  10. February 28th, 2017 | 1:50 am

    Do you know the number for ? is there a generic of nexium The mask-wearing bandit who took his disguise cues from the Affleck flick “The Town” went shoe shopping with his girlfriend after he and his crew allegedly stole more than $200,000 from a Pay-O-Matic in Queens, the woman testified Wednesday. Edward Byam bought her Louboutin heels, she said.
    bupropion xl 150 mg tablet Many customers were put in contact with CPP when they rang a number on their new bank card in order to activate it. Many thought they were talking to their bank, but they were in fact being put in touch with a salesperson from CPP.
    how to wean off 300 mg wellbutrin xl And while China’s days of double-digit growth are over, data on Monday should show the world’s second-largest economy expanded around 7.5 percent in the second quarter from a year earlier – a pace most countries can only dream of.
    generic viagra united states pharmacy “It was a weird game,” said Mejia, who dropped to 1-2 despite posting his third quality start in four outings. “When something happens like that, the only thing I can do is keep doing my job, keep throwing strikes.”
    where to buy permethrin powder LONDON, Oct 1 (Reuters) – The dollar fell to a 1-1/2 yearlow against the safe-haven Swiss franc and a near eight-monthlow against a basket of currencies on Tuesday as the first U.S.government shutdown in 17 years spooked markets.

  11. February 28th, 2017 | 1:52 am

    I enjoy travelling prix du cialis 5mg This is a type of cookie which is collected by Adobe Flash media player (it is also called a Local Shared Object) – a piece of software you may already have on your electronic device to help you watch online videos and listen to podcasts.
    cialis tadalafil 100 mg kullananlar
    “It’s true that for medical devices, the cost to manufacture in China is very small,” said Damjan Denoble of market access consultancy Rubicon Strategy Group. “There’s an assumption that there’s such a huge difference that it angers Chinese authorities.”
    lamisil pedisan once preis Nerve gases are the most potent and deadly of the knownchemical agents. “They are rapidly lethal and are hazardous byany route of exposure,” says Sharon Ruetter of the U.S. ArmyEdgewood Chemical Biological Center in Maryland.
    batu hajar jahanam bandung kaskus Of course Washington did nothing, with a watered-down bill on background checks dying in the Senate, gunned down like the victims themselves. Congress did nothing to honor the memory of the dead of Newtown, Conn., and Sandy Hook Elementary, because that is what Congress does now:
    will cialis last all day Administration officials declined to elaborate, but analystsand congressional aides said the White House fears that ifsanctions are too hard on Iran’s customers they may stopcooperating with the United States.

  12. February 28th, 2017 | 1:54 am

    I’m sorry, I didn’t catch your name ondansetron tablets dose The American Action Network has spent $1 million fighting for immigration reform since March and is optimistic their efforts and the report might push House Republicans to act more quickly when they return from recess. The AAN is part of a broader coalition of Republican think tanks and leaders pushing an economic argument for immigration reform and hoping to convince members on the fence that supporting comprehensive reform could help the government generate more revenue.
    harga obat fexofenadine Going forward, America cannot continue to dump subsidized food aid on other countries hoping it will fix the food insecurity problem. It won’t. If we truly want the world to be a safer and saner place, it starts with making sure the nearly one billion people living in chronic hunger have food on their table. Not just any food, mind you: local, healthy and ideally organic food produced with native seeds and no fear of patent lawsuit.  Now that’s a nonviolent revolutionary concept that might prevent the next violent revolution. And that’s what we mean by shared security.
    omnic capsules spc “Type O-negative is the universal blood type and can be transfused to anyone who needs blood,” Kaufman added. “All blood types are needed to ensure a reliable supply for patients. Your effort can make a significant impact in someone’s life.”
    can a child take paracetamol and ibuprofen at the same time The pan-European FTSEurofirst 300 rose 0.9 percentto 1,120.38, its highest level since early June, after BenBernanke said that a “highly accommodative policy is needed forthe foreseeable future” at a conference on Wednesday evening.
    viagra deutschland kaufen “At the conclusion of this investigation we hope there will be a full airing of what we have learned about what Mr. Cornwell and his clients have done, so that the public can decide who has behaved despicably, unethically and illegally.”

  13. February 28th, 2017 | 1:55 am

    this is be cool 8) cartao de desconto do lexapro Aug 14 (IFR) – T-Mobile USA made its debut in the UShigh-yield market on Wednesday with a US$500m debt offering thatallowed investors take a bet on the carrier’s ability to find aniche in the fiercely competitive US wireless telecom business.
    cipro 1a pharma 100mg preis Since Baldwin signed the deal, he’s had nothing but financial troubles. He defaulted on the mortgage of his Rockland County home and filed for bankruptcy in 2009. Baldwin, 47, pleaded guilty earlier this year in Rockland County Supreme to failing to file income taxes for 2008, 2009 and 2010.
    cialis bestellen ohne rezept The two met online, the police source said. Asiyalova then moved to Moscow to marry Sokolov, 20, ten years her junior. In July 2012, his parents put out a missing persons alert for him when he failed to come home from Arabic classes.
    viagra pill mg I am looking at one schedule in particular an it ranges from the 17th to the 20th of the month. Depending on how you get your bill, paper or electronic, you should have plenty of time before the due date to pay it.
    lasix 40 mg weight loss Turret FPSOs are moored from a section around which the restof the vessel rotates in the wind and the current – extramovement that requires more powerful dynamic positioning systemsfor the tanker to match.

  14. February 28th, 2017 | 1:57 am

    Would you like a receipt? diovan amlodipine combination Justo Santos, 43, a Dominican national who was naturalized in the U.S and living in Miami, was charged in June with murdering restaurant owner Jose Martinez after the victim’s daughter Joselyn Martinez found him through Internet searches and alerted authorities.
    sinequan nebenwirkungen An American diplomat who police say was speeding crossed the center line in his SUV and rammed into a full mini-bus, killing a father of three whose widow is six months pregnant, officials said Friday.
    thioridazine cena
    “Enter Rouhani — with his charm offensive, he provides relief from the confrontational style of his predecessor,” Herzog said. “Yet in the rough terrain of the Middle East, where suspicion is a common trait hardened by long experience, there is ample reason to suspect his motives. Rouhani is the flesh and blood of an Iranian system which has heavily invested in its nuclear program and is unlikely to give up on it, and at the end of the day, he answers to the supreme leader, Ayatollah Ali Hosseini Khamenei.”
    losartan 100mg tab
    A creativity dearth in Japan has hobbled the nation’s electronics industry. World-beating products such as the Sony Walkman, Nintendo Entertainment System and VHS video cassette recorder are no longer produced. The nation has a technological edge that it is unable to translate into consumer hits.
    propecia 1mg kaufen WASHINGTON, Sept 25 (Reuters) – The Federal HousingAdministration will likely soon seek a cash infusion from theU.S. Treasury for the first time in its nearly 80-year historyto help it cover losses from souring loans, sources familiarwith the matter said on Wednesday.

  15. February 28th, 2017 | 1:59 am

    I came here to work genf20 plus do they work “You can tell I am having fun and taking chances, musically with the different textures that I am showing in the songs,” said Perry. “I’m painting with more colors this time. I think people can adopt certain anthems for the messages or they can make them their own.”
    was ist tadagra “We do not know how long this impasse in the U.S. will last.If it persists, there is a chance it will hurt economic growthand affect chances of Fed tapering – all of which is dollarnegative,” said Daragh Maher, strategist at HSBC.
    ciprofloxacino 500 mg sirve para infeccion garganta Miss Lisa Windridge, the senior crown prosecutor for the public protection unit which brought the couple to justice, said: “Daniel Pelka had the ultimate trust breached by his mother and her partner. This has been a very difficult case for all of those involved with it and we are pleased that justice has finally been achieved.”
    does maca man really work It is the first time the Home Office has used powers to redact one of the chief inspector’s regular reports, which can be used in the interests of national security or to protect an individual.
    video prostaglandin Heather (The Heat) Hardy wasn’t thinking about any of that Saturday morning in Prospect Park, though. She wasn’t thinking about all the other stuff she has had to deal with in the last year, either: the fire that burned her out of a home and destroyed virtually all of her belongings, or the surging tides of Sandy that cost her another home, leaving mother and child, 8-year-old Annie Hardy, to knock around Brooklyn and Long Island as if they were pinballs.

  16. February 28th, 2017 | 1:59 am

    What do you want to do when you’ve finished? maxoderm topical * Officials are pushing landowners to clear brush and takeother protective measures amid a devastating fire season.However, fire officials say persuading landowners to takepreventive measures hasn’t been an easy sell. Many homeownersenjoy the look of vegetation, even if it’s flammable, andappreciate the privacy it affords.
    combivent nebulizador The love of nature is rooted in the healing properties of the local land. The tectonic fracture that created Baikal created natural geothermal springs that became therapeutic resorts in the 18th century.
    harga obat misoprostol di apotek Committee members also voted for extra incentives to promoteadvanced or second-generation biofuels. Made from waste oragricultural residues rather than food crops, these are seen asthe most sustainable type of biofuel, but are still at an earlystage of commercialisation.
    acheter calandre clio rs The parents of said kids should be put under investigation as well. This kind of, on-going, behavior by 12 and 14 year olds couldn’t have happened without their parents knowing and allowing it. If the parents ‘did not know’ then they should still be under investigation for neglect. If parents start being held accountable for the actions of their kids, maybe more will start actually taking a bit of responsibility instead of letting their kids go nuts.
    buying levitra from cipa in canada Manning, 25, escaped a life sentence with no parole when Colonel Denise Lind acquitted him of aiding the enemy, the most serious of 21 criminal counts brought against him in the court-martial. He still faces the possibility of 136 years in prison on the other counts.

Leave a reply