3v4l.org

run code in 500+ PHP versions simultaneously
<?php // test harness: fake request $_SERVER['REQUEST_URI'] = '/blog/some-post?x=1'; $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REMOTE_ADDR'] = '203.0.113.7'; $_SERVER['HTTP_COOKIE'] = 'PHPSESSID=abc; _np_vid=1; _ib_x=2'; $_SERVER['HTTP_USER_AGENT'] = 'test-agent'; $_SERVER['HTTP_X_FORWARDED_HOST'] = 'evil.example'; $_SERVER['HTTP_AUTHORIZATION'] = 'Basic secret'; /** * inblog 서브디렉토리 연결용 PHP 중계 스크립트 * * https://{내 도메인}{블로그 경로}/... 요청을 https://proxy.inblog.dev/{inblog 서브도메인}/... 로 * 전달하고, 받은 응답을 방문자에게 그대로 돌려줍니다. * 루트 .htaccess 의 RewriteRule 이 블로그 경로 요청만 이 파일로 보냅니다. * * 요구 사항: PHP 5.3 이상, cURL 확장(TLS 1.2 지원) */ // ---- 설정: 인블로그 대시보드에 입력한 주소로 채워진 값입니다 ---- // inblog 기본 주소 {서브도메인}.inblog.io 의 서브도메인 $inblogSubdomain = 'YOUR_INBLOG_SUBDOMAIN'; // 블로그를 연결한 내 사이트의 대표 도메인 $publicHost = 'www.example.com'; // 블로그가 열리는 경로 (끝에 슬래시 없이) $basePath = '/blog'; // --------------------------------------- $upstreamOrigin = 'https://proxy.inblog.dev'; // PHP 경고 문구가 응답에 섞이면 압축된 본문이 깨지므로 화면 출력을 끕니다. @ini_set('display_errors', '0'); // inblog 가 방문 집계에 쓰는 쿠키만 전달합니다. 내 사이트의 로그인 세션 쿠키는 전달하지 않습니다. $forwardedCookiePrefixes = array('_np_', '_ib_', '_inblog'); // inblog 로 전달하지 않는 요청 헤더 ($_SERVER 키에서 HTTP_ 를 뗀 이름) $skippedRequestHeaders = array( 'HOST', 'COOKIE', 'AUTHORIZATION', 'PROXY_AUTHORIZATION', 'CONNECTION', 'PROXY_CONNECTION', 'KEEP_ALIVE', 'TE', 'TRAILER', 'TRANSFER_ENCODING', 'UPGRADE', 'EXPECT', 'CONTENT_LENGTH', 'CONTENT_TYPE', 'X_REAL_IP', 'CDN_LOOP', 'VIA', 'FORWARDED' ); // 뒤쪽 다섯 개는 카페24 웹호스팅이 내부에서 붙이는 헤더입니다. $skippedRequestHeaderPrefixes = array( 'X_FORWARDED_', 'X_INBLOG_', 'CF_', 'CAFE24_', 'HOSTING_', 'MOD_SECURITY_', 'X_SERVER_', 'X_SIMPLEXI' ); // 방문자에게 돌려주지 않는 응답 헤더 $skippedResponseHeaders = array( 'connection', 'keep-alive', 'proxy-authenticate', 'trailer', 'transfer-encoding', 'upgrade', 'server', 'date', 'alt-svc', 'strict-transport-security', 'report-to', 'nel' ); $relayState = array('status' => 0, 'headers' => array(), 'sent' => false); function inblog_relay_fail($status, $message) { header('X-Inblog-Relay: php', true, $status); header('Content-Type: text/plain; charset=utf-8'); header('Cache-Control: no-store'); header('X-Robots-Tag: noindex'); echo $message; exit; } function inblog_relay_starts_with_any($value, $prefixes) { foreach ($prefixes as $prefix) { if (strncmp($value, $prefix, strlen($prefix)) === 0) { return true; } } return false; } function inblog_relay_on_header($curl, $line) { global $relayState; $trimmed = trim($line); if (preg_match('#^HTTP/\S+\s+(\d{3})#', $trimmed, $match)) { // 새 상태줄이 오면(100 Continue 다음의 실제 응답 등) 헤더를 다시 모읍니다. $relayState['status'] = (int) $match[1]; $relayState['headers'] = array(); } elseif (strpos($trimmed, ':') > 0) { $relayState['headers'][] = $trimmed; } return strlen($line); } function inblog_relay_send_headers() { global $relayState, $skippedResponseHeaders; if ($relayState['sent']) { return; } $relayState['sent'] = true; header('X-Inblog-Relay: php', true, $relayState['status']); $seenNames = array(); foreach ($relayState['headers'] as $headerLine) { $name = strtolower(trim(substr($headerLine, 0, strpos($headerLine, ':')))); if (in_array($name, $skippedResponseHeaders)) { continue; } // 같은 이름이 여러 번 오는 헤더(Set-Cookie, Link 등)는 두 번째부터 덧붙입니다. header($headerLine, !isset($seenNames[$name])); $seenNames[$name] = true; } } function inblog_relay_on_body($curl, $chunk) { inblog_relay_send_headers(); echo $chunk; flush(); return strlen($chunk); } if (!function_exists('curl_init')) { // cURL 확장이 없으면 inblog 로 요청을 보낼 수 없습니다. inblog_relay_fail(500, 'cURL extension is required'); } // ---- 1. 요청 경로 확인 ---- $requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; $baseLength = strlen($basePath); $rest = (string) substr($requestUri, $baseLength); // '', '/글-주소', '?쿼리' 중 하나 $isBlogRequest = strncmp($requestUri, $basePath, $baseLength) === 0 && ($rest === '' || $rest[0] === '/' || $rest[0] === '?'); if (!$isBlogRequest) { // 블로그 경로가 아닌 주소로 이 파일을 직접 열면 응답하지 않습니다. inblog_relay_fail(404, 'Not Found'); } $queryStart = strpos($rest, '?'); $restPath = $queryStart === false ? $rest : substr($rest, 0, $queryStart); if (preg_match('#/(\.|%2e){1,2}(/|$)#i', $restPath) || strpos($restPath, '\\') !== false) { // 상위 경로로 올라가는 주소는 다른 블로그로 연결될 수 있어 막습니다. inblog_relay_fail(404, 'Not Found'); } $method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET'; if (!in_array($method, array('GET', 'HEAD', 'POST'))) { header('Allow: GET, HEAD, POST'); inblog_relay_fail(405, 'Method Not Allowed'); } // ---- 2. inblog 로 보낼 요청 헤더 구성 ---- $clientIp = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; $requestHeaders = array( 'X-Real-IP: ' . $clientIp, 'X-Forwarded-For: ' . $clientIp, 'X-Inblog-Public-Host: ' . $publicHost, 'X-Forwarded-Host: ' . $publicHost, 'X-Forwarded-Prefix: ' . $basePath, 'X-Forwarded-Proto: https', 'Expect:' ); foreach ($_SERVER as $key => $value) { if (strncmp($key, 'HTTP_', 5) !== 0 || !is_string($value)) { continue; } $name = substr($key, 5); if (in_array($name, $skippedRequestHeaders) || inblog_relay_starts_with_any($name, $skippedRequestHeaderPrefixes)) { continue; } $requestHeaders[] = str_replace('_', '-', $name) . ': ' . $value; } if ($method === 'POST') { // 값이 비어 있으면 cURL 이 기본 Content-Type 을 붙이지 않도록 헤더를 비워서 보냅니다. $contentType = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : ''; $requestHeaders[] = $contentType === '' ? 'Content-Type:' : 'Content-Type: ' . $contentType; } if (!empty($_SERVER['HTTP_COOKIE'])) { $forwardedCookies = array(); foreach (explode(';', $_SERVER['HTTP_COOKIE']) as $cookie) { $cookie = trim($cookie); if (inblog_relay_starts_with_any($cookie, $forwardedCookiePrefixes)) { $forwardedCookies[] = $cookie; } } if (count($forwardedCookies) > 0) { $requestHeaders[] = 'Cookie: ' . implode('; ', $forwardedCookies); } } // ---- 3. inblog 로 요청을 보내고 응답을 그대로 전달 ---- @ini_set('zlib.output_compression', 'Off'); // PHP 5.3 의 zlib 압축 버퍼처럼 닫을 수 없는 출력 버퍼를 만나면 멈춥니다. while (ob_get_level() > 0) { if (!@ob_end_clean()) { break; } } $curl = curl_init($upstreamOrigin . '/' . $inblogSubdomain . $rest); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); if ($method === 'HEAD') { curl_setopt($curl, CURLOPT_NOBODY, true); } if ($method === 'POST') { curl_setopt($curl, CURLOPT_POSTFIELDS, (string) file_get_contents('php://input')); } curl_setopt($curl, CURLOPT_HTTPHEADER, $requestHeaders); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false); curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($curl, CURLOPT_TIMEOUT, 20); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curl, CURLOPT_HEADERFUNCTION, 'inblog_relay_on_header'); curl_setopt($curl, CURLOPT_WRITEFUNCTION, 'inblog_relay_on_body'); $succeeded = curl_exec($curl); $curlErrorCode = curl_errno($curl); if ($relayState['sent']) { exit; } if ($succeeded === false || $relayState['status'] === 0) { header('X-Inblog-Relay-Error: curl-' . $curlErrorCode); inblog_relay_fail(502, 'Bad Gateway'); } // 본문이 없는 응답(HEAD, 204, 304, 리디렉션)은 여기에서 헤더만 보냅니다. inblog_relay_send_headers();
Output for master
cURL extension is required

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
13.74 ms | 1163 KiB | 6 Q