Архив

Публикации с меткой ‘curl’
16 ноября 2017 Нет комментариев

Нужно используя CURL просто получить URL перенаправления, но не переходить по нему внутри CURL.

$post_fields=array(
	"field1"=>$value1,
	"field2"=>$value2,
);
$curl=curl_init();
curl_setopt($curl,CURLOPT_URL,'https://site.ru/path/');
curl_setopt($curl,CURLOPT_HEADER,1);
curl_setopt($curl,CURLOPT_POST,1);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,false);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post_fields);
$res=curl_exec($curl);
curl_close($curl);
preg_match_all('/^Location:(.*)$/mi',$res,$matches);
if(!empty($matches[1])){
	header("Location: ".trim($matches[1][0]),true,301);
}
exit();
Categories: PHP Tags: ,
13 февраля 2012 6 комментариев

Альтернатива, которую пришлось искать после перевода на платную основу Google Translate API.

Источник: http://habrahabr.ru/blogs/php/120174/

Проект на GihHub: https://github.com/Andrew8xx8/GoogleTranslater

Исходники:

  1. <?php
  2. /**
  3.  * GoogleTranslater is PHP interface for http://translate.google.com/
  4.  * It send request to google translate service, get response and provide 
  5.  * translated text.
  6.  *
  7.  * @author Andrew Kulakov <[email protected]>
  8.  * @version 1.0.0
  9.  * @license https://github.com/Andrew8xx8/GoogleTranslater/blob/master/MIT-LICENSE.txt
  10.  * @copyright Andrew Kulakov (c) 2011
  11.  */
  12.  
  13. class GoogleTranslater 
  14. {
  15.     /**
  16.      * @var string Some errors
  17.      */
  18.     private $_errors = "";
  19.  
  20.     /**
  21.      * Constructor
  22.      */
  23.     public function _construct() 
  24.     {
  25.         if (!function_exists('curl_init'))
  26.             $this->_errors = "No CURL support";
  27.     }   
  28.  
  29.     /**
  30.      * Translate text.
  31.      * @param  string $text          Source text to translate
  32.      * @param  string $fromLanguage  Source language
  33.      * @param  string $toLanguage    Destenation language
  34.      * @param  bool   $translit      If true function return transliteration of source text 
  35.      * @return string|bool           Translated text or false if exists errors
  36.      */
  37.     public function translateText($text, $fromLanguage = "en", $toLanguage = "ru", $translit = false) 
  38.     {
  39.         if (empty($this->_errors)) {
  40.             $result = "";
  41.             for($i = 0; $i < strlen($text); $i += 1000)
  42.             {
  43.                 $subText = substr($text, $i, 1000);
  44.  
  45.                 $response = $this->_curlToGoogle("http://translate.google.com/translate_a/t?client=te&text=".urlencode($subText)."&hl=ru&sl=$fromLanguage&tl=i$toLanguage&multires=1&otf=1&ssel=0&tsel=0&uptl=ru&sc=1");
  46.                 $result .= $this->_parceGoogleResponse($response, $translit);
  47. //                sleep(1); 
  48.             }
  49.             return $result;
  50.         } else
  51.             return false;
  52.     } 
  53.  
  54.     /**
  55.      * Translate array.
  56.      * @param  array  $array         Array with source text to translate
  57.      * @param  string $fromLanguage  Source language
  58.      * @param  string $toLanguage    Destenation language
  59.      * @param  bool   $translit      If true function return transliteration of source text 
  60.      * @return array|bool            Array  with translated text or false if exists errors
  61.      */     
  62.     public function translateArray($array, $fromLanguage = "en", $toLanguage = "ru", $translit = false) 
  63.     {
  64.         if (empty($this->_errors)) {
  65.             $text = implode("[<#>]", $array);
  66.             $response = $this->translateText($text, $fromLanguage, $toLanguage, $translit);
  67.             return $this->_explode($response);
  68.         } else
  69.             return false;
  70.     }
  71.  
  72.     public function getLanguages()
  73.     {
  74.         if (empty($this->_errors)) {
  75.             $page = $this->_curlToGoogle('http://translate.google.com/');
  76.             preg_match('%<select[^<]*?tl[^<]*?>(.*?)</select>%is', $page, $match);
  77.             preg_match_all("%<option.*?value=\"(.*?)\">(.*?)</option>%is", $match[0], $languages);
  78.             $result = Array();
  79.             for($i = 0; $i < count($languages[0]); $i++){
  80.                 $result[$languages[1][$i]] = $languages[2][$i]);
  81.             }
  82.             return $result;           
  83.         } else                 
  84.             return false; 
  85.     }
  86.  
  87.     public function getLanguagesHTML()
  88.     {
  89.         if (empty($this->_errors)) {
  90.             $page = $this->_curlToGoogle('http://translate.google.com/');
  91.             preg_match('%<select[^<]*?tl[^<]*?>(.*?)</select>%is', $page, $match);
  92.             return $match[1];
  93.         } else                 
  94.             return false; 
  95.     }
  96.  
  97.     public function getErrors()
  98.     {
  99.         return $this->_errors;
  100.     }
  101.  
  102.     private function _explode($text)
  103.     {        
  104.         $text = preg_replace("%\[\s*<\s*#\s*>\s*\]%", "[<#>]", $text);
  105.         return array_map('trim', explode('[<#>]', $text));
  106.     }
  107.  
  108.     private function _curlToGoogle($url)
  109.     {
  110.         $curl = curl_init();
  111.         curl_setopt($curl, CURLOPT_URL, $url);
  112.         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  113.         if (isset($_SERVER['HTTP_REFERER'])) {
  114.             curl_setopt($curl, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']);
  115.         }
  116.         curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.71 Safari/534.24");  
  117.         $response = curl_exec($curl);
  118.         // Check if any error occured
  119.         if(curl_errno($curl))
  120.         {
  121.             $this->_errors .=  "Curl Error: ".curl_error($curl);
  122.             return false;
  123.         }
  124.         curl_close($curl);
  125.         return $response;
  126.     }
  127.  
  128.     private function _parceGoogleResponse($response, $translit = false)
  129.     {
  130.         if (empty($this->_errors)) {
  131.             $result = "";            
  132.             $json = json_decode($response);           
  133.             foreach ($json->sentences as $sentence) {
  134.                 $result .= $translit ? $sentence->translit : $sentence->trans;  
  135.             }
  136.             return $result;
  137.         }  else {
  138.             return false;
  139.         }
  140.     }
  141. }
  142. ?>

