473,378 Members | 1,429 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,378 software developers and data experts.

Accounts, Sessions, Proxies And Intermittent Errors!

Php Gurus,

I added a url logger to Mini Proxy so that whatever my free users browse gets logged into my db under their account usernames. The code of Mini Proxy is too long to fit into this post and so you may check it out here: https://github.com/joshdick/miniProx.../miniProxy.php

Using the Mini Proxy, whatever I browse now gets logged into my DB. Tbl: browsing_history. Columns: ids, time & dates, usernames, urls.

Now, when I view a url it gets logged. Good.

Expand|Select|Wrap|Line Numbers
  1. // Dump $url into db
  2.  
  3. $stmt = mysqli_prepare($conn, "INSERT INTO 
  4. browsing_histories(ids,usernames,urls) VALUES (?, ?, ?)");
  5. mysqli_stmt_bind_param($stmt, 'iss', $id, $user, $url);
  6. mysqli_stmt_execute($stmt);
  7. if($stmt)
  8. {
  9.     echo "Logged $url to db a success!";
  10. }
  11. else    
  12. {
  13.     echo "Logging $url to db failed!";
  14. }
  15.  

Q1. Why is the web proxy php script only fetching "http" but not "https" pages ? Which line to change and to what to fix this ? I get error: Error: The requested URL was disallowed by the server administrator.
If you check the link for the code then you will see that error is mentioned on line 308 on the script code.

Q2. I want to fake the REFERRER so the websites (viewed via the proxy) see the referrer as: http://www.example.com/referrer.html and not the actual referrer. On which line do I add what lines of code to achieve this ?

Q3.
The Mini Proxy is a one page script. But in order to log my users browsings, I built account feature (registration.php, account_activation.php, login.php & logout.php, home.php, browser.php).
The proxy page, I renamed to browser.php.
Now, when you log-in to your account via login.php, you are redirected to home.php and the login.php sets the session:

Expand|Select|Wrap|Line Numbers
  1.         if (!password_verify($password, $db_password))
  2.         {
  3.             echo "Incorrect User Credentials!';<br>";
  4.             exit();
  5.         }
  6.         else
  7.         {
  8.             $_SESSION["user"] = $db_username;            
  9.             header("location:home.php?user=$db_username");
  10.  

home.php & browser.php

Expand|Select|Wrap|Line Numbers
  1. // check if user is already logged in
  2. if (is_logged() === false) 
  3. {
  4.     //Redirect user to homepage page after 2 seconds.
  5.     header("refresh:2;url=login.php");
  6.     exit;
  7. }
  8. else 
  9. {
  10.     $user = $_SESSION["user"];
  11.  
Now, when you log-in to your account and get redirected to home.php, the session identifies your Username. So far, so good.
But, when next you navigate to browser.php then for some reason the session fails to identify your username. It's as if the session gets fropped some-ho. But, I don't understand how & why! There is no clear session in browser.php.

I am including the login.php, home.php and browser.php. I need to know why the browser.php losses the session when you go from:
-> home.php -> browser.php.

Thanks!


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

Q4.
Why does home.php show error:

Expand|Select|Wrap|Line Numbers
  1. Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FROM users WHERE usernames = ?' at line 1 in C:\xampp\htdocs\id\home.php:30 Stack trace: #0 C:\xampp\htdocs\id\home.php(30): mysqli_prepare(Object(mysqli), 'SELECT ids, use...') #1 {main} thrown in C:\xampp\htdocs\id\home.php on line 30
  2.  
The code at line 30 looks like this:

Expand|Select|Wrap|Line Numbers
  1. $stmt = mysqli_prepare($conn, $query);
  2.  
Full context of the concerned code:

Expand|Select|Wrap|Line Numbers
  1. $query = "SELECT ids, usernames, passwords, first_names, surnames, emails, FROM users WHERE usernames = ?";            
  2.             $stmt = mysqli_prepare($conn, $query); //This line is creating the error! But why ?
  3.             mysqli_stmt_bind_param($stmt, 's', $user);
  4.             mysqli_stmt_execute($stmt);
  5.             $result = mysqli_stmt_bind_result($stmt, $id, $username, $password, $first_name, $surname, $email);
  6.             ?>
  7.  
Oct 10 '17 #1
0 2047

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

Similar topics

0
by: Philip | last post by:
Hi, I have a problem with a win 2003 server Standard edition. Sometimes when I'm working in my web application the session hangs (but not the ASP-application). In the application log I find the...
10
by: Dan | last post by:
We have a fairly large set of ASP.NET applications running on Windows 2003 SP1 server. The entire suite of software was originally written in ASP and ran on a Win 2k server. For about the last...
0
by: RonNanko | last post by:
Hi, let me first explain what my problem is all about: I have a third-party application, which does not allow multiple instances of itself. As I need to run the application in multiple instances...
0
by: deevoy | last post by:
Hi- I'm developing a asp.net web application and everything has proven fine on the dev and acceptance environment. We've moved the code up to our windows server 2003 prod environment and get the...
0
by: Ravi Chand via .NET 247 | last post by:
(Type your message here) Hi All, One of our ASP.Net application was stress tested recently andunfortunately it is throwing up intermittent errors. Theapplication has been setup in a load...
6
by: Daniel Walzenbach | last post by:
Hi, I have a web application which sometimes throws an “out of memory” exception. To get an idea what happens I traced some values using performance monitor and got the following values (for...
4
by: Molina | last post by:
Hi !!! I have a VB.Net application that consumes an WebService. The problem is that the HTTP address works fine, but it will change to an HTTPS address, and it isn't working. The weird thing...
13
by: Simon Dean | last post by:
And while Im at it... should I be using PHP's built in sessions, or use my own functions that I've chobbled together from various sources and takes advantage of also validating IP Addresses??? I...
1
by: james | last post by:
Hi Guys, Is it expensive to create proxies in WCF? I always create new proxy instances (when not using sessions) so I don't have to worry about a proxy falling into a Faulted state. I started...
1
by: dotNetDone | last post by:
I have a thorny issue that we've been unable to resolve now for months. First our web ap uses framework 2.5, and IIS 6.0. What happens is that ocassionaly (once every 5 months or so) a user...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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...

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.