How to POST Form Data using CURL - By PHP Expert


Posting Form Data with cURL
CURL is a very useful tool for a web programmer to be able to fully interact with another website or page. It stands for Client URL (Library), and contains many powerful features when used with php.

<?php
$ch = curl_init( );
curl_setopt( $ch, CURLOPT_URL, "http://www.google.com" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$response = curl_exec( $ch );
print $response;
?>

Breakup:
Line 1: Create a curl handle and set it to the variable $ch
Line 2: Use the curl_setopt( ) function to set the url the script is targeting to google.com
Line 3: Use the parameter CURLOPT_RETURNTRANSFER to make the curl handle receive the response in a string when executed.
Line 4: Execute the curl script and put the response into $response.
Line 5: Output what google.com says.

Now, to add a pratical application of this incredibly powerful library. Use an HTTP POST request.

<?php

$ch = curl_init( );
curl_setopt( $ch, CURLOPT_URL, "http://www.google.com" );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, "username=Third_Degree&password=youwish" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$response = curl_exec( $ch );
print $response;

?>


These two lines are the power of this script
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, "username=Third_Degree&password=youwish" );

The URL specified earlier will now be dealing with the post fields username and password just like you submitted the form in your browser. This technique has an endless list of applications, and hopefully you will now have better control of the posting technique of cURL in PHP.

No comments

Enter your email address:

Delivered by FeedBurner

OR

 Subscribe in a reader

 
jQuery UI provides a comprehen
 
Program Plan   I drafted a p
 
I present to you my skills, ac
 
Introduction One of the issue
 
If you are a PHP developer and
 
cURL is a great tool to help y
 
cformsII cforms is a powerful
 
  The lack of Unicode su
 
History PHP-GTK was origina
 
Performance on the web is stra
 
Listen t
 
What\'s the number one cost in
 
When you\'re discussing the In
 
Classe
 
A service-oriented architectur
 
Introduc
 
PHP Crons and Linux Linux has
 
Cross site scripting (XSS) is
 
What Makes a Web 2.0 Applicati
 
As you develop web application
 
Cryptogr
 
Posting
 
Have you
 
Resources The Google API - ht
 
Get Started
 
Output B
 
If you r
 
PHP has some really sweet new
 
There were some new php.ini di
 
In PHP 5 there are some new fu
 
The following code implements
 
The following code snippet imp
 
A fine implementation of the o
 
Exception handling PHP 5 adds
 
Support for dereferencing obje
 
Static members Classes defini
 
Explicit object cloning In or
 
final methods The final keywo
 
Interfaces Gives the ability
 
The new object oriented featur
 
Sometimes its the little thing
 
Consider your file is at locat
 
# If a method can be static, d