Невероятные вещи с помощью PHP и cURL

Невероятные вещи с помощью PHP и cURL
  • Добавить комментарии
  • Печать
  • Добавить в избранные

cURL и его PHP расширение — полезный инструмент для таких задач, как моделирование веб-браузера, обработки различных форм или авторизации для веб-служб.

В этой статье мы собрали самые востребованные вещи, которые вы сможете сделать с помощью PHP и cURL.

Проверка на доступность определенного сайта

Хотите проверять доступность определенного сайта? cURL вам может помочь. Этот скрипт можно использовать в кроне для мониторинга ваших сайтов.

Не забудьте поменять в 3 строке адрес сайта.

<?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;
       }
?>

Источник: http://css-tricks.com/snippets/php/check-if-website-is-available/

cURL замена для file_get_contents ()

Функция file_get_contents() очень полезна, но к сожалению, она отключена для большинства хостингов. Используя cURL, вы сможете заменить функцию file_get_contents() на похожую.

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;
}

Источник: http://snipplr.com/view/4084

Получение последнего Твиттер статуса

Используя PHP и cURL, вы можете получить статус определенного пользователя из Твиттера.

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);
}

Функция супер-проста в использовании:

echo get_status('catswhocode');

Источник: http://www.catswhocode.com/blog/php-snippets-to-interact-with-twitter

Twitter: проверка дружбы между двумя пользователями

Если вам нужна информация о том, следит ли определенный пользователь за вами или за кем нибудь еще, то с помощью Твиттер API можно проверить такую связь. Данный сниппет вернет true, если два пользователя, которых можно задать в строках 18 и 19, являются друзьями. Если не так, то вернется false.

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"

Источник: http://www.catswhocode.com/blog/php-snippets-to-interact-with-twitter

Загрузка и сохранение изображений с определенной страницы с помощью cURL

Этот набор функций делает простую вещь — сохраняет все изображения с указанной страницы на вашем веб-сервере.

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;
}

Источник: http://stackoverflow.com/questions/7747875/grab-download-images-from-multiple-pages-using-php-preg-match-all-curl

Конвертирование валют с помощью cURl и Google

Сам функционал по конвертированию валют сделать не трудно, труднее добиться получения актуальных значений стоимости. Для получения таких данных мы будем использовать сервис Google. В основе нашего функционала будет функция currency(), для которой нужны 3 параметра: from, to и sum.

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.

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. Далее рабочий пример:

// 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/

Источник: catswhocode.com

PS. Если вам не очень нравится язык PHP, то вы можете посмотреть ресурс coding4.net - программирование на С#. Может быть вы найдете там интересные материалы по программированию.

Тэги: ,

Нет комментариев на “Невероятные вещи с помощью PHP и cURL”

добавить комментарий

Написать ответ

» Подписаться на комментарии к этой статье по RSS