0

Я недавно в теме изучения php.. Есть такая библиотека как curl...

Решил попробовать сделать зеркало на localhost, нашел на одном из блогов код плюс .htaccess заполненный по феншую, но результат такой: при загрузке первой страницы все отображается нормально, бывает что стили и js падают, но это не беда; как только пытаюсь пройти по ссылке зеркала редиректит сразу на внешнюю страницу или 404(((

Решил попробовать написать сам и вот, что примерно получилось:

$http   = 'http://';
    $domain = 'xxxx.ru';
    $var = $_SERVER['REQUEST_URI'];
    $host = $_SERVER['HTTP_HOST'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $http.$domain.$var);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$tuData = curl_exec($ch);
$tuData = str_replace($domain , $host , $tuData);
echo $tuData;

1 ответ 1

1

Киньте файлы .htaccess и index.php в корень сайта, внутри index.php в переменной $base поменяйте адрес сайта, который вы будете проксировать.

index.php

<?php

session_start();
ob_start();

/* config settings */
$base = "http://www.bbc.co.uk";  //set this to the url you want to scrape
$ckfile = '/tmp/simpleproxy-cookie-'.session_id();  //this can be set to anywhere you fancy!  just make sure it is secure.



/* all system code happens below - you should not need to edit it! */

//work out cookie domain
$cookiedomain = str_replace("http://www.","",$base);
$cookiedomain = str_replace("https://www.","",$cookiedomain);
$cookiedomain = str_replace("www.","",$cookiedomain);

$url = $base . $_SERVER['REQUEST_URI'];

if($_SERVER['HTTPS'] == 'on'){
    $mydomain = 'https://'.$_SERVER['HTTP_HOST'];
} else {
    $mydomain = 'http://'.$_SERVER['HTTP_HOST'];
}

// Open the cURL session
$curlSession = curl_init();

curl_setopt ($curlSession, CURLOPT_URL, $url);
curl_setopt ($curlSession, CURLOPT_HEADER, 1);


if($_SERVER['REQUEST_METHOD'] == 'POST'){
    curl_setopt ($curlSession, CURLOPT_POST, 1);
    curl_setopt ($curlSession, CURLOPT_POSTFIELDS, $_POST);
}

curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT,30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt ($curlSession, CURLOPT_COOKIEJAR, $ckfile); 
curl_setopt ($curlSession, CURLOPT_COOKIEFILE, $ckfile);

//handle other cookies cookies
foreach($_COOKIE as $k=>$v){
    if(is_array($v)){
        $v = serialize($v);
    }
    curl_setopt($curlSession,CURLOPT_COOKIE,"$k=$v; domain=.$cookiedomain ; path=/");
}

//Send the request and store the result in an array
$response = curl_exec ($curlSession);

// Check that a connection was made
if (curl_error($curlSession)){
        // If it wasn't...
        print curl_error($curlSession);
} else {

    //clean duplicate header that seems to appear on fastcgi with output buffer on some servers!!
    $response = str_replace("HTTP/1.1 100 Continue\r\n\r\n","",$response);

    $ar = explode("\r\n\r\n", $response, 2); 


    $header = $ar[0];
    $body = $ar[1];

    //handle headers - simply re-outputing them
    $header_ar = explode("\n",$header);  
    foreach($header_ar as $k=>$v){
        if(!preg_match("/^Transfer-Encoding/",$v)){
            $v = str_replace($base,$mydomain,$v); //header rewrite if needed
            header(trim($v));
        }
    }

  //rewrite all hard coded urls to ensure the links still work!
    $body = str_replace($base,$mydomain,$body);

    print $body;

}

curl_close ($curlSession);

.htaccess

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /index.php [L]

Полностью рабочий PHP-прокси в рамках одного домена с поддержкой куки. Данное решение также является отличным и несложным для понимания (благодаря обилию комментариев) примером того, как это должно работать.

Данный код не мой, я взял его из репозитория Google Code и слегка подправил для совместимости с PHP 7.

9
  • Огромное спасибо за помощь, но у меня не сработало как надо(( возможен ли такой вариант , что проблемы с локалкой? Использую openserver...
    – Vinotti
    2 ноя 2016 в 21:16
  • Можете подробнее описать проблему? Например, какие ошибки возникли к процессе выполнения скрипта.
    – Petr Flaks
    2 ноя 2016 в 21:17
  • Запускаю на локалке , пытаюсь пройти по ссылкам, и после клика по любой из них 404 вылазиет..
    – Vinotti
    2 ноя 2016 в 21:19
  • Я с Open Server, к сожалению, не знаком, поэтому скажите: у вас там Apache? Если да, то установите для вашего сайта AllowOverride All в настройках Apache, чтобы заработал файл .htaccess.
    – Petr Flaks
    2 ноя 2016 в 21:29
  • Поменял, выдает такое вот Function split() is deprecated in W:\domains\localhost\sock\index.php on line 75,
    – Vinotti
    2 ноя 2016 в 21:45

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.