เขียน php ให้สามารถ login เว็บอื่นด้วย cURL

login เว็บอื่นด้วย cURL

The other day I wanted to automate some downloading from a username and password secured website. I wrote a quick script and it is working like a dream, below is the CURL part of the code that does the logging in and download.

$username = 'myuser';
$password = 'mypass';
$loginUrl = 'http://www.example.com/login/';
//init curl
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&pass='.$password);
//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request (the login)
$store = curl_exec($ch);
//the login is now done and you can continue to get the
//protected content.
//set the URL to the protected file
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/protected/download.zip');
//execute the request
$content = curl_exec($ch);
//save the data to disk
file_put_contents('~/download.zip', $content);


ตัวอย่างการเขียนโปรแกรม Post  ลง SMF โดยตรง

// post smf posttosmf("หัวข้อ","ข้อความ","username","password","4","http://forum.nonvisual.com/");


function posttosmf($subj, $mess, $user, $password, $board, $domain) { $ch = curl_init(); curl_setopt($ch, CURLOPT_COOKIESESSION, 1); curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt'); curl_setopt($ch, CURLOPT_USERAGENT, "Automatic SMF poster thing"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_HEADER, 1);

curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "user=".$user."&passwrd=".$password); curl_setopt($ch, CURLOPT_URL, "$domain?action=login2"); curl_exec($ch);

curl_setopt($ch, CURLOPT_URL, "$domain?action=post;board=".$board.".0"); $data = curl_exec($ch);

sleep(3); preg_match ( "", $data, $sc); preg_match ( "", $data, $seqnum); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "subject=".urlencode($subj)."&icon=xx&message=".urlencode($mess)."&notify=0&lock=0&goback=1&sticky=0&move=0&attachment%5B%5D=&attachmentPreview=&post=xxxxx&sc=".$sc[1]."&seqnum=4&seqnum=".$seqnum[1]); curl_setopt($ch, CURLOPT_URL, "$domain?action=post2;start=0;board=".$board); curl_exec($ch);

curl_close($ch);}

?>

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

หมายเหตุ: มีเพียงสมาชิกของบล็อกนี้เท่านั้นที่สามารถแสดงความคิดเห็น