<?php

  header('Content-type: text/html; charset=utf-8'); 
  /* STEP 1: LOAD RECORDS - Copy this PHP code block near the TOP of your page */
  
  list($html, $statusCode) = getPage('https://soundcloud.com');

  echo "<br>Attempting new connection...<br>\r\n";

  if($statusCode){
    echo "Connected Successfully!<br>";
  }else{
    echo " Could not connect... checking port issue:<br>\r\n";
    $connectTimeout = 5;
    $handle = fsockopen('ssl://soundcloud.com', 443, $errno, $errstr, $connectTimeout);

    if (!$handle) {

      if ($errstr || $errno) {
        echo "Error opening socket: $errstr ($errno)<br>\n";
      }
    }else{
      echo "Connected successfully!<br>";
      // close socket
      fclose($handle);
    }
  }





//GET PAGE FUNCTION FROM CMSB


// download a web page
// list($html, $httpStatusCode, $headers, $request) = getPage($url);
function getPage($url, $connectTimeout = 5, $headers = array(), $POST = false, $responseBody = '') {
  global $SETTINGS;

  $html             = null;
  $httpStatusCode   = null;
  $httpHeaders      = null;
  if (!$connectTimeout) { $connectTimeout = 5; }
  if (!$headers)        { $headers = array(); }

  // use an http proxy server?
  $httpProxy = @$SETTINGS['advanced']['httpProxyServer'];
  $targetUrl = '';
  if ($httpProxy) {
    $targetUrl = $url;
    $url       = $httpProxy;
  }

  // is secure connection?
  $parsedUrl = parse_url($url);
  if     (@$parsedUrl['scheme'] == 'http')  { $isSSL = false; }
  elseif (@$parsedUrl['scheme'] == 'https') { $isSSL = true; }
  else { die(__FUNCTION__ . ": Url must start with http:// or https://!\n"); }
  if ($isSSL && !function_exists('openssl_open')) { die(__FUNCTION__ .": You must install the php openssl extension to be able to access https:// urls"); }

  // get port
  if (@$parsedUrl['port']) { $port = $parsedUrl['port']; }
  elseif ($isSSL)          { $port = 443; }
  else                     { $port = 80; }

  // open socket
  $scheme = $isSSL ? 'ssl://' : 'tcp://';

  //$ip  = gethostbyname($parsedUrl['host']); // get around PHP IPv6 bugs by connecting to IPv4 IP directly, Host: header is sent below regardless.
  //$handle = @fsockopen("$scheme$ip", $port, $errno, $errstr, $connectTimeout);
  // v2.64 - We can't do this anymore PHP 5.6+ now fails on invalid certificates: http://php.net/manual/en/migration56.openssl.php
  // ... and sometimes valid certificates: https://bugs.php.net/bug.php?id=68265
  // ... which causes fsockopen to fail if cert is invalid or hostname dosn't match: http://php.net/manual/fr/function.fsockopen.php#115405
  // So while connecting to the IP forces the server to use IPv4 and bypasses any potential IPv6 misconfigurations, it causes fsockopen to
  // fail on SSL sites because the IP won't match the certificate name

  // v2.64 - instead of using @ we disable 'display_errors' to cause errors to get logged because fsockopen can return multiple errors related to SSL certificate issues that aren't all captured in $php_errormsg
  // FUTURE: Consider switching to stream_socket_client from fsockopen so we can specify stream context options related to certificate checking when needed
  $old_display_errors = ini_set('display_errors', '0');
  $handle = fsockopen($scheme . $parsedUrl['host'], $port, $errno, $errstr, $connectTimeout);
  ini_set('display_errors', $old_display_errors);

  if (!$handle) {
    $isSocketsDisabled = ($errno == 0   || $errstr == "The operation completed successfully." ||
                          $errno == 1   || $errstr == "Operation not permitted" ||
                          $errno == 11  || $errstr == "Resource temporarily unavailable" ||
                          $errno == 13  || $errstr == "Permission denied" ||
                          $errno == 22  || $errstr == "Invalid argument" ||
                          $errno == 60  || $errstr == "Operation timed out" ||
                          $errno == 110 || $errstr == "Connection timed out" ||
                          $errno == 111 || $errstr == "Connection refused" ||
                          $errno == 10060 || $errstr == "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.");
    if ($isSocketsDisabled) { return(array(NULL,NULL,NULL,NULL)); }
    die(__FUNCTION__ . ": Error opening socket: $errstr ($errno)\n");
  }

  // set timeout
  $readWriteTimeout = 15;
  stream_set_timeout($handle, $readWriteTimeout);

  // if we're using an http proxy...
  if ($httpProxy) {
    $url       = $targetUrl;
    $parsedUrl = parse_url($url);
  }

  // determine request path (default to /, add the query string if this is a GET request, or if there was a query string and response body supplied)
  $path = @$parsedUrl['path'] ? $parsedUrl['path'] : '/';
  if (@$parsedUrl['query'] && (!$POST || $responseBody)) { $path .= "?{$parsedUrl['query']}"; }

  // set default headers
  $headers['Connection'] = 'close'; // Force HTTP/1.1 connection to close after request
  if (@$parsedUrl['user'] && @$parsedUrl['pass'] &&
      !@$headers['Authorization'])           { $headers['Authorization']  = "Basic " .base64_encode("{$parsedUrl['user']}:{$parsedUrl['pass']}"); };
  if (!@$headers['User-Agent'])              { $headers['User-Agent']     = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"; } // ref: http://blogs.msdn.com/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx
  if (!@$headers['Host'])                    { $headers['Host']           = $parsedUrl['host']; }
  if ($POST && !strlen($responseBody))       { $responseBody = @$parsedUrl['query']; }
  if ($POST && !@$headers['Content-Type'])   { $headers['Content-Type']   = 'application/x-www-form-urlencoded'; }
  if ($POST && !@$headers['Content-Length']) { $headers['Content-Length'] = strlen( $responseBody ); }

  // send request
  $method   = $POST ? 'POST' : 'GET';
  $request  = "$method $path HTTP/1.0\r\n";
  foreach ($headers as $name => $value) { $request .= "$name: $value\r\n"; }
  $request .= "\r\n";
  if ($POST) { $request .= $responseBody . "\r\n\r\n"; }
  fwrite($handle, $request);

  // get response
  $header         = null;
  $html           = null;
  $httpStatusCode = null;
  $response       = '';
  socket_set_blocking($handle, false); // use this or fgets() will block forever if no data available - even ignoring set_time_limit(###) limits - this happens when the other side doesn't close the connection or we send HTTP/1.1 by accident
  while (!feof($handle)) {
    $buffer = @fgets($handle, 128); // hide errors from: http://bugs.php.net/23220 and also see "Warning" box on http://php.net/file-get-contents
    if (!isset($buffer)) { break; } // prevent infinite loops on fgets errors
    $response .= $buffer;
  }

  if ($response) {
    list($header, $html) = preg_split("/(\r?\n){2}/", $response, 2);
    if (preg_match("/^HTTP\S+ (\d+) /", $header, $matches)) { $httpStatusCode = $matches[1]; }
  }

  // close socket
  fclose($handle);

  //
  return(array($html, $httpStatusCode, $header, $request));
}
