Foolproof Way To Check For SSL With PHP - php

We have a need to check for certain if the server has SSL installed. Every method that we tried does not seem to be fool proof.
Our ultimate goal is if someone types in http://somedomain.com, we can test is the server has SSL and then display https://somedomain.com
We need to be able to do this with PHP and not htaccess since this is a module we are creating. Using file_exists or curl all seems to be some sort of drawback where it might not be turned on.
Thanks In Advance!

You can use the php $_SERVER['HTTPS'].
eg.
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
header("Location: myurl.com");
exit();
}
You should try both if the $_SERVER['HTTPS'] is empty and if the $_SERVER['HTTPS'] is set to on.
Be careful you should place this piece of code at the start of the page, because the redirection is happening with header() which only works if no html output is done.

Can you connect to $hostname:443?
Does $hostname:443 provide a valid certificate for $hostname
???
Profit!

Related

Https causing too many redirects?

I have a simple code in place for my php file to redirect to https if it's not present and I keep getting a too many redirects issue.
if(strtolower($_SERVER['HTTPS']) != 'on') {
redirect('https://domain.com/register.php');
}
Is there something I can do to fix the issue?
Thank you.
From PHP manual, $_SERVER['HTTPS'] is Set to a non-empty value if the script was queried through the HTTPS protocol. That isn't necessarily on. You may then end up in an infinite loop of redirects.
To avoid this, use the empty() function:
if ((!isset($_SERVER['HTTPS'])) || (empty($_SERVER['HTTPS']))
{
redirect('https://domain.com/register.php');
}
Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.
if(!isset($_SERVER['HTTPS'])){
//redirect
}

fsockopen() and header(location:xxx) in opened script?

strange problem, i'm opening a connection with fsockopen() to a page,
that page has a header(location:xx) to the same page (i'm just refreshing the script), but it'seems that the redirect isn't working...
obviously everything is working if i'm replicating it with a browser...
some code:
CONNECTION PAGE:
$socketcon = fsockopen($_SERVER['HTTP_HOST'],80,$errorno,$errorstr,10);
if($socketcon) {
$socketdata = "GET http://www.example.com/test2.php HTTP/1.0\r\nHost: ".$_SERVER['HTTP_HOST']."\r\nConnection: Close\r\n\r\n";
fwrite($socketcon,$socketdata);
fclose($socketcon);
}
CONNECTED PAGE (test2.php):
<?
//other code (working fine)
if($_GET["AAA"]){
//REDIRECT WORKED !
} else {
header("location:test2.php?AAA=1"); //same page but with a get param
}
?>
the REDIRECT WORKED part never get executed...
any suggestions ?
EDIT: the connection MUST be asynchronous
any suggestions ?
Yes, stop using a socket to do what cURL can do better ;) A header('Location: X') will actually send you a 301/303 HTTP response, which you (or the browser) should handle by making a new request. However, you don't seem to handle redirects. cURL, on the other hand, mimics browser-like functionality and it can follow redirects by using curl_setopt( $curlResource, CURLOPT_FOLLOWLOCATION, true );
Consider Is making asynchronous HTTP requests possible with PHP? which is a similar question.
Using exec()-family functions might be a good bet if you don't need return values; you can just call curl appended by & and it'll run in the background.
If you really, truly want to do this in PHP, you can either: spawn a new process (using pcntl_fork()) or handle redirects yourself.
To handle redirects you'll need to:
Determine what your response code is by looking at the first three characters read from the stream. A 200 means sucess, anything in the 300s means partial success.
Once you've found a 302 (or 307) in the first three characters, search for a location header. This will match the regex /\s*location:\s*(.+)$/m, I believe.
Validate that the URL you have from the location field matches your expectations and is trustworthy. It should be an absolute URL, but you'll need to check it for a safe server, safe port, safe URL and safe parameters. parse_url() may come in handy, but does not check for potential security issues.
Open a new connection to the new URL matched above (or, if it's the same host and you're using HTTP 1.1 with Keep-Alive, reuse your connection) to send the appropriate data.
Deal with any results/clean-up as required.
You can see this is very complex. This will also be recursive. What you're really talking about doing is writing a rudimentary HTTP parser in PHP. This is not a good idea - use cURL and find some other way to make it asynchronous.
Your connect function does not handle redirects.
If you want to support it you have to write the code yourself, or use a library like curl to make the connection.

Trouble redirecting to HTTPS with PHP

I just had an ssl installed for a site I am working on and I obviously need to get a few of the pages (checkout etc) redirected to https.
I am currently using this code:
if (!isset($_SERVER['HTTPS']) || !$_SERVER['HTTPS']) {
$url = 'https://www.mysite.php';
header("location: ". $url);
exit();
}
Firefox is telling me that "the page is trying to redirect in a way that will never complete."
A var_dump of $_SERVER shows no ['HTTPS'] or similar when I am on the secure page. This is on a Network Solutions small unix package. Is it possible I need to be checking for a different server variable or perhaps I need to change some server settings?
Clearly the script is never finding HTTPS so it is trying to redirect without end.
It becomes clearer if you use OR:
if (!isset($_SERVER['HTTPS']) OR !$_SERVER['HTTPS']) {
Chances are one of the conditions always evaluates to true, even when you already are in HTTPs mode.
You want AND:
if (!isset($_SERVER['HTTPS']) AND !$_SERVER['HTTPS']) {
I use this form of SSL Checking too. For me my code works. Here is what i do.
if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") {
header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
}
This works great and also redirects you to the previous url.
hope this helps.

blocking Proxies with PHP

I put the little code on the header of php file to blocking proxies:
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| ($_SERVER['HTTP_USER_AGENT']=='')
|| ($_SERVER['HTTP_VIA']!='')) {
die("Don't use proxies, please.");
}
In member.php I put the above code and its work very well and when someone request example.com/member.php with http proxy this code blocks them, but when they request example.com/member.php?action=login this code can't block them! What am I going to do? Thanks in Advance.
A blank user agent doesn't imply they're using a proxy... some people just don't like broadcasting what browser/OS they're using... As for why the login script doesn't get blocked why not look at what's in $_SERVER at each stage. A simple var_dump($_SERVER) will show everything and tell you why what you're trying to match isn't being matched.

$_SERVER["SCRIPT_URI"] not working? alternative?

This is odd, but for some reason the $_SERVER["SCRIPT_URI"] will not return the domain name when I am in child/sub-pages but will only work on the main page. Not sure if its due to the script (WordPress) or host, but please can you suggest any reliable solution to retrieve the domain name with PHP?
If you need domain name, use:
$_SERVER['HTTP_HOST']
When in doubt
var_dump($_SERVER);
Depending on what you want, I'd use one of the following:
$_SERVER['PHP_SELF'] for the script file location
$_SERVER['SERVER_NAME'] for the host name
From the php docs
EDIT: Maybe PHP_SELF isn't the best. See comments.
This might be due to URL rewriting, you can try $_SERVER['REQUEST_URI'] instead if you want the path that was called in the url.
I was using $_SERVER[SCRIPT_URI] on my website
http://www.a2zidx.com
and a number of subdirectories like
http://howto.a2zidx.com
I have had no problem with this for years and today got an error on a number of sites where $_SERVER[SCRIPT_URI] was not assigned. After contacting my isp they claim they have not made any changes but $_SERVER[SCRIPT_URI] no longer works. getenv('SCRIPT_URI') does not fail but returns a null string. Why this should happen suddenly after so many years I do not know. I ended up calling a function to go through various options to extract the filename which is what I wanted. Hope this covers everything. I had trouble including the function but checked
"SCRIPT_NAME"
"PHP_SELF"
"SCRIPT_FILENAME
"SCRIPT_URI"
Hope his helps.
If anyone knows why SCRIPT_URI would suddenly stop working I would love to know. The server is currently running Apache 2.4.
Also, SCRIPT_URI does not exist, the right syntax is REQUEST_URI:
echo $_SERVER["REQUEST_URI"]; It returns the whole path without the host and domain.
var_dump($_SERVER) and see what suites your needs.
P.S. Making use of unsanitized $_SERVER["PHP_SELF"] could be a security risk.
Late late reply. I use this piece of script to store information in my db. Hope this might help someone. How to get your full url and the ip address of the client access from.
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
$url = $_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME'];
echo $ip;
echo "<br>";
echo $url;
On Apache, SCRIPT_URI only exists when mod_rewrite is enabled.
Apache requires:
rewrite_module (note: use platform specific load syntax)
and
RewriteEngine On
statements in the Apache configuration file at the appropriate locations.
Then restart Apache, and it should work fine.
SCRIPT_URI is not fond because it has no any value when your site run with root domain. it only come when you working with sub-directory.
HTTP_HOST is not good idea when we working with sub-directory
use following code to get SCRIPT_URI :
$SCRIPT_URI = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].'/'.ltrim(dirname($_SERVER['SCRIPT_URL']),'/');
If your browser formats JSON documents nicely and no output has taken place, inserting the following will result in something more readable than var_dump:
header('Content-Type: application/json');die(json_encode($_SERVER));
phpinfo() will also provide a list of all $_SERVER values and so much more!

Categories