cURL и его PHP расширение — полезный инструмент для таких задач, как моделирование веб-браузера, обработки различных форм или авторизации для веб-служб.
В этой статье мы собрали самые востребованные вещи, которые вы сможете сделать с помощью PHP и cURL.
Проверка на доступность определенного сайта
Хотите проверять доступность определенного сайта? cURL вам может помочь. Этот скрипт можно использовать в кроне для мониторинга ваших сайтов.
Не забудьте поменять в 3 строке адрес сайта.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php if (isDomainAvailible('http://www.css-tricks.com')) { echo "Up and running!"; } else { echo "Woops, nothing found there."; } //возвращает true, если домен доступен и false, если нет function isDomainAvailible($domain) { //проверка на правильность url if(!filter_var($domain, FILTER_VALIDATE_URL)) { return false; } //инициализация curl $curlInit = curl_init($domain); curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10); curl_setopt($curlInit,CURLOPT_HEADER,true); curl_setopt($curlInit,CURLOPT_NOBODY,true); curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true); //получение ответа $response = curl_exec($curlInit); curl_close($curlInit); if ($response) return true; return false; } ?> |
Источник:
cURL замена для file_get_contents ()
Функция file_get_contents()
очень полезна, но к сожалению, она отключена для большинства хостингов. Используя cURL, вы сможете заменить функцию file_get_contents()
на похожую.
1 2 3 4 5 6 7 8 9 10 11 12 |
function file_get_contents_curl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser. curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); curl_close($ch); return $data; } |
Источник:
Получение последнего Твиттер статуса
Используя PHP и cURL, вы можете получить статус определенного пользователя из Твиттера.
1 2 3 4 5 6 7 8 9 10 11 |
function get_status($twitter_id, $hyperlinks = true) { $c = curl_init(); curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1"); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $src = curl_exec($c); curl_close($c); preg_match('/<text>(.*)<\/text>/', $src, $m); $status = htmlentities($m[1]); if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", '<a href="%5C%22%5C%5C0%5C%22">\\0</a>', $status); return($status); } |
Функция супер-проста в использовании:
1 |
echo get_status('catswhocode'); |
Источник:
Проверка дружбы между двумя пользователями с помощью Твиттера
Если вам нужна информация о том, следит ли определенный пользователь за вами или за кем нибудь еще, то с помощью Твиттер API можно проверить такую связь. Данный сниппет вернет true
, если два пользователя, которых можно задать в строках 18 и 19, являются друзьями. Если не так, то вернется false
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function make_request($url) { $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); $result = curl_exec($ch); curl_close($ch); return $result; } /* gets the match */ function get_match($regex,$content) { preg_match($regex,$content,$matches); return $matches[1]; } /* persons to test */ $person1 = 'phpsnippets'; $person2 = 'catswhocode'; /* send request to twitter */ $url = 'https://api.twitter.com/1/friendships/exist'; $format = 'xml'; /* check */ $persons12 = make_request($url.'.'.$format.'?user_a='.$person1.'&user_b='.$person2); $result = get_match('/<friends>(.*)<\/friends>/isU',$persons12); echo $result; // returns "true" or "false" |
Источник:
Загрузка и сохранение изображений с определенной страницы с помощью cURL
Этот набор функций делает простую вещь — сохраняет все изображения с указанной страницы на вашем веб-сервере.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function getImages($html) { $matches = array(); $regex = '~http://somedomain.com/images/(.*?)\.jpg~i'; preg_match_all($regex, $html, $matches); foreach ($matches[1] as $img) { saveImg($img); } } function saveImg($name) { $url = 'http://somedomain.com/images/'.$name.'.jpg'; $data = get_data($url); file_put_contents('photos/'.$name.'.jpg', $data); } $i = 1; $l = 101; while ($i < $l) { $html = get_data('http://somedomain.com/id/'.$i.'/'); getImages($html); $i += 1; } |
Конвертирование валют с помощью cURl и Google
Сам функционал по конвертированию валют сделать не трудно, труднее добиться получения актуальных значений стоимости. Для получения таких данных мы будем использовать сервис Google. В основе нашего функционала будет функция currency()
, для которой нужны 3 параметра: from
, to
и sum
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $data = explode('"', $rawdata); $data = explode(' ', $data['3']); $var = $data['0']; return round($var,2); } |
Источник: http://l33ts.org/forum/Thread-PHP-Convert-currencies-using-Google-and-cURL-Snippet
Как удаленно получить размера файла с помощью cURL
Вам нужно знать размер определенного файла? Следующая функция вам поможет. Для ее запуска нужны 3 параметра: url
файла, и если файл под паролем, то username
и password
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function remote_filesize($url, $user = "", $pw = ""){ ob_start(); $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); if(!empty($user) && !empty($pw)) { $headers = array('Authorization: Basic ' . base64_encode("$user:$pw")); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } $ok = curl_exec($ch); curl_close($ch); $head = ob_get_contents(); ob_end_clean(); $regex = '/Content-Length:\s([0-9].+?)\s/'; $count = preg_match($regex, $head, $matches); return isset($matches[1]) ? $matches[1] : "unknown"; } |
Источник: http://megasnippets.com/source-codes/php/get_remote_filesize
Выгрузка на FTP с помощью cURL
В PHP уже есть FTP библиотека, но вы можете использовать для выгрузки файлов cURL. Далее рабочий пример:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// open a file pointer $file = fopen("/path/to/file", "r"); // the url contains most of the info needed $url = "ftp://username:password@mydomain.com:21/path/to/new/file"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // upload related options curl_setopt($ch, CURLOPT_UPLOAD, 1); curl_setopt($ch, CURLOPT_INFILE, $fp); curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/path/to/file")); // set for ASCII mode (e.g. text files) curl_setopt($ch, CURLOPT_FTPASCII, 1); $output = curl_exec($ch); curl_close($ch); |
Источник: http://net.tutsplus.com/tutorials/php/techniques-and-resources-for-mastering-curl/
Как создать простого робота-паука на PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?php function crawl_page($url, $depth = 5) { static $seen = array(); if (isset($seen[$url]) || $depth === 0) { return; } $seen[$url] = true; $dom = new DOMDocument('1.0'); @$dom->loadHTMLFile($url); $anchors = $dom->getElementsByTagName('a'); foreach ($anchors as $element) { $href = $element->getAttribute('href'); if (0 !== strpos($href, 'http')) { $path = '/' . ltrim($href, '/'); if (extension_loaded('http')) { $href = http_build_url($url, array('path' => $path)); } else { $parts = parse_url($url); $href = $parts['scheme'] . '://'; if (isset($parts['user']) && isset($parts['pass'])) { $href .= $parts['user'] . ':' . $parts['pass'] . '@'; } $href .= $parts['host']; if (isset($parts['port'])) { $href .= ':' . $parts['port']; } $href .= $path; } } crawl_page($href, $depth - 1); } echo "URL:",$url,PHP_EOL,"CONTENT:",PHP_EOL,$dom->saveHTML(),PHP_EOL,PHP_EOL; } crawl_page("http://hobodave.com", 2); ?> |
Источник: