<?php
/*
cURL POST request
*/
function cURLpost($target, $data = false, $cookiePath) {
$ch = curl_init();
$queryString = queryString($data);
if(isset($queryString)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString);
}
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPGET, FALSE);
curl_setopt($ch, CURLOPT_NOBODY, FALSE);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiePath);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiePath);
curl_setopt($ch, CURLOPT_URL, $target);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/*
cURL GET request
*/
function cURLget($target, $data = false, $cookiePath) {
$ch = curl_init($target);
$queryString = queryString($data);
if(isset($queryString)) {
$target = $target."?".$queryString;
}
curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
curl_setopt($ch, CURLOPT_POST, FALSE);
curl_setopt($ch, CURLOPT_NOBODY, FALSE);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiePath);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiePath);
curl_setopt($ch, CURLOPT_URL, $target);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/*
build a query string
*/
function queryString($dataArray = false) {
if(!is_array($dataArray)) {
return false;
}
foreach($dataArray as $key => $value) {
if(strlen(trim($value)) > 0) {
$value = is_array($value) ? $value : urlencode($value);
$tempString[] = $key . "=" . $value;
}
else {
$tempString[] = $key;
}
}
$queryString = join('&', $tempString);
return $queryString;
}
/*
usage
*/
$cookiePath = "/tmp/cookies.txt";
$data['username'] = 'test';
$data['password'] = 'test123';
$data['submit'] = 'login';
// login
$result = cURLpost("http://www.foobar.com/login", $data, $cookiePath);
// go to my account
$result = cURLget("http://www.foobar.com/my-account", false, $cookiePath);
print "<xmp>";
print $result;
print "</xmp>";
?>
Langganan:
Posting Komentar (Atom)
Tidak ada komentar:
Posting Komentar