Использование:

  1. <?php
  2. /**
  3.  * Sample. How to use GoogleTranslater.
  4.  *
  5.  * @author Andrew Kulakov <[email protected]>
  6.  * @version 1.0.0
  7.  * @license https://github.com/Andrew8xx8/GoogleTranslater/blob/master/MIT-LICENSE.txt
  8.  * @copyright Andrew Kulakov (c) 2011
  9.  * @licenze CI
  10.  */ 
  11.  
  12. require_once("GoogleTranslater.php");
  13.  
  14. // Create GT Object
  15.     $gt = new GoogleTranslater();
  16.  
  17. // Translate text
  18. // Usage: GoogleTranslater :: translateText(string $text, string $fromLanguage, string $tolanguage, bool $translit = false)
  19. $translatedText = $gt->translateText("
  20.     English literature is the literature written in the English language, including literature composed in English by writers not necessarily from England; for example, Robert Burns was Scottish, James Joyce was Irish, Joseph Conrad was born in Poland, Dylan Thomas was Welsh, Edgar Allan Poe was American, V.S. Naipaul was born in Trinidad, and Vladimir Nabokov was Russian, but all are considered important writers in the history of English literature. In other words, English literature is as diverse as the varieties and dialects of English spoken around the world. In academia, the term often labels departments and programmes practising English studies in secondary and tertiary educational systems. Despite the variety of authors of English literature, the works of William Shakespeare remain paramount throughout the English-speaking world.
  21.     This article primarily deals with some of the literature from Britain written in English. For literature from specific English-speaking regions, consult the see also section, bottom of the page
  22.     The first works in English, written in Old English, appeared in the early Middle Ages (the oldest surviving text is Cædmon's Hymn). The oral tradition was very strong in the early English culture and most literary works were written to be performed. Epic poems were thus very popular and many, including Beowulf, have survived to the present day in the rich corpus of Anglo-Saxon literature that closely resemble today's Icelandic, Norwegian, North Frisian and the Northumbrian and Scots English dialects of modern English. Much Old English verse in the extant manuscripts is probably a milder adaptation of the earlier Germanic war poems from the continent. When such poetry was brought to England it was still being handed down orally from one generation to another, and the constant presence of alliterative verse, or .consonant rhyme (today's newspaper headlines and marketing abundantly use this technique such as in Big is Better) helped the Anglo-Saxon people remember it. Such rhyme is a feature of Germanic languages and is opposed to vocalic or end-rhyme of Romance languages. But the first written literature dates to the early Christian monasteries founded by St. Augustine of Canterbury and his disciples and it is reasonable to believe that it was somehow adapted to suit to needs of Christian readers.
  23.     ", "en", "ru");
  24.     if ($translatedText !== false) {
  25.         echo $translatedText;
  26.     } else {
  27.         //If some errors present
  28.         echo $gt->getErrors(); 
  29.     }
  30.  
  31. // Crasy stuff. Translate array
  32. // Usage: GoogleTranslater :: translateArray(array $array, string $fromLanguage, string $tolanguage, bool $translit = false)
  33.     $translatedArray = $gt->translateArray(array("Some", "Words", "To", "Translate"), "en", "ru");
  34.     if ($translatedArray !== false) {
  35.         print_r($translatedArray);
  36.     } else {
  37.         echo $gt->getErrors(); 
  38.     }    
  39. ?>

Опечатка (убрать закрывающуюся скобку):

  1. $result[$languages[1][$i]] = $languages[2][$i];

Спасибо автору.

Categories: PHP, Web Tags: ,
13 февраля 2012 Нет комментариев

Взято с http://www.som3on3.com/programming/php/php-bing-translate-api/

<?php
define('BING_API', 'YOUR_API_KEY');
 
function loadData($url, $ref = false) {
	$chImg = curl_init($url);
	curl_setopt($chImg, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($chImg, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0) Gecko/20100101 Firefox/4.0");
	if ($ref) {
		curl_setopt($chImg, CURLOPT_REFERER, $ref);
	}
	$curl_scraped_data = curl_exec($chImg);
	curl_close($chImg);
	return $curl_scraped_data;
}
 
function translate($text, $from = 'en', $to = 'fr') {
	$data = loadData('http://api.bing.net/json.aspx?AppId=' . BING_API . '&Sources=Translation&Version=2.2&Translation.SourceLanguage=' . $from . '&Translation.TargetLanguage=' . $to . '&Query=' . urlencode($text));
	$translated = json_decode($data);
	if (sizeof($translated) > 0) {
		if (isset($translated->SearchResponse->Translation->Results[0]->TranslatedTerm)) {
			return $translated->SearchResponse->Translation->Results[0]->TranslatedTerm;
		} else {
			return false;
		}
	} else {
		return false;
	}
}
?>

Использование:

<?php
echo translate('Hello World', 'en', 'fr');
?>

Еще по теме: http://habrahabr.ru/blogs/javascript/133940/

Categories: PHP, Web Tags: ,
4 августа 2010 8 комментариев

Имеется форма на сайте, при сабмите которой POST запросы должны отправляться на сторонний сайт, и у себя мы должны выводить полученные со стороннего сайта результаты.
1. Ну сама наша форма:

echo '<form action="" method="post">';
	echo 'Фамилия';
		echo '<input type="text" name="lastName" size="10" value="'.$_POST['lastName'].'" />';
	echo 'Имя';
		echo '<input type="text" name="firstName" size="10" value="'.$_POST['firstName'].'" />';
	echo '<input type="submit" name="searchButton" value="Поиск" />';
echo '</form>';

value для text-inputов добавлены для того чтобы после самбита формы указанные данные оставались введенными, можно и без этого
2. Если форма была отправлена:

if (!empty($_POST)) {
	$curl = curl_init(); //инициализация сеанса
	curl_setopt($curl, CURLOPT_URL, 'http://example.com/'); //урл сайта к которому обращаемся
	curl_setopt($curl, CURLOPT_HEADER, 1); //выводим заголовки
	curl_setopt($curl, CURLOPT_POST, 1); //передача данных методом POST
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //теперь curl вернет нам ответ, а не выведет
	curl_setopt($curl, CURLOPT_POSTFIELDS, //тут переменные которые будут переданы методом POST
	array (
		'lastName'=>$_POST['lastName'],
		'firstName'=>$_POST['firstName'],
		'searchButton'=>'get' //это на случай если на сайте, к которому обращаемся проверяется была ли нажата кнопка submit, а не была ли оправлена форма
	));
	curl_setopt($curl, CURLOPT_USERAGENT, 'MSIE 5'); //эта строчка как-бы говорит: "я не скрипт, я IE5" :)
	curl_setopt ($curl, CURLOPT_REFERER, "http://ya.ru"); //а вдруг там проверяют наличие рефера
	$res = curl_exec($curl);
	//если ошибка то печатаем номер и сообщение
	if(!$res) {
		$error = curl_error($curl).'('.curl_errno($curl).')';
		echo $error;
	}
	else {
		//если результат содержит то что нам надо (проверяем регуляркой), а в данном случае это табличка с классом yaResultat, то выводим ее.
		if (preg_match("/\<table class\='yaResultat'(.+)\<\/table\>/isU", $res, $found)) {
			$content = $found[0];
			echo $content; //перед этим его конечно можно обработать всякими str_replace и т.д.
		}
		else {
			echo "<p>Неизвестная ошибка</p>"; //а если табличики с результатами нет, то печатать нечего и мы незнаем что делать :(
		}
	}
	curl_close($curl);
}

Хорошие ссылки:
http://www.web-junior.net/otpravka-post-zaprosov-s-pomoshhyu-php-otpravka-fajjlov/
http://www.web-junior.net/otpravka-post-zaprosov-s-pomoshhyu-php-chast-2/
http://www.sql.ru/forum/actualthread.aspx?tid=750546

Categories: PHP Tags: ,