cURL это PHP расширение библиотеки libcURL, инструмент при помощи которого Вы можете симулировать веб браузер. К примеру это может быть отправка формы для авторизации на сайте и получения результирующей страницы. В этой статье я собираюсь показать вам 10 невероятных вещей, которые Вы можете сделать с помощью PHP и CURL.
Обратите внимание, что некоторые из методов, показанные здесь, могут быть использованы для методов "черной" оптимизации а также для парсинга сайтов и кражи информации. Целью данной статьи является только ознакомление, пожалуйста, не используйте любой из фрагментов ниже в незаконных целях.
1 - Обновление своего фейсбук статуса
Хотите автоматически обновлять facebook статус, но не хотите заходить на facebook.com, вводить каждый раз логин и пароль, и, делать это со страниц своего сайта? Просто сохраните следующий код на вашем сервере, определить переменные, и вуаля!
<?PHP /******************************* * Facebook Status Updater * Christian Flickinger * http://nexdot.net/blog * April 20, 2007 *******************************/ $status = 'Новый статус'; $first_name = 'YOUR_FIRST_NAME'; $login_email = 'YOUR_LOGIN_EMAIL'; $login_pass = 'YOUR_PASSWORD'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php'); curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($login_email).'&pass='.urlencode($login_pass).'&login=Login'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt"); curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3"); curl_exec($ch); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php'); $page = curl_exec($ch); curl_setopt($ch, CURLOPT_POST, 1); preg_match('/name="post_form_id" value="(.*)" \/>'.ucfirst($first_name).'/', $page, $form_id); curl_setopt($ch, CURLOPT_POSTFIELDS,'post_form_id='.$form_id[1].'&status='.urlencode($status).'&update=Update'); curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php'); curl_exec($ch); ?>
Дальше интереснее
2 - получить скорость загрузки веб-сервера
Вы когда-нибудь хотели узнать точную скорость загрузки своего веб-сервера (или любого другого) Если да, то Вам понравится этот код. Просто в $url задаем адресс какого-либо доступного интернет ресурса, фото, видео или даже pdf документа. А дальше получаем полную статистику по загрузке этого ресурса Вашим сервером.
<?php error_reporting(E_ALL | E_STRICT); // Initialize cURL with given url $url = 'http://download.bethere.co.uk/images/61859740_3c0c5dbc30_o.jpg'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, 'Sitepoint Examples (thread 581410; http://www.sitepoint.com/forums/showthread.php?t=581410)'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($ch, CURLOPT_TIMEOUT, 60); set_time_limit(65); $execute = curl_exec($ch); $info = curl_getinfo($ch); // Time spent downloading, I think $time = $info['total_time'] - $info['namelookup_time'] - $info['connect_time'] - $info['pretransfer_time'] - $info['starttransfer_time'] - $info['redirect_time']; // Echo friendly messages header('Content-Type: text/plain'); printf("Загружено %d байт за %0.4f секунды.\n", $info['size_download'], $time); printf("Со скоростью %0.4f mbps\n", $info['size_download'] * 8 / $time / 1024 / 1024); printf("CURL сообщает скорость %0.4f mbps\n", $info['speed_download'] * 8 / 1024 / 1024); echo "\n\ncurl_getinfo() said:\n", str_repeat('-', 31 + strlen($url)), "\n"; foreach ($info as $label => $value) { printf("%-30s %s\n", $label, $value); } ?>
3 - Авторизация на Myspace с помощью Curl
<?php function login( $data, $useragent = 'Mozilla 4.01', $proxy = false ) { $ch = curl_init(); $hash = crc32( $data['email'].$data['pass'] ); $hash = sprintf( "%u", $hash ); $randnum = $hash.rand( 0, 9999999 ); if( $proxy ) curl_setopt( $ch, CURLOPT_PROXY, $proxy ); curl_setopt( $ch, CURLOPT_COOKIEJAR, '/tmp/cookiejar-'.$randnum ); curl_setopt( $ch, CURLOPT_COOKIEFILE, '/tmp/cookiejar-'.$randnum ); curl_setopt( $ch, CURLOPT_USERAGENT, $useragent ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_POST, 0); curl_setopt( $ch, CURLOPT_URL, 'http://www.myspace.com' ); $page = curl_exec( $ch ); preg_match( '/MyToken=(.+?)"/i', $page, $token ); if( $token[1] ) { curl_setopt( $ch, CURLOPT_URL, 'http://login.myspace.com/index.cfm?fuseaction=login.process&MyToken='.$token[1] ); curl_setopt( $ch, CURLOPT_REFERER, 'http://www.myspace.com' ); curl_setopt( $ch, CURLOPT_HTTPHEADER, Array( 'Content-Type: application/x-www-form-urlencoded' ) ); curl_setopt( $ch, CURLOPT_POST, 1 ); $postfields = 'NextPage=&email='.urlencode( $data['mail'] ).'&password='.urlencode( $data['pass'] ).'&loginbutton.x=&loginbutton.y='; curl_setopt( $ch, CURLOPT_POSTFIELDS, $postfields ); $page = curl_exec( $ch ); if( strpos( $page, 'SignOut' ) !== false ) { return $randnum; } else { preg_match( '/MyToken=(.+?)"/i', $page, $token ); preg_match( '/replace\("([^\"]+)"/', $page, $redirpage ); if( $token[1] ) { curl_setopt( $ch, CURLOPT_POST, 0 ); curl_setopt( $ch, CURLOPT_URL, 'http://home.myspace.com/index.cfm?&fuseaction=user&Mytoken='.$token[1] ); $page = curl_exec( $ch ); curl_close( $ch );; if( strpos( $page, 'SignOut' ) !== false ) { return $randnum; } } elseif( $redirpage[1] ) { curl_setopt( $ch, CURLOPT_REFERER, 'http://login.myspace.com/index.cfm?fuseaction=login.process&MyToken='.$token[1] ); curl_setopt( $ch, CURLOPT_URL, $redirpage[1] ); curl_setopt( $ch, CURLOPT_POST, 0 ); $page = curl_exec( $ch ); curl_close( $ch ); if( strpos( $page, 'SignOut' ) !== false ) { return $randnum; } } } } return false; } ?>
4 - опубликовать пост на вашем блоге WordPress, используя Curl
Многим нравится WordPress, а что если публиковать одну и туже новость или пост сразу в нескольких своих wordPress блогах. В этой CMS есть такая функция.При этом Вам не потребуется входить в панель администрирования. Хотя, преред ее использованием необходимо активировать опцию XMLRPC размещения в вашем блоге WordPress. Если эта опция не активирована, код не сможет вставлять что-либо в базе данных WordPress. Другое дело, убедитесь, что XMLRPC функции включена на вашем файле php.ini.
function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8') { $title = htmlentities($title,ENT_NOQUOTES,$encoding); $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding); $content = array( 'title'=>$title, 'description'=>$body, 'mt_allow_comments'=>0, // 1 to allow comments 'mt_allow_pings'=>0, // 1 to allow trackbacks 'post_type'=>'post', 'mt_keywords'=>$keywords, 'categories'=>array($category) ); $params = array(0,$username,$password,$content,true); $request = xmlrpc_encode_request('metaWeblog.newPost',$params); $ch = curl_init(); curl_setopt($ch, CURLOPT_POSTFIELDS, $request); curl_setopt($ch, CURLOPT_URL, $rpcurl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 1); $results = curl_exec($ch); curl_close($ch); return $results; ?>
5 - Проверка существования ссылки на ресурс, а точнее ее валидность
Это может быть полезно, к примеру для проверки битых ссылок в комментариях на форуме.
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.jellyandcustard.com/"); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); curl_close($ch) echo $data; ?>
6 - Оставить комментарий на WordPress блоге
Спемеры именно так и спамят Ваш любимый бложик, просто нужно заполнить все поля в массиве $postfields. Данный код можно переделать и для других сайтов, к примеру форумов. И легко можно использовать для продвижения на форумах своего ресурса.
<?php $postfields = array(); $postfields["action"] = "submit"; $postfields["author"] = "Spammer"; $postfields["email"] = "spammer@spam.com"; $postfields["url"] = "http://www.iamaspammer.com/"; $postfields["comment"] = "I am a stupid spammer."; $postfields["comment_post_ID"] = "123"; $postfields["_wp_unfiltered_html_comment"] = "0d870b294b"; //Url of the form submission $url = "http://www.ablogthatdoesntexist.com/blog/suggerer_site.php?action=meta_pass&id_cat=0"; $useragent = "Mozilla/5.0"; $referer = $url; //Initialize CURL session $ch = curl_init($url); //CURL options curl_setopt($ch, CURLOPT_POST, 1); //We post $postfields data curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); //We define an useragent (Mozilla/5.0) curl_setopt($ch, CURLOPT_USERAGENT, $useragent); //We define a refferer ($url) curl_setopt($ch, CURLOPT_REFERER, $referer); //We get the result page in a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //We exits CURL $result = curl_exec($ch); curl_close($ch); //Finally, we display the result echo $result;
7- получить общее число подписчиков по вашему блогу из сервиса FeedBurner.
Если вы блоггер, вы, вероятно, используя популярный сервис FeedBurner, который с помощью иконки показывает сколько людей "съели" Ваш канал. Этот сервис показывает число в виде миниатюрной иконки, которая не всем нравится и вписывается не в любой дизайн. С помощью следующего кода можно получить число подписчиков и встроить его куда угодно, в собственный дизайн
//get cool feedburner count $whaturl="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=feedburner-id"; //Initialize the Curl session $ch = curl_init(); //Set curl to return the data instead of printing it to the browser. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set the URL curl_setopt($ch, CURLOPT_URL, $whaturl); //Execute the fetch $data = curl_exec($ch); //Close the connection curl_close($ch); $xml = new SimpleXMLElement($data); $fb = $xml->feed->entry['circulation']; //end get cool feedburner count
8 - отправка POST запроса на сервер
function request($url,$post = 0,$ref=''){ $ch = curl_init();//здесь разве не нужно curl_setopt($ch, CURLOPT_URL, $url ); // отправляем на curl_setopt($ch, CURLOPT_HEADER, 0); // пустые заголовки curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // возвратить то что вернул сервер curl_setopt($ch, CURLOPT_REFERER, $ref); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // следовать за редиректами curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);// таймаут4 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt'); // сохранять куки в файл curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt'); curl_setopt($ch, CURLOPT_POST, $post!==0 ); // использовать данные в post if($post) curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $data = curl_exec($ch); curl_close($ch); return $data; } request('http://xdan.ru',http_build_query('text'=>'Произвольный текст'),'http://google.ru');
9 - получить содержимое веб-страницы в переменную PHP
Это пожалуй самое главное, что можно делать с Curl, и дает Вам бесконечные возможности. Именно с этого примера и стоит начать изучение построения сложных парсеров.
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "example.com"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); ?>
10 - Пост в Twitter используя PHP и CURL
Twitter очень популярен, уже долгое время, и у Вас, вероятно, уже есть учетная запись. (может ни одна) Почему бы не твитить через php автоматически
<?php // Set username and password $username = 'username'; $password = 'password'; // The message you want to send $message = 'is twittering from php using curl'; // The twitter API address $url = 'http://twitter.com/statuses/update.xml'; // Alternative JSON version // $url = 'http://twitter.com/statuses/update.json'; // Set up and execute the curl process $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, "$url"); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_POST, 1); curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message"); curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password"); $buffer = curl_exec($curl_handle); curl_close($curl_handle); // check for success or failure if (empty($buffer)) { echo 'message'; } else { echo 'success'; } ?>
Комментарии
$postfields["_wp_unfiltered_html_comment"] = "0d870b294b"; - откуда Вы возьмете это значение?
Где и как можно узнать цену
или купить? днепропетровская резка фанеры
post's to be just what I'm looking for. Does one offer guest writers to write content for you personally?
I wouldn't mind producing a post or elaborating on some of the subjects you write concerning here.
Again, awesome weblog!
am here now and would just like to say thank you for a marvelous post
and ɑ all round interesting blg (I also love the theme/design), I don’t have time to browse it all at the mijnute ƅbut I have book-mɑrked
it and alo ɑdded your RSS feeds, so when I have time I will
be back to read more, Please do keep up the excellent b.
Hеre is my wеbpage :: abоut mobile slot (Calvin)
It will always be սwefuⅼ too reаd thгogh content from other authors and practice a little
something frⲟm other ԝebsites.
Stop by my hоmepage :: read More
My homepage: read more (Tonja)
Many thanks fooг providing these detaiⅼs.
Also viѕit my web site; download here
Woᥙld youu be interested in tradiing lunks or mabe gurst
writing a ƅⅼog powt ooг vice-versa? My blog discusses a lot of the same subjects ɑs yours and
I feel we could gгeatly benefit frοm each other.
If you are intereѕtеd feel rеe to shoot me an e-mail.
I look forward to hearing from y᧐u! Excelllent blog by the way!
Feel free to surf to my web site about mobile Slot
knowledge, ѕo it's pleasant to read this webρage, and I used too
visit this blog dailү.
my webpage; download here
The clearness in your post iss just cool and i coսld assume you are an exlert on tһis subject.
Fine with your permission let me to grab your feed
to kеep up to date with forthcoming post.
Thanks a million and please carry on the rewarding work.
Also visit my web page check it heгe
I need to to thank yoᥙ for ones time for this particuⅼarly fantaѕtic read!!
I definitely enjoyed every bit of it andd i also have you savеd to favv to cһeck oսt neԝ thіngs
in your site.
Here is my web site about mobile slot
Have a look at my homepage :: check this
site
amusement account it. Look complex to more introduced agreeable from you!
By the way, how could we be in contact?
I've book marked it for later!
as compared too teⲭtbooks, asѕ I foun this piеce of writing at this weeb page.
Here is my web site ... kiss 918
am browsing this web site and reading very informative articles at this time.
RSS лента комментариев этой записи