October 2, 2008

Using cURL with PHP

Basic cURL:
= curl_init('http://www.target.com'); // the target
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return the page
$result = curl_exec ($ch); // executing the cURL
curl_close ($ch); // Closing connection

echo $result;
?>
that code would get the source code of target.com, and echo it.

Post via cURL:
= "field_name=field_value&submit_value=submit\";

$ch = curl_init('http://www.target.com'); // the target
curl_setopt ($ch, CURLOPT_POST, 1); // telling cURl to POST
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
curl_exec ($ch); // executing the cURL
curl_close ($ch); // Closing connection

?>


Simple posting via cURL.

- Using cookies with cURL:

( You will find this usefull when you are trying to do something that needs a login and a cookie stored )

= curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.target.com');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, '/path/to/cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/path/to/cookie.txt');
$result = curl_exec($ch);
curl_close($ch);

echo
$result;

?>

ofcourse you might need to post first into the login form, to get the cookies stored, then you can do other things with you being logged in.

- Extra info:

you can set `user-agent`, `referrer`, `headers`.. using cURL:

// set user-agent to DarkMindZ
curl_setopt($ch, CURLOPT_USERAGENT, 'DarkMindZ');
?>
// set referrer darkmindz.com
curl_setopt($ch, CURLOPT_REFERER, "http://www.darkmindz.com\");
?>


- Making life easier:

This function will help you alot in making things go easy:

function curl_it($method, $target, $post_var)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, '/path/to/cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/path/to/cookie.txt');

if (
$method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_var);
}

$result = curl_exec($ch);
curl_close($ch);
}

// usage:

curl_it('', 'http://www.darkmindz.com'); // get darkmindz.com homepage

curl_it('POST', 'http://www.darkmindz.com', 'user=dude&pass=dude2'); // login using dude:dude2

?>

1 comment:

Anonymous said...

Địa chỉ Bar Seventeen:
103A Phạm Ngũ Lão, Q.1, TP. Hồ Chí Minh.