473,395 Members | 1,466 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Why httpS Fails To Load ?

Php Gurus!

This is a php web proxy called Mini Proxy not written by me.
Why do https pages show blank white when I visit any https pages with the proxy ?
I reckon the https pages are failing to load. Why do you think that is ?

You can see the actual code here if you want to see it with line numbers:
https://github.com/joshdick/miniProxy/blob/master/miniProxy.php

Which line of the code should I change to what ?

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. /*
  3. miniProxy - A simple PHP web proxy. <https://github.com/joshdick/miniProxy>
  4. Written and maintained by Joshua Dick <http://joshdick.net>.
  5. miniProxy is licensed under the GNU GPL v3 <http://www.gnu.org/licenses/gpl.html>.
  6. */
  7. /****************************** START CONFIGURATION ******************************/
  8. //To allow proxying any URL, set $whitelistPatterns to an empty array (the default).
  9. //To only allow proxying of specific URLs (whitelist), add corresponding regular expressions
  10. //to the $whitelistPatterns array. Enter the most specific patterns possible, to prevent possible abuse.
  11. //You can optionally use the "getHostnamePattern()" helper function to build a regular expression that
  12. //matches all URLs for a given hostname.
  13. $whitelistPatterns = array(
  14.   //Usage example: To support any URL at example.net, including sub-domains, uncomment the
  15.   //line below (which is equivalent to [ @^https?://([a-z0-9-]+\.)*example\.net@i ]):
  16.   //getHostnamePattern("example.net")
  17. );
  18. //To enable CORS (cross-origin resource sharing) for proxied sites, set $forceCORS to true.
  19. $forceCORS = false;
  20. //Set to false to report the client machine's IP address to proxied sites via the HTTP `x-forwarded-for` header.
  21. //Setting to false may improve compatibility with some sites, but also exposes more information about end users to proxied sites.
  22. $anonymize = true;
  23. //Start/default URL that that will be proxied when miniProxy is first loaded in a browser/accessed directly with no URL to proxy.
  24. //If empty, miniProxy will show its own landing page.
  25. $startURL = "";
  26. //When no $startURL is configured above, miniProxy will show its own landing page with a URL form field
  27. //and the configured example URL. The example URL appears in the instructional text on the miniProxy landing page,
  28. //and is proxied when pressing the 'Proxy It!' button on the landing page if its URL form is left blank.
  29. $landingExampleURL = "https://example.net";
  30. /****************************** END CONFIGURATION ******************************/
  31. ob_start("ob_gzhandler");
  32. if (version_compare(PHP_VERSION, "5.4.7", "<")) {
  33.   die("miniProxy requires PHP version 5.4.7 or later.");
  34. }
  35. $requiredExtensions = ['curl', 'mbstring'];
  36. foreach($requiredExtensions as $requiredExtension) {
  37.   if (!extension_loaded($requiredExtension)) {
  38.     die("miniProxy requires PHP's \"" . $requiredExtension . "\" extension. Please install/enable it on your server and try again.");
  39.   }
  40. }
  41. //Helper function for use inside $whitelistPatterns.
  42. //Returns a regex that matches all HTTP[S] URLs for a given hostname.
  43. function getHostnamePattern($hostname) {
  44.   $escapedHostname = str_replace(".", "\.", $hostname);
  45.   return "@^https?://([a-z0-9-]+\.)*" . $escapedHostname . "@i";
  46. }
  47. //Helper function used to removes/unset keys from an associative array using case insensitive matching
  48. function removeKeys(&$assoc, $keys2remove) {
  49.   $keys = array_keys($assoc);
  50.   $map = array();
  51.   $removedKeys = array();
  52.   foreach ($keys as $key) {
  53.     $map[strtolower($key)] = $key;
  54.   }
  55.   foreach ($keys2remove as $key) {
  56.     $key = strtolower($key);
  57.     if (isset($map[$key])) {
  58.       unset($assoc[$map[$key]]);
  59.       $removedKeys[] = $map[$key];
  60.     }
  61.   }
  62.   return $removedKeys;
  63. }
  64. if (!function_exists("getallheaders")) {
  65.   //Adapted from http://www.php.net/manual/en/function.getallheaders.php#99814
  66.   function getallheaders() {
  67.     $result = array();
  68.     foreach($_SERVER as $key => $value) {
  69.       if (substr($key, 0, 5) == "HTTP_") {
  70.         $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
  71.         $result[$key] = $value;
  72.       }
  73.     }
  74.     return $result;
  75.   }
  76. }
  77. $usingDefaultPort =  (!isset($_SERVER["HTTPS"]) && $_SERVER["SERVER_PORT"] === 80) || (isset($_SERVER["HTTPS"]) && $_SERVER["SERVER_PORT"] === 443);
  78. $prefixPort = $usingDefaultPort ? "" : ":" . $_SERVER["SERVER_PORT"];
  79. //Use HTTP_HOST to support client-configured DNS (instead of SERVER_NAME), but remove the port if one is present
  80. $prefixHost = $_SERVER["HTTP_HOST"];
  81. $prefixHost = strpos($prefixHost, ":") ? implode(":", explode(":", $_SERVER["HTTP_HOST"], -1)) : $prefixHost;
  82. define("PROXY_PREFIX", "http" . (isset($_SERVER["HTTPS"]) ? "s" : "") . "://" . $prefixHost . $prefixPort . $_SERVER["SCRIPT_NAME"] . "?");
  83. //Makes an HTTP request via cURL, using request data that was passed directly to this script.
  84. function makeRequest($url) {
  85.   global $anonymize;
  86.   //Tell cURL to make the request using the brower's user-agent if there is one, or a fallback user-agent otherwise.
  87.   $user_agent = $_SERVER["HTTP_USER_AGENT"];
  88.   if (empty($user_agent)) {
  89.     $user_agent = "Mozilla/5.0 (compatible; miniProxy)";
  90.   }
  91.   $ch = curl_init();
  92.   curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
  93.   //Get ready to proxy the browser's request headers...
  94.   $browserRequestHeaders = getallheaders();
  95.   //...but let cURL set some headers on its own.
  96.   $removedHeaders = removeKeys($browserRequestHeaders, array(
  97.     "Accept-Encoding", //Throw away the browser's Accept-Encoding header if any and let cURL make the request using gzip if possible.
  98.     "Content-Length",
  99.     "Host",
  100.     "Origin"
  101.   ));
  102.   array_change_key_case($removedHeaders, CASE_LOWER);
  103.   curl_setopt($ch, CURLOPT_ENCODING, "");
  104.   //Transform the associative array from getallheaders() into an
  105.   //indexed array of header strings to be passed to cURL.
  106.   $curlRequestHeaders = array();
  107.   foreach ($browserRequestHeaders as $name => $value) {
  108.     $curlRequestHeaders[] = $name . ": " . $value;
  109.   }
  110.   if (!$anonymize) {
  111.     $curlRequestHeaders[] = "X-Forwarded-For: " . $_SERVER["REMOTE_ADDR"];
  112.   }
  113.   //Any `origin` header sent by the browser will refer to the proxy itself.
  114.   //If an `origin` header is present in the request, rewrite it to point to the correct origin.
  115.   if (array_key_exists('origin', $removedHeaders)) {
  116.     $urlParts = parse_url($url);
  117.     $port = $urlParts['port'];
  118.     $curlRequestHeaders[] = "Origin: " . $urlParts['scheme'] . "://" . $urlParts['host'] . (empty($port) ? "" : ":" . $port);
  119.   };
  120.   curl_setopt($ch, CURLOPT_HTTPHEADER, $curlRequestHeaders);
  121.   //Proxy any received GET/POST/PUT data.
  122.   switch ($_SERVER["REQUEST_METHOD"]) {
  123.     case "POST":
  124.       curl_setopt($ch, CURLOPT_POST, true);
  125.       //For some reason, $HTTP_RAW_POST_DATA isn't working as documented at
  126.       //http://php.net/manual/en/reserved.variables.httprawpostdata.php
  127.       //but the php://input method works. This is likely to be flaky
  128.       //across different server environments.
  129.       //More info here: http://stackoverflow.com/questions/8899239/http-raw-post-data-not-being-populated-after-upgrade-to-php-5-3
  130.       //If the miniProxyFormAction field appears in the POST data, remove it so the destination server doesn't receive it.
  131.       $postData = Array();
  132.       parse_str(file_get_contents("php://input"), $postData);
  133.       if (isset($postData["miniProxyFormAction"])) {
  134.         unset($postData["miniProxyFormAction"]);
  135.       }
  136.       curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
  137.     break;
  138.     case "PUT":
  139.       curl_setopt($ch, CURLOPT_PUT, true);
  140.       curl_setopt($ch, CURLOPT_INFILE, fopen("php://input", "r"));
  141.     break;
  142.   }
  143.   //Other cURL options.
  144.   curl_setopt($ch, CURLOPT_HEADER, true);
  145.   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  146.   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  147.   //Set the request URL.
  148.   curl_setopt($ch, CURLOPT_URL, $url);
  149.   //Make the request.
  150.   $response = curl_exec($ch);
  151.   $responseInfo = curl_getinfo($ch);
  152.   $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  153.   curl_close($ch);
  154.   //Setting CURLOPT_HEADER to true above forces the response headers and body
  155.   //to be output together--separate them.
  156.   $responseHeaders = substr($response, 0, $headerSize);
  157.   $responseBody = substr($response, $headerSize);
  158.   return array("headers" => $responseHeaders, "body" => $responseBody, "responseInfo" => $responseInfo);
  159. }
  160. //Converts relative URLs to absolute ones, given a base URL.
  161. //Modified version of code found at http://nashruddin.com/PHP_Script_for_Converting_Relative_to_Absolute_URL
  162. function rel2abs($rel, $base) {
  163.   if (empty($rel)) $rel = ".";
  164.   if (parse_url($rel, PHP_URL_SCHEME) != "" || strpos($rel, "//") === 0) return $rel; //Return if already an absolute URL
  165.   if ($rel[0] == "#" || $rel[0] == "?") return $base.$rel; //Queries and anchors
  166.   extract(parse_url($base)); //Parse base URL and convert to local variables: $scheme, $host, $path
  167.   $path = isset($path) ? preg_replace("#/[^/]*$#", "", $path) : "/"; //Remove non-directory element from path
  168.   if ($rel[0] == "/") $path = ""; //Destroy path if relative url points to root
  169.   $port = isset($port) && $port != 80 ? ":" . $port : "";
  170.   $auth = "";
  171.   if (isset($user)) {
  172.     $auth = $user;
  173.     if (isset($pass)) {
  174.       $auth .= ":" . $pass;
  175.     }
  176.     $auth .= "@";
  177.   }
  178.   $abs = "$auth$host$port$path/$rel"; //Dirty absolute URL
  179.   for ($n = 1; $n > 0; $abs = preg_replace(array("#(/\.?/)#", "#/(?!\.\.)[^/]+/\.\./#"), "/", $abs, -1, $n)) {} //Replace '//' or '/./' or '/foo/../' with '/'
  180.   return $scheme . "://" . $abs; //Absolute URL is ready.
  181. }
  182. //Proxify contents of url() references in blocks of CSS text.
  183. function proxifyCSS($css, $baseURL) {
  184.   // Add a "url()" wrapper to any CSS @import rules that only specify a URL without the wrapper,
  185.   // so that they're proxified when searching for "url()" wrappers below.
  186.   $sourceLines = explode("\n", $css);
  187.   $normalizedLines = [];
  188.   foreach ($sourceLines as $line) {
  189.     if (preg_match("/@import\s+url/i", $line)) {
  190.       $normalizedLines[] = $line;
  191.     } else {
  192.       $normalizedLines[] = preg_replace_callback(
  193.         "/(@import\s+)([^;\s]+)([\s;])/i",
  194.         function($matches) use ($baseURL) {
  195.           return $matches[1] . "url(" . $matches[2] . ")" . $matches[3];
  196.         },
  197.         $line);
  198.     }
  199.   }
  200.   $normalizedCSS = implode("\n", $normalizedLines);
  201.   return preg_replace_callback(
  202.     "/url\((.*?)\)/i",
  203.     function($matches) use ($baseURL) {
  204.         $url = $matches[1];
  205.         //Remove any surrounding single or double quotes from the URL so it can be passed to rel2abs - the quotes are optional in CSS
  206.         //Assume that if there is a leading quote then there should be a trailing quote, so just use trim() to remove them
  207.         if (strpos($url, "'") === 0) {
  208.           $url = trim($url, "'");
  209.         }
  210.         if (strpos($url, "\"") === 0) {
  211.           $url = trim($url, "\"");
  212.         }
  213.         if (stripos($url, "data:") === 0) return "url(" . $url . ")"; //The URL isn't an HTTP URL but is actual binary data. Don't proxify it.
  214.         return "url(" . PROXY_PREFIX . rel2abs($url, $baseURL) . ")";
  215.     },
  216.     $normalizedCSS);
  217. }
  218. //Proxify "srcset" attributes (normally associated with <img> tags.)
  219. function proxifySrcset($srcset, $baseURL) {
  220.   $sources = array_map("trim", explode(",", $srcset)); //Split all contents by comma and trim each value
  221.   $proxifiedSources = array_map(function($source) use ($baseURL) {
  222.     $components = array_map("trim", str_split($source, strrpos($source, " "))); //Split by last space and trim
  223.     $components[0] = PROXY_PREFIX . rel2abs(ltrim($components[0], "/"), $baseURL); //First component of the split source string should be an image URL; proxify it
  224.     return implode($components, " "); //Recombine the components into a single source
  225.   }, $sources);
  226.   $proxifiedSrcset = implode(", ", $proxifiedSources); //Recombine the sources into a single "srcset"
  227.   return $proxifiedSrcset;
  228. }
  229. //Extract and sanitize the requested URL, handling cases where forms have been rewritten to point to the proxy.
  230. if (isset($_POST["miniProxyFormAction"])) {
  231.   $url = $_POST["miniProxyFormAction"];
  232.   unset($_POST["miniProxyFormAction"]);
  233. } else {
  234.   $queryParams = Array();
  235.   parse_str($_SERVER["QUERY_STRING"], $queryParams);
  236.   //If the miniProxyFormAction field appears in the query string, make $url start with its value, and rebuild the the query string without it.
  237.   if (isset($queryParams["miniProxyFormAction"])) {
  238.     $formAction = $queryParams["miniProxyFormAction"];
  239.     unset($queryParams["miniProxyFormAction"]);
  240.     $url = $formAction . "?" . http_build_query($queryParams);
  241.   } else {
  242.     $url = substr($_SERVER["REQUEST_URI"], strlen($_SERVER["SCRIPT_NAME"]) + 1);
  243.   }
  244. }
  245. if (empty($url)) {
  246.     if (empty($startURL)) {
  247.       die("<html><head><title>miniProxy</title></head><body><h1>Welcome to miniProxy!</h1>miniProxy can be directly invoked like this: <a href=\"" . PROXY_PREFIX . $landingExampleURL . "\">" . PROXY_PREFIX . $landingExampleURL . "</a><br /><br />Or, you can simply enter a URL below:<br /><br /><form onsubmit=\"if (document.getElementById('site').value) { window.location.href='" . PROXY_PREFIX . "' + document.getElementById('site').value; return false; } else { window.location.href='" . PROXY_PREFIX . $landingExampleURL . "'; return false; }\" autocomplete=\"off\"><input id=\"site\" type=\"text\" size=\"50\" /><input type=\"submit\" value=\"Proxy It!\" /></form></body></html>");
  248.     } else {
  249.       $url = $startURL;
  250.     }
  251. } else if (strpos($url, ":/") !== strpos($url, "://")) {
  252.     //Work around the fact that some web servers (e.g. IIS 8.5) change double slashes appearing in the URL to a single slash.
  253.     //See https://github.com/joshdick/miniProxy/pull/14
  254.     $pos = strpos($url, ":/");
  255.     $url = substr_replace($url, "://", $pos, strlen(":/"));
  256. }
  257. $scheme = parse_url($url, PHP_URL_SCHEME);
  258. if (empty($scheme)) {
  259.   //Assume that any supplied URLs starting with // are HTTP URLs.
  260.   if (strpos($url, "//") === 0) {
  261.     $url = "http:" . $url;
  262.   }
  263. } else if (!preg_match("/^https?$/i", $scheme)) {
  264.     die('Error: Detected a "' . $scheme . '" URL. miniProxy exclusively supports http[s] URLs.');
  265. }
  266. //Validate the requested URL against the whitelist.
  267. $urlIsValid = count($whitelistPatterns) === 0;
  268. foreach ($whitelistPatterns as $pattern) {
  269.   if (preg_match($pattern, $url)) {
  270.     $urlIsValid = true;
  271.     break;
  272.   }
  273. }
  274. if (!$urlIsValid) {
  275.   die("Error: The requested URL was disallowed by the server administrator.");
  276. }
  277. $response = makeRequest($url);
  278. $rawResponseHeaders = $response["headers"];
  279. $responseBody = $response["body"];
  280. $responseInfo = $response["responseInfo"];
  281. //If CURLOPT_FOLLOWLOCATION landed the proxy at a diferent URL than
  282. //what was requested, explicitly redirect the proxy there.
  283. $responseURL = $responseInfo["url"];
  284. if ($responseURL !== $url) {
  285.   header("Location: " . PROXY_PREFIX . $responseURL, true);
  286.   exit(0);
  287. }
  288. //A regex that indicates which server response headers should be stripped out of the proxified response.
  289. $header_blacklist_pattern = "/^Content-Length|^Transfer-Encoding|^Content-Encoding.*gzip/i";
  290. //cURL can make multiple requests internally (for example, if CURLOPT_FOLLOWLOCATION is enabled), and reports
  291. //headers for every request it makes. Only proxy the last set of received response headers,
  292. //corresponding to the final request made by cURL for any given call to makeRequest().
  293. $responseHeaderBlocks = array_filter(explode("\r\n\r\n", $rawResponseHeaders));
  294. $lastHeaderBlock = end($responseHeaderBlocks);
  295. $headerLines = explode("\r\n", $lastHeaderBlock);
  296. foreach ($headerLines as $header) {
  297.   $header = trim($header);
  298.   if (!preg_match($header_blacklist_pattern, $header)) {
  299.     header($header, false);
  300.   }
  301. }
  302. //Prevent robots from indexing proxified pages
  303. header("X-Robots-Tag: noindex, nofollow", true);
  304. if ($forceCORS) {
  305.   //This logic is based on code found at: http://stackoverflow.com/a/9866124/278810
  306.   //CORS headers sent below may conflict with CORS headers from the original response,
  307.   //so these headers are sent after the original response headers to ensure their values
  308.   //are the ones that actually end up getting sent to the browser.
  309.   //Explicit [ $replace = true ] is used for these headers even though this is PHP's default behavior.
  310.   //Allow access from any origin.
  311.   header("Access-Control-Allow-Origin: *", true);
  312.   header("Access-Control-Allow-Credentials: true", true);
  313.   //Handle CORS headers received during OPTIONS requests.
  314.   if ($_SERVER["REQUEST_METHOD"] == "OPTIONS") {
  315.     if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"])) {
  316.       header("Access-Control-Allow-Methods: GET, POST, OPTIONS", true);
  317.     }
  318.     if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"])) {
  319.       header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}", true);
  320.     }
  321.     //No further action is needed for OPTIONS requests.
  322.     exit(0);
  323.   }
  324. }
  325. $contentType = "";
  326. if (isset($responseInfo["content_type"])) $contentType = $responseInfo["content_type"];
  327. //This is presumably a web page, so attempt to proxify the DOM.
  328. if (stripos($contentType, "text/html") !== false) {
  329.   //Attempt to normalize character encoding.
  330.   $detectedEncoding = mb_detect_encoding($responseBody, "UTF-8, ISO-8859-1");
  331.   if ($detectedEncoding) {
  332.     $responseBody = mb_convert_encoding($responseBody, "HTML-ENTITIES", $detectedEncoding);
  333.   }
  334.   //Parse the DOM.
  335.   $doc = new DomDocument();
  336.   @$doc->loadHTML($responseBody);
  337.   $xpath = new DOMXPath($doc);
  338.   //Rewrite forms so that their actions point back to the proxy.
  339.   foreach($xpath->query("//form") as $form) {
  340.     $method = $form->getAttribute("method");
  341.     $action = $form->getAttribute("action");
  342.     //If the form doesn't have an action, the action is the page itself.
  343.     //Otherwise, change an existing action to an absolute version.
  344.     $action = empty($action) ? $url : rel2abs($action, $url);
  345.     //Rewrite the form action to point back at the proxy.
  346.     $form->setAttribute("action", rtrim(PROXY_PREFIX, "?"));
  347.     //Add a hidden form field that the proxy can later use to retreive the original form action.
  348.     $actionInput = $doc->createDocumentFragment();
  349.     $actionInput->appendXML('<input type="hidden" name="miniProxyFormAction" value="' . htmlspecialchars($action) . '" />');
  350.     $form->appendChild($actionInput);
  351.   }
  352.   //Proxify <meta> tags with an 'http-equiv="refresh"' attribute.
  353.   foreach ($xpath->query("//meta[@http-equiv]") as $element) {
  354.     if (strcasecmp($element->getAttribute("http-equiv"), "refresh") === 0) {
  355.       $content = $element->getAttribute("content");
  356.       if (!empty($content)) {
  357.         $splitContent = preg_split("/=/", $content);
  358.         if (isset($splitContent[1])) {
  359.           $element->setAttribute("content", $splitContent[0] . "=" . PROXY_PREFIX . rel2abs($splitContent[1], $url));
  360.         }
  361.       }
  362.     }
  363.   }
  364.   //Profixy <style> tags.
  365.   foreach($xpath->query("//style") as $style) {
  366.     $style->nodeValue = proxifyCSS($style->nodeValue, $url);
  367.   }
  368.   //Proxify tags with a "style" attribute.
  369.   foreach ($xpath->query("//*[@style]") as $element) {
  370.     $element->setAttribute("style", proxifyCSS($element->getAttribute("style"), $url));
  371.   }
  372.   //Proxify "srcset" attributes in <img> tags.
  373.   foreach ($xpath->query("//img[@srcset]") as $element) {
  374.     $element->setAttribute("srcset", proxifySrcset($element->getAttribute("srcset"), $url));
  375.   }
  376.   //Proxify any of these attributes appearing in any tag.
  377.   $proxifyAttributes = array("href", "src");
  378.   foreach($proxifyAttributes as $attrName) {
  379.     foreach($xpath->query("//*[@" . $attrName . "]") as $element) { //For every element with the given attribute...
  380.       $attrContent = $element->getAttribute($attrName);
  381.       if ($attrName == "href" && preg_match("/^(about|javascript|magnet|mailto):/i", $attrContent)) continue;
  382.       $attrContent = rel2abs($attrContent, $url);
  383.       $attrContent = PROXY_PREFIX . $attrContent;
  384.       $element->setAttribute($attrName, $attrContent);
  385.     }
  386.   }
  387.   //Attempt to force AJAX requests to be made through the proxy by
  388.   //wrapping window.XMLHttpRequest.prototype.open in order to make
  389.   //all request URLs absolute and point back to the proxy.
  390.   //The rel2abs() JavaScript function serves the same purpose as the server-side one in this file,
  391.   //but is used in the browser to ensure all AJAX request URLs are absolute and not relative.
  392.   //Uses code from these sources:
  393.   //http://stackoverflow.com/questions/7775767/javascript-overriding-xmlhttprequest-open
  394.   //https://gist.github.com/1088850
  395.   //TODO: This is obviously only useful for browsers that use XMLHttpRequest but
  396.   //it's better than nothing.
  397.   $head = $xpath->query("//head")->item(0);
  398.   $body = $xpath->query("//body")->item(0);
  399.   $prependElem = $head != NULL ? $head : $body;
  400.   //Only bother trying to apply this hack if the DOM has a <head> or <body> element;
  401.   //insert some JavaScript at the top of whichever is available first.
  402.   //Protects against cases where the server sends a Content-Type of "text/html" when
  403.   //what's coming back is most likely not actually HTML.
  404.   //TODO: Do this check before attempting to do any sort of DOM parsing?
  405.   if ($prependElem != NULL) {
  406.     $scriptElem = $doc->createElement("script",
  407.       '(function() {
  408.         if (window.XMLHttpRequest) {
  409.           function parseURI(url) {
  410.             var m = String(url).replace(/^\s+|\s+$/g, "").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
  411.             // authority = "//" + user + ":" + pass "@" + hostname + ":" port
  412.             return (m ? {
  413.               href : m[0] || "",
  414.               protocol : m[1] || "",
  415.               authority: m[2] || "",
  416.               host : m[3] || "",
  417.               hostname : m[4] || "",
  418.               port : m[5] || "",
  419.               pathname : m[6] || "",
  420.               search : m[7] || "",
  421.               hash : m[8] || ""
  422.             } : null);
  423.           }
  424.           function rel2abs(base, href) { // RFC 3986
  425.             function removeDotSegments(input) {
  426.               var output = [];
  427.               input.replace(/^(\.\.?(\/|$))+/, "")
  428.                 .replace(/\/(\.(\/|$))+/g, "/")
  429.                 .replace(/\/\.\.$/, "/../")
  430.                 .replace(/\/?[^\/]*/g, function (p) {
  431.                   if (p === "/..") {
  432.                     output.pop();
  433.                   } else {
  434.                     output.push(p);
  435.                   }
  436.                 });
  437.               return output.join("").replace(/^\//, input.charAt(0) === "/" ? "/" : "");
  438.             }
  439.             href = parseURI(href || "");
  440.             base = parseURI(base || "");
  441.             return !href || !base ? null : (href.protocol || base.protocol) +
  442.             (href.protocol || href.authority ? href.authority : base.authority) +
  443.             removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === "/" ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? "/" : "") + base.pathname.slice(0, base.pathname.lastIndexOf("/") + 1) + href.pathname) : base.pathname)) +
  444.             (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
  445.             href.hash;
  446.           }
  447.           var proxied = window.XMLHttpRequest.prototype.open;
  448.           window.XMLHttpRequest.prototype.open = function() {
  449.               if (arguments[1] !== null && arguments[1] !== undefined) {
  450.                 var url = arguments[1];
  451.                 url = rel2abs("' . $url . '", url);
  452.                 url = "' . PROXY_PREFIX . '" + url;
  453.                 arguments[1] = url;
  454.               }
  455.               return proxied.apply(this, [].slice.call(arguments));
  456.           };
  457.         }
  458.       })();'
  459.     );
  460.     $scriptElem->setAttribute("type", "text/javascript");
  461.     $prependElem->insertBefore($scriptElem, $prependElem->firstChild);
  462.   }
  463.   echo "<!-- Proxified page constructed by miniProxy -->\n" . $doc->saveHTML();
  464. } else if (stripos($contentType, "text/css") !== false) { //This is CSS, so proxify url() references.
  465.   echo proxifyCSS($responseBody, $url);
  466. } else { //This isn't a web page or CSS, so serve unmodified through the proxy with the correct headers (images, JavaScript, etc.)
  467.   header("Content-Length: " . strlen($responseBody), true);
  468.   echo $responseBody;
  469. }
  470.  
