Изменения внесённые в библиотеку в период с 19.10.2022 по 20.10.2022(версия 1.a01xA), 31.10.2022 был добавлен метод getHeaderByName для получения одного заголовка по имени заголовка. 1 или true - всегда возвращается массив. Если результатов нет пустой массив. Если 1 результат массив из одного элемента public $startpos = 0;// номер символа с которого начинается поиск public $startplus = false; // Если задано положительное число(не нуль) то поиск осуществляется в диапазоне с символа $startpos плюс $startplus колличество символов. В данном случаи $endpos никак не учитывается, даже если отличается от false public $endpos = false; // номер символа которым заканчивается поиск public $startrequired = true; // Обязательно наличие начального поискового элемента, за исключением случаев если $start = false public $endrequired = true; // Обязательно наличие конечного поискового элемента, за исключением случаев если $end = false public $requiredifarray = false; // Если значение устанавливается в true когда $startrequired и $endrequired установлены оба в false к массиву результатов будет добавлен кусок строки контента, оставшийся после всех разбиений(фактически мусор). Нужно решить что в этом случаи делать с добавлениями $start и $end в результаты... public $startinclude = false; // true - Включать первый поисковый элемент в результат public $endinclude = false; // true - Включить последний поисковый элемент в результат public $trim = true; // Вырезать пробелы в начале и конце строки всех результатов public $tolose = false; // Если $tolose = true, $start и $end заданы и $endrequired = false то в случаи если $end не найден, дальнейшая разбивка не будет происходить по start. Для rparse зеркально public $content = false; // Хранение объекта для парсинга // При создании функции установки $startpos если устанавливается 0 требуется установить false // Если $startplus <=0 то обязательно установить его в false. Если $startplus не целое стоит сделать его целым // Если $start устанавливается в "" считаь $start = false // Если $end устанавливается в "" считаь $end = false // Если $moreone устанавливаенся в false установить в 0, если true, то установить в 1 public function getTagNameBeta($text=false) {//Получает имя тега. Входная строка должна начинаться с имени тега или символа / для закрывающего тега и не должна начинаться с символа < if (($text !==false) and ($textLen = strlen($text))) { $selfClosingFlag = false; $tagName = ""; for ($i=0;$i<$textLen;$i++) { $chr = substr($text,$i,1); if (($i == 0) and ($chr == "/")) { $selfClosingFlag = true; } else { $ord = ord($chr); if (($ord >= 65) and ($ord <= 90) or ($ord >= 97) and ($ord <= 122)) { $tagName .= $chr; } else { break; } } } return $tagName; } return false; } public function getCloseTagPositionBeta($tag=false,$text=false,$ignoreFirstOpeningTag=false) { if (($tag !== false) and ($text !== false)) { $positionOffset = -2; $tagOpeningsCounter = 0;//Сразу же устанавливается поправка на 2 пробела которые будут дописаны к началу строки ниже $lastIterationNoClosedTag = false;//Не закрытый тег на прошлой итерации if ($ignoreFirstOpeningTag) {$tagOpeningsCounter--;} $tag = strtolower($tag); $tagLen = strlen($tag); $text = " " . strtolower($text);//Добавляем 2 знака пробел в начало, чтобы не проверять при поиске минусовую позицию если имя тега пришло в начале строки, поскольку может потребоваться найти комбинацию перед именем тега while (($pos = strpos($text,$tag)) !== false) { if ($lastIterationNoClosedTag) { if (($posMoreSign = strpos($text,">")) !== false) { $text = substr($text,$posMoreSign+1); $lastIterationNoClosedTag = false; if ($posMoreSign < $pos) { $pos -= $posMoreSign+1; $positionOffset += $posMoreSign+1; } else {continue;} } else {break;} } $type = false; $textBeforeTag = substr($text,0,$pos); $posLessSignThis = false;//Это переменная была добавлена если требуется получить позицию начала закрывающего тега if (($tmp = substr($text,$pos-1,1)) == "<") { $type = "opening"; $textBeforeTag = substr($textBeforeTag,0,$pos-1); $posLessSignThis = $positionOffset + $pos - 1; } elseif (($tmp == "/") and (substr($text,$pos-2,1) == "<")) { $type = "covering"; $textBeforeTag = substr($textBeforeTag,0,$pos-2); $posLessSignThis = $positionOffset + $pos - 2; } if ((($posLessSign = strrpos($textBeforeTag,"<")) !== false) and ((($posMoreSign = strrpos($textBeforeTag,">")) === false) or ($posMoreSign < $posLessSign))) { $lastIterationNoClosedTag = true; $text = substr($text,$pos+$tagLen); $positionOffset += $pos+$tagLen; } else { $positionOffsetItem = $pos+$tagLen; $text = substr($text,$positionOffsetItem);//Остаётся найти в оставшейся части текста символ > $positionOffset += $positionOffsetItem; if ($type !== false) { if (($posMoreSign = strpos($text,">")) !== false) { if ($type == "opening") { $tagOpeningsCounter++; } else { if ($tagOpeningsCounter == 0) { //return $posLessSignThis;//Этой строкой можно вернуть позицию начала искомого закрывающего тега в переданном в функцию тексте return $positionOffset + $posMoreSign + 1;// плюс один это сам символ ">" } $tagOpeningsCounter--; } $positionOffsetItem = $posMoreSign+1; $text = " " . substr($text,($positionOffsetItem)); $positionOffsetItem -= 2; $positionOffset += $positionOffsetItem; } else { break;//Если strpos в If выше вернул false значит закрывающий тег отсуствует и можно выходить из цикла чтобы функция вернула false } } else { //echo noxss($text);echo "OPA END1"; } } } } return false; } public function beta2($tagName=false,$atrib="wm-nav-captures") { // $atrib = "wm-nav-captures"; $atribLen = strlen($atrib); $pos = strpos($this->content,$atrib); echo "$pos"; $tmp = substr($this->content,0,$pos); $pos1 = strrpos($tmp,"<"); if ($pos1 !== false) {echo 2; $pos2 = strrpos($tmp,">"); echo "[$pos1:$pos2]"; if ($pos1 > $pos2) {//внутри тега, а значит атрибут $tagTmp = substr($tmp,($pos1+1)); $tagName = $this->getTagNameBeta($tagTmp); if (!in_array($tagName,$this->$tagNames["notPaired"])) {//Если тег парный $continuationText = substr($this->content,$pos+$atribLen); if (($posTest = $this->getCloseTagPositionBeta($tagName,$continuationText,true)) !== false) { return substr($this->content,$pos1,($pos+$atribLen-$pos1)) . substr($continuationText,0,$posTest); } } echo "продолжение: " . noxss($tagTmp);exit; } else { echo "вне тега";//а значит не атрибут } } } public function returncontent ($content="") { // вернуть или массив или строку или false в зависимости от результатов и настроек return $content; } public function moreone($flag=nil) { if ($flag === nil) { return $this->moreone; } elseif(($flag === true) or ($flag == 1)) { $this->moreone = true; } elseif(($flag === false) or ($flag === 0)) { $this->moreone = false; } elseif (is_numeric($flag) and ($flag > 1)) { $this->moreone = $flag * 1; } else { return false; } return true; } public function strposTL($content="",$search="") { if ($this->tolower) { $content = strtolower($content); $search = strtolower($search); } return strpos($content,$search); } public function trim($flag=nil){ if ($flag === nil) { return $this->trim; } elseif($flag) { $this->trim = true; } else { $this->trim = false; } return true; } public function tolose($flag=nil) { if ($flag === nil) { return $this->tolose; } elseif($flag) { $this->tolose = true; } else { $this->tolose = false; } return true; } public function result($result="",$start="",$end="",$startyes=false,$endyes=false) {// вставляет начальные и конечные элементы в результат, а так же обрезает пробелы если это нужно if ($this->trim) { $result = trim($result); } if ($startyes and $this->startinclude) { $result = $start . $result; } if ($endyes and $this->endinclude) { $result = $result . $end; } return $result; } public function results($results=array(),$end=false) { // Тестовая штука для $this->tolose Предназначена когда $end=false и $this->tolose=true всегда возвращался один результат не зависимо от остальных настроек. Если убрать эту функцию то передавать ззначение $end в эту функцию не надо if ($this->tolose and !$end) { if (count($results)) { return $results[0]; } } // Тестовая штука закончилась if ($this->moreone == 0) { if (count($results)) { return $results[0]; } else { return false; } } return $results; } public function string() { // Вернуть контент объекта в формате string return $this->content; } public function a($content=false,$start=false,$end=false) { $results = array(); if (($content !== false) and ($content !== "")) { if (($this->startplus === false) and ($this->endpos !== false) and ($this->endpos < (strlen($content) - 1))) { $content = substr($content,0,($this->endpos+1)); } if ($this->startpos !== false) { if ($this->startpos <= (strlen($content) - 1)) { if ($this->startplus !== false) { $content = substr($content,$this->startpos,$this->startplus); } else { $content = substr($content,$this->startpos); } } else { $content = ""; } } if ($content != "") { $i = 0; do { $goodflag = false; $start2 = ""; // Реальный начальный элемент поиска из контента для подстановки с учётом регистра $end2 = ""; // Конечный элемент, аналогично $start2 if ($start !== false) { if (($pos = $this->strposTL($content,$start)) !== false) { $start2 = substr($content,$pos,strlen($start)); $content = substr($content,$pos+strlen($start)); $goodflag = true; } elseif ($this->startrequired) { break; // вернуть результаты что контента нет } } if ($end !== false) { if (($pos = $this->strposTL($content,$end)) !== false) { $end2 = substr($content,$pos,strlen($end)); $results[] = $this->result(substr($content,0,$pos),$start2,$end2,$goodflag,true); $content = substr($content,$pos+strlen($end)); $goodflag = true; } elseif ($this->endrequired) { break; } else { if ($goodflag) { if ((($pos = $this->strposTL($content,$start)) !== false) and !$this->tolose) { $results[] = $this->result(substr($content,0,$pos),$start2,$end2,$goodflag,false); } else { $results[] = $this->result($content,$start2,$end2,$goodflag,false); } } } } else { if ($goodflag) { if ((($pos = $this->strposTL($content,$start)) !== false) and !$this->tolose) { $results[] = $this->result(substr($content,0,$pos),$start2,$end2,$goodflag,false); } else { $results[] = $this->result($content,$start2,$end2,$goodflag,false); } } } if (!$goodflag) { if (!count($results) or $this->requiredifarray) { $results[] = $this->result($content,$start2,$end2,false,false); } break; } $i++; } while (($this->moreone == 1) or (($this->moreone > 1) and ($this->moreone > $i))); } } return $this->results($results,$end); } public function __toString() { return ($this->content . ""); } public function val() { return $this->content; } public function __construct($content = "") { $this->content = $content; return $this; } public function parse($start=false,$end=false) { $content = $this->content; $results = $this->a($content,$start,$end); $results2 = false; if (is_array($results)) { $results2 = array(); foreach ($results as $v) { $results2[] = new textparser($v); } } else { $results2 = new textparser($results); } return $results2; } } class curlPro { // Options public $fp, $ip, $port, $httphost = '', $uri = '/', $uagent = 'curlPro', $body = false, $head = false, $headarray, $requestheaderarray = array(), $httpprotokol = false, $httpcode = false, $httpcomment = false,$location = false, $contenttype = false, $charset = false, $servercharset = false,$autoencodingenabled=true; public $postarray = array(); public $postactivedata = false; public $cookiearray = array(); // Массив который используется курл для установки кук public $cookiesetarray = array(); // Массив с куками полученными от веб сервера в результате http/s запроса public $mysql = false; // Идентификатор подключения к mysql public $dbok = false; // Флаг побключения к базе данных public $cash = false; // Флаг работы с кешем public $linksArray = array(); // Двумерный массив ссылок. Под индексом 0 значение href, под индексом 1 - текст анкора public $imagesArray = array(); // Массив изображений public $userid = false; // Идентификатор пользователя в базе данных, за которым закрепляется кеш и куки public $dom = false; // Объект класса DOM. Используется для XML разбора полученной страницы public $httpsflag = false; // флаг использвания https public $referrer = ""; // REFERRER откуда осуществляется переход на указанную страницу public $requestContentType = false;//Content-Type запроса public $requestContentTypeCharset = false;//Кодировка запроса(указывается в контент type в изначальной версии только для JSON) // Methods function __construct() { $this->default_settings(); } function setRequestHeaderBeta($name=false,$value=false,$clear=false) { if ($name !== false) { if (is_array($name) and $name) { foreach ($name as $headerName => $headerValue) { if (($headerNameLower = strtolower($headerName)) == "cookie") { foreach(explode("; ",$headerValue) as $cookieItem) { $cookieItemAr = explode("=",$cookieItem); unset($cookieItem); if ((count($cookieItemAr) > 1) and (($cookieItemAr[0]."") != "") and (($cookieItemAr[1]."") != "")) { $cookieName = $cookieItemAr[0]; $cookieValue = $cookieItemAr[1]; if (count($cookieItemAr) > 2) {//Возможна ли такая ситуация не проверено unset($cookieItemAr[0]);unset($cookieItemAr[1]); $cookieValue .= "=" . implode($cookieItemAr,"="); } unset($cookieItemAr); } $this->cookiedata($cookieName,$cookieValue); } } elseif ($headerNameLower != "host") { $this->requestheaderarray[$headerName] = $headerValue; } } return true; } elseif (($name."") != "") { } } return false; } //Преобразует произвольный массив любого уровня вложенности в одномерный массив с ключами соответсвующими правилам оформления массивов для передачи методом POST и значениями соответствующие ключам function arrayConvertPostRequestFormat($array=false) { if ($array !== false) { $noKeys = true; if ($noKeys and (array_keys($array) == array_keys(array_keys($array)))) { foreach ($array as $key => $item) { if (is_array($item)) { $noKeys = false; break; } } } else { $noKeys = false; }//var_dump($noKeys); foreach ($array as $key => $item) {//echo 0; // if (array_key($array) != array_key(array_key($array))) {$noKeys = false;} if (is_array($item)) { if ($keyAddressLast == "") {//echo 1; $array = array_merge($array,arReqursive($item,$key)); // unset($array[$key]); } else {//echo 2; $array = array_merge($array,arReqursive($item,$keyAddressLast."[$key]")); } unset($array[$key]); } elseif ($keyAddressLast != "") { if ($noKeys and 0) {//Ранее ($noKeys and (array_keys($array) == array_keys(array_keys($array)))) $array[$keyAddressLast."[]"] = $item; $noKeys = false; } else { $array[$keyAddressLast."[".$key."]"] = $item; } unset($array[$key]); } } return $array; } return false; } // Установка или считывание флага https соединения function https($flag = null) { if ($flag === null) { $flag = $this->httpsflag; } else { if ($flag) { $flag = true; } else { $flag = false; } $this->httpsflag = $flag; } return $flag; } function referrer($referrer = null) { if ($referrer === null) { $referrer = $this->referrer; } else { $this->referrer = $referrer; } return $referrer; } function default_settings() { $this->newuseragent("User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0"); $this->port = 80; $this->newip('192.168.0.1'); $this->headarray = array(); return true; } function cashExtractLast ($n = 1) { If (is_int($n)) { If ($this->dbok) { $result = mysql_query("SELECT * FROM cp_cash ORDER BY code DESC LIMIT $n", $this->mysql); If ($result) { $array = array(); $array2 = array(); $count = mysql_num_rows($result) - 1; for ($i=0;$i<=$count;$i++) { $array[] = mysql_fetch_assoc($result); } for ($i=$count;$i>=0;$i--) { $array2[] = $array[$i]; } return $array2; } } } return false; } function setUserName($name = false) { if ($name) { $result = mysql_query("SELECT * FROM user WHERE username = ''"); If (mysql_num_rows($result) >= 1) { $mysqlmass = mysql_fetch_assoc($result); $this->userid = $mysqlmass["code"]; return true; } } return false; } function createDom() { If (!$this->dom) { If ($this->body) { $this->dom = new domDocument(); $this->dom->loadHTML($this->body); } If ($this->dom) { return $this->dom; } } return false; } function getTagBody($tagname = false, $tagattrs = false, $saveto = false, $loadin = false, $boolresult = false) { // If ($tagname or $tagattrs) { // If ($this->dom()) { // return true; // } // } return false; } function getimagesarray() { If (!count($this->imagesArray)) { If ($this->body) { $obj = new textparser($this->body); $obj->trim(false); foreach ($obj->parse("") as $v) { $hreftoresult = false; if (($src = array_shift($v->parse("src=",false))) !== null) { $kav = substr($src->string(),0,1); if ($kav = "\"" or $kav = "'") { if (($src = array_shift($src->parse($kav,$kav))) !== null) { $srctoresult = $src->string(); } } else { //надо как то без кавычки определить } } $this->imagesArray[] = $srctoresult; } /* If (1) { If ($this->body) { $dom = new domDocument(); $dom->loadHTML($this->body); $elementsList = $dom->getElementsByTagname('img'); $imgArray = array(); $imgCount = -1; for ($i=0;$i<$elementsList->length; $i++) { $node = $elementsList->item($i); If ($node->getAttribute('src')) { $imgCount++; $imgArray[$imgCount][0] = $node->getAttribute('src'); $childNodes = $node->childNodes; $imgArray[$imgCount][1] = ''; for ($t=0;$t<$childNodes->length;$t++) { $node = $childNodes->item($t); $imgArray[$imgCount][1] = $imgArray[$imgCount][1] . $dom->saveXML($node); } } } } } return $imgArray; */ } } return $this->imagesArray; } function getlinksarray() { If (!count($this->linksArray)) { If ($this->body) { $obj = new textparser($this->body); $obj->trim(false); foreach ($obj->parse("trim(false); $text = $v->string(); if (strlen($text) > 0) { $text = substr($text,0,1); if (($text == " ") or ($text == "\t") or ($text == "\n") or ($text == "\r")) { $v->tolose(true); if (($text = $v->parse(">")) !== null) { $hreftoresult = false; $text = $text->string(); $v->tolose(false); // работа по коиску текста ссылки завершена, переходим к определению значения href if (($href = array_shift($v->parse("href=",">"))) !== null) { $kav = substr($href->string(),0,1); if ($kav = "\"" or $kav = "'") { if (($href = array_shift($href->parse($kav,$kav))) !== null) { $hreftoresult = $href->string(); } } else { //надо как то без кавычки определить } } $this->linksArray[] = array($hreftoresult,$text); } } } } /* If (!$this->linksArray) { If ($this->body) { $dom = new domDocument(); $dom->loadHTML($this->body); $elementsList = $dom->getElementsByTagname('a'); $this->linksArray = array(); $linksCount = -1; for ($i=0;$i<$elementsList->length; $i++) { $node = $elementsList->item($i); If ($node->getAttribute('href')) { $linksCount++; $this->linksArray[$linksCount][0] = $node->getAttribute('href'); $childNodes = $node->childNodes; $this->linksArray[$linksCount][1] = ''; for ($t=0;$t<$childNodes->length;$t++) { $node = $childNodes->item($t); $this->linksArray[$linksCount][1] = $this->linksArray[$linksCount][1] . $dom->saveXML($node); } } } } } return $this->linksArray; */ } } return $this->linksArray; } function setcash ($flag = 1) { // Устанавливает флаг кеша. Если флаг установлен повторные запросы получают сохранённую информацию из БД а не из сети If ($flag) { $this->cash = true; } else { $this->cash = false; } return true; } function mysqldb ($db = false) { If ($db) { If ($this->mysql) { $result = mysql_select_db($db, $this->mysql); If ($result) { $this->dbok = true; return true; } } } $this->dbok = false; return false; } function mysqlconnect($host = false, $user = false, $password = '') { If ($host) { If ($user) { $this->mysql = mysql_connect($host,$user,$password); If ($this->mysql) { return true; } } } return false; } function getcookiesetarray() { return $this->cookiesetarray; } // Установить Cookie полученные от сервера. Дата добавления 11.03.2014 23:15 function setservercookie() { foreach ($this->getcookiesetarray() as $key => $value) { $this->cookiedata($key,$value); } } function cookiedata ($name = false, $value = false) { If ($name) { If ($value !== false) { $this->cookiearray[$name] = $value; } else { unset($this->cookiearray[$name]); } return true; } else { return false; } } function aceptbrowsercookie() { if (count($_COOKIE)) { foreach ($_COOKIE as $name => $value) { //$this->cookiedata($name,$value); } } return true; } function getcookiedata() { return $this->cookiearray; } function postjson($jsonString=false,$charset=false) { if (($jsonString !== false) and json_encode($jsonString)) { $this->postactivedata = $jsonString; $this->requestContentType = "application/json"; if ($charset === false) { $this->requestContentTypeCharset = "utf-8"; } else { $this->requestContentTypeCharset = $charset; } return true; } return false; } function post($name = false, $value = false) { return $this->postdata($name,$value); } function postdata ($name = false, $value = false) { If ($name) { If ($value !== false) { $this->postarray[$name] = $value; } else { unset($this->postarray[$name]); } return true; } else { return false; } } function aceptbrowserpost() { if (count($_POST)) { foreach ($_POST as $name => $value) { $this->postdata($name,$value); } } return true; } function getpostdata() { return $this->postarray; } function showhead() { return $this->head; } function setservercharset($charset = false) { $this->servercharset = $charset; return true; } function getheadarray() { return $this->headarray; } function getHeaderByName($name=false) { if ((($name."") != "") and is_array($this->headarray) and $this->headarray) { $name = strtolower($name); $nameLen = strlen($name) + 2; foreach ($this->headarray as $header) { if (strtolower(substr($header,0,$nameLen)) == ($name.": ")) { return substr($header,$nameLen); } } }echo "x"; return false; } function gethttpprotokol() { return $this->httpprotokol; } function gethttpcode() { return $this->httpcode; } function gethttpcomment() { return $this->httpcomment; } function getlocation() { return $this->location; } function getcontenttype() { return $this->contenttype; } function getcharset() { return $this->charset; } function autoencoding() { If (($this->servercharset === false) and (ini_get("default_charset") != "")) { $this->servercharset = ini_get("default_charset"); } If ($this->servercharset !== false) { If (strtolower($this->contenttype) == "text/html") { If ($this->charset != "") { $this->body = iconv($this->charset, $this->servercharset . "//TRANSLITE",$this->body); } } return true; } else { return false; } } function acepturi() { // Установить URI полученный из браузера $this->newuri(getenv("REQUEST_URI")); return true; } function newuri($uri = '') { If ($uri == '') { $this->uri = '/'; } else { If (mb_substr($uri,0,1) != '/') { $uri = '/' . $uri; } $this->uri = $uri; } } function newuseragent($uagent) { $this->uagent = $uagent; } function newip($ip = '') { if ($ip == '') { return false; } else { $this->ip = $ip; $this->httphost = $this->ip; return true; } } function newhttphost($host = false) { $this->httphost = $host; } function go() { $incash = -1; // -1 - кеширование не используется; 0 - кеширование используется страницы нет в кеше; 1 - кеширование используется страница есть в кеше if ($this->cash) { $result = mysql_query("SELECT * FROM cp_cash WHERE (host = '" . mysql_real_escape_string($this->httphost) . "') and (uri = '" . mysql_real_escape_string($this->uri) . "')"); $Amysqlmass = mysql_num_rows($result) - 1; If ($Amysqlmass >= 0) { $mysqlmass = mysql_fetch_assoc($result); $this->head = $mysqlmass["head"]; $this->body = $mysqlmass["body"]; $incash = 1; } else { $incash = 0; } } If ($incash < 1) { $ch = curl_init(); $https = ""; if ($this->httpsflag) { $https = "https://"; } curl_setopt($ch, CURLOPT_URL, $https . $this->ip . $this->uri); // set url to post to curl_setopt($ch, CURLOPT_TIMEOUT, 23); // times out after 4s curl_setopt($ch, CURLOPT_HEADER, 1); // times out after 4s // Не проверяем сертификаты при работе с https(следующие 2 строчки). При работе по HTTP эти строчки не мешают, поэтому не проверяем используется ли https // Иначе https сайты с недействительными или незаверенными(не подписанными) сертификатами не загрузятся curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $header = array(); $header[] = "Host: " . $this->httphost; if (is_array($this->requestheaderarray) and $this->requestheaderarray) { foreach ($this->requestheaderarray as $headrName => $headerValue) { if ((($headrName."") != "") and (($headerValue."") != "")) { $header[] = "$headrName: $headerValue"; } } } else { $header[] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:61.0) Gecko/20100101 Firefox/61.0"; $header[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; $header[] = "Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3"; $header[] = "Accept-Encoding: gzip, deflate, br"; // изпользуем добавление реферера через заголовки а не опцией курла, чтобы заголовок был в той же последовательности в которой он выводится в файрфоксе if ($this->referrer) { $header[] = "HTTP_REFERER: " . $this->referrer; } $header[] = "Connection: keep-alive"; $header[] = "Upgrade-Insecure-Request: 1"; // if (count($this->postarray)) { // $header[] = "CONTENT_TYPE: application/x-www-form-urlencoded"; // $header[] = "CONTENT_LENGTH: 76"; // } // $header[] = "Cookie: phpbb3_t48hi_u=1; phpbb3_t48hi_k=; phpbb3_t48hi_sid=c8f60461f0e9abe650a14653032d5e03"; // $header[] = "Cache-Control: max-age=0"; } if (($this->postactivedata !== false) and (strlen($this->postactivedata) >= 1)) { // if ($this->requestContentType !== false) { // $contentType = "Content-Type: " . $this->requestContentType; // if ($this->requestContentTypeCharset !== false) { // $contentType .= "; charset=utf-8"; // } // $header[] = $contentType; // } curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postactivedata); $this->postactivedata = false; } else { if (count($this->postarray)) { $post = array(); foreach ($this->postarray as $name => $value) { $post[] = $name . "=" . urlencode($value); $post[] = $name . "=" . $value; } curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, join('&', $post)); // Сброс пост данных после выполнения запроса $this->postarray = array(); } } if (count($this->cookiearray)) { foreach ($this->cookiearray as $name => $value) { //$cookie[] = $name . "=" . urlencode($value); // старый вариант. С ним не работала авторизация на mail.ru Возможно используется когда форма отправляется без application/x-www-form-urlencoded $cookie[] = $name . "=" . $value; } curl_setopt($ch, CURLOPT_COOKIE, join('; ', $cookie)); } curl_setopt($ch,CURLOPT_ENCODING , "gzip, deflate"); curl_setopt($ch,CURLOPT_RETURNTRANSFER , 1); // Не возвращать результат в браузер curl_setopt($ch, CURLOPT_HTTPHEADER, $header); $content = curl_exec($ch); // run the whole process curl_close($ch); }//echo "111"; //[НАЧАЛО]Если в ответ на запрос сервер вернул первой строкой HTTP/1.1 100 Continue и после двух переносов строк есть ещё данные, то данный заголовок с переносами строк будет вырезан/проигнорирован if ((strlen($content) > 25) and (strtolower(mb_substr($content,0,5)) == "http/") and (strtolower(mb_substr($content,8,17)) == " 100 continue\x0D\x0A\x0D\x0A")) { $content = mb_substr($content,25); } //[КОНЕЦ]Если в ответ на запрос сервер вернул первой строкой HTTP/1.1 100 Continue и после двух переносов строк есть ещё данные, то данный заголовок с переносами строк будет вырезан/проигнорирован If (mb_strpos($content,"\x0D\x0A\x0D\x0A")) {//echo "222";//$fp = fopen("tesssst.txt","w");fwrite($fp,$content);fclose($fp);echo $content; $this->head = mb_substr($content,0,mb_strpos($content,"\x0D\x0A\x0D\x0A")); $this->body = mb_substr($content,(mb_strpos($content,"\x0D\x0A\x0D\x0A")+4)); // Генерируем из body объект класса textparser // $this->body = new textparser($this->body); } else {echo 333;/*$fp = fopen("tesssst.txt","w");fwrite($fp,$content);fclose($fp);*/echo "stop";exit;} //echo 444; /* If (mb_strpos($content,"\x0D\x0D")) { $this->head = mb_substr($content,0,mb_strpos($content,"\x0D\x0D")); $this->body = mb_substr($content,(mb_strpos($content,"\x0D\x0D")+2)); // Генерируем из body объект класса textparser // $this->body = new textparser($this->body); } */ If ($incash == 0) { // Сохраняем в базу данных если кэш включон $result = mysql_query("INSERT INTO cp_cash (`host`,`uri`,`head`,`body`,`time`) VALUES ('" . mysql_real_escape_string($this->httphost) . "', '" . mysql_real_escape_string($this->uri) . "', '" . mysql_real_escape_string($this->head) . "', '" . mysql_real_escape_string($this->body) . "', '" . time() . "')", $this->mysql); } $this->headarray = preg_split("/[\r]\n/m",$this->head); foreach ($this->headarray as $value) { If (mb_substr(strtolower($value),0,5) == 'http/') { $value = mb_substr($value,5); If (mb_strpos($value," ")) { $this->httpprotokol = mb_substr($value,0,mb_strpos($value," ")); $value = mb_substr($value,mb_strpos($value," ")+1); If (mb_strpos($value," ")) { $this->httpcode = mb_substr($value,0,mb_strpos($value," ")); $value = mb_substr($value,mb_strpos($value," ")+1); If ($value != "") { $this->httpcomment = $value; } } } } If (mb_substr(strtolower($value),0,13) == 'content-type:') { $value = trim(mb_substr($value,13)); If (mb_strpos($value,";")) { $this->contenttype = mb_substr($value,0,mb_strpos($value,";")); $value = mb_substr($value,mb_strpos($value,";")+1); If (mb_strpos(strtolower($value),"charset=") !==false) { $this->charset = trim(mb_substr($value,(mb_strpos(strtolower($value),"charset=")+8))); } } else { $this->contenttype = $value; } } If (mb_substr(strtolower($value),0,11) == 'set-cookie:') { /* Set-Cookie:"Mpop=1394650954:5c6547575c7c0104190502190a1d00071c02054f6a5d5e465e07070602031e08020e1e5750535e5c50524352435651165450595a164047:nikolaevevge@mail.ru:; expires=Tue, 10 Jun 2014 19:02:34 GMT; path=/; domain=.mail.ru ssdc=4147faa666fd43028a0b96094dab5652; expires=Tue, 10 Jun 2014 19:02:34 GMT; path=/; domain=.auth.mail.ru; Secure; HttpOnly ssdc_info=4147:0:1394650954; expires=Tue, 10 Jun 2014 19:02:34 GMT; path=/; domain=.auth.mail.ru; HttpOnly t=obLD1AAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAACAAAEBwgcA; expires=Mon, 08 Sep 2014 19:02:34 GMT; path=/; domain=.mail.ru" "Mpop=1394650954:5c6547575c7c0104190502190a1d00071c02054f6a5d5e465e07070602031e08020e1e5750535e5c50524352435651165450595a164047:nikolaevevge@mail.ru:; expires=Tue, 10 Jun 2014 19:02:34 GMT; path=/; domain=.mail.russdc=4147faa666fd43028a0b96094dab5652; expires=Tue, 10 Jun 2014 19:02:34 GMT; path=/; domain=.auth.mail.ru; Secure; HttpOnlyssdc_info=4147:0:1394650954; expires=Tue, 10 Jun 2014 19:02:34 GMT; path=/; domain=.auth.mail.ru; HttpOnlyt=obLD1AAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAACAAAEBwgcA; expires=Mon, 08 Sep 2014 19:02:34 GMT; path=/; domain=.mail.ru" Cookie: Mpop=1394653298:6f5d4a62695b7272190502190a1d00071c02054f6a5d5e465e07070602031e08020e1e5750535e5c50524352435651165450595a164047:nikolaevevge@mail.ru:; t=obLD1AAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAACAAAEBwgcA */ $value = trim(mb_substr($value,11)); If (mb_strpos($value,"=")) { $name = mb_substr($value,0,mb_strpos($value,"=")); $value = mb_substr($value,mb_strpos($value,"=")+1); If (mb_strpos($value,";")) { $value = mb_substr($value,0,mb_strpos($value,";")); } If (($name != '') && ($value != '')) { $this->cookiesetarray[$name] = $value; } } } If (mb_substr(strtolower($value),0,9) == 'location:') { $this->location = trim(mb_substr($value,9)); } } if ($this->autoencodingenabled) { $this->autoencoding(); } $this->linksArray = array(); return new textparser($this->body); } }