Oct 12 '17 #1
0 2150

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Paul Winkler | last post by:
This is driving me up the wall... any help would be MUCH appreciated. I have a module that I've whittled down into a 65-line script in an attempt to isolate the cause of the problem. (Real...
22
by: Bloke | last post by:
Hi all. Some time ago (years) I had a script on Python 2.2 that would retieve a HTTPS web site. I used python22-win32-ssl.zip to handle the SSL aspect and it worked wonderfully. I am...
0
by: Earle Oxner | last post by:
We are developing an application on PocketPC2002 platform and we are trying to make webservice calls using HTTPS. HTTP works fine but HTTPS does not work. The same code which doesn't work on...
8
by: vandenberc | last post by:
I am trying to setup an html page. I have a button and when you click on it I want it to go to either http:///.../demo.htm or https://..../demo.htm based on whether or not you went through the...
2
by: Greg Collins [Microsoft MVP] | last post by:
In reviewing my web site statistics, I see that I get 404 errors (often enough to make me ask about it) when users try to click on a link to a secure external site (i.e. an https:// link). I've...
1
by: Jens Mander | last post by:
Hi and sorry for the heavy crossposting (fu2 mpdf)! As you might have gotten out of the subject line, my application tries to consume a webservice that's being connected to via https. This works...
9
by: LVP | last post by:
Hello, What are the ways to switch from http to https. Is there a way internal to IIS 6.0 or x.xx? Some configuration? Is there a way via DNS? I have seen Scripts in VB and JavaScript ...
5
by: Chuck Anderson | last post by:
I run Apache 2.0.55, and Php (both 4.4.1 and 5.2.5) on my home PC (Windows XP). One of the scripts that I run daily needs to access a secure URL (https://..............). When I am running Php4,...
2
by: =?Utf-8?B?TGVuc3Rlcg==?= | last post by:
A C# (.NET 2) application which uses the System.Net.HttpWebRequest object to request a resource over HTTPS is failing following the installation of a new proxy server on our internal network with...
0
by: wsung | last post by:
I got a p12 file from one payment service, only by using this file i can load wsdl from the https address they provide to me. Below are steps how i import the p12 file to my browser to load the wdsl...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.