I have the following snippet that I am stuck at how to figure out getting the port number so the result might "turn" out correct as expected.
$server_list = array(
"localhost:8282" => array("test" => FALSE, "site_id" => "flyToHeaven"),
);
$server_name = $_SERVER["SERVER_NAME"];
if (!isset($server_list[$server_name])) {
$server_name = "unknown";
print "unknown server name!!";
exit();
i will always get "Unknown Server Name" in the output. If I delete the port number after localhost then the error is different, which means it passed this 'if' condition. Any help please ....
I believe what you're looking for is a combination of $_SERVER['SERVER_NAME'] and $_SERVER['SERVER_PORT'], which defaults to port 80.
Try this:
$server_name = $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
Source: http://www.php.net/manual/en/reserved.variables.server.php
I am using $_SERVER['HTTP_HOST'] which gives me server-name::port-number. The documentation says that this is "contents of the Host: header from the current request, if there is one".
My runtime environment is apache running on Linux and PHP 5.4 and this has always worked.
$_SERVER['SERVER_NAME'] will only return the name of the server.
If you're typing in http://localhost:8282 in the browser,
you'll get 'localhost' as the value of $_SERVER['SERVER_NAME'].
If you want to get the request port, you want to use $_SERVER['SERVER_PORT']. If you combine them both like so:
$server = $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
then you will get something closer to what you want.
I would suggest you look at the $_SERVER manual for all the details.
Related
I am desperately trying to make my form works.
But I am having issue with validating the recaptcha server side.
I have been looking around and going over my form a thousand times making tests, I know it doesn't pass the step of the recaptcha, but can't figure it out.
Here is my piece of code :
//variable :
$recaptcha = $_POST['g-recaptcha-response'];
//test captcha
if($recaptcha != '')
{
$secret = " MY KEY HERE";
$ip = $_SERVER['REMOTE_ADDR'];
$var = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$recaptcha."&remoteip=".$ip);
$array = json_decode($var,true);
//check if captcha ok then check fields empty
if($array['success'])
Please let me know if you can find anything wrong.
Thank you.
(indeed I removed my security key)
In my testing, I ran into two problems that you might be having.
The remoteip argument is optional. When I removed it, everything worked. Here's why: I was testing with both client and server machines on private IP's behind a firewall, so the $_SERVER['REMOTE_ADDR'] value on my server was 192.168.x.x. Google saw the public IP of my NAT firewall, so that is what siteverify tried to match against.
You can only check a given response once. If you try to check it again, it will always fail. So during testing you need to use a fresh one each time.
Also, you can simplify your PHP code a bit by using:
"...siteverify?secret=$secret&response=$recaptcha");
Try this:
$secret = "YOUR-SECRET-KEY";
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $_POST['g-recaptcha-response']);
$googleResponse = json_decode($verifyResponse);
if ($googleResponse->success)
{
$captchaVerified = true;
}
I wish to extract the exact hostname from an ip address but what i am receiving is an entire string of the address.
I would just like to extract only the Host Name from the the string. Can any one point me in the right direction ?
Here is the snippet of the code being used:-
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$fullhost = gethostbyname(gethostbyaddr($ip));
$host = preg_replace("/^[^.]+./", "*.", $fullhost);
?>
Host: <?=$host?>
The output received from it is :-
Host: *.36.64.182.airtelbroadband.in
I would just like to display Airtel Broadband and nothing else to the user
You can try this:
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']); // gets the full hostname
$hostNames = explode(".", $host); // explodes into parts divided by DOT
echo $hostNames[count($hostNames)-2]; // take what you need
// $hostNames[count($hostNames)-1]; -> in
// $hostNames[count($hostNames)-2]; -> airtelbroadband
You might also want to look into geoip.
This is a basic PHP extension that can be installed using PECL.
string geoip_isp_by_name ( string $hostname )
The geoip_isp_by_name() function will return the name of the Internet Service Provider (ISP) that an IP is assigned to.
This function is currently only available to users who have bought a commercial GeoIP ISP Edition. A warning will be issued if the proper database cannot be located.
Consider this simple example:
<?php
$subject = 'Host: *.36.64.182.airtelbroadband.in';
$pattern = '/^Host:\s+((\*|\d+)\.){4}(.+)\..+$/';
preg_match($pattern, $subject, $tokens);
var_dump($tokens[3]);
The output obviously is:
string(15) "airtelbroadband"
That is all the information you can rip from your input. If you really want to somehow show the "publicly known company names" (as opposed to the technical network names), then you need to use some form of catalog. It is very hard to somehow retrieve such information directly from the network. You could give the whois database a try. But parsing the output of that will be a really tough task...
I have a form to get some urls from users.
Eg: web address, facebook address, twitter address etc. Then I need to check user may or may not enter the protocol as part of the address. If protocol is not with submitted url I need to add protocol to it.
In this case it is http://. As well as sometimes users may type the protocol incorrectly.
Eg. htttp:/, http//, htp:// etc..
With this issue I need to know is there any way to remove the protocol completely which users has entered and add new protocol with that URL to insert to the database.
I wrote some code to detect submitted URL has a protocol.. Its working little I am expecting but not 100%.
$url = 'www.example.com';
$checkProtocol = strpos($url, '://');
if (false === $checkProtocol ) {
$url = 'http://' . $url;
echo 'This is new URL : ' . $url;
} else {
echo 'Invalid';
}
Just assume $url have htp://www.example.com its become an invalid url.. not assigning the protocol.
Hope someone help me out.
Thank You.
If you want to handle all cases, you might just want to assume that the URL is missing the http:// or has it malformed and just add it in all cases after cleaning the string:
$url = 'htp://www.example.com';
$fixed_url = 'http://' . preg_replace('#^.*://#', '', $url);
Okay so the basically I'm building an application to connect to xero on the activecollab framework. And I'm testing the xeroapi php script created by David Pitman. And I'm just trying to find out why my browser responds with The connection to the server was reset while the page was loading. (but doesn't generated any liveheaders nor does firebug pick anything up)...
(source: iforce.co.nz)
Here is a snippet of code, that is being used. (Everything has been setup prior using the XERO Api previewer and openssl.)
define('XERO_KEY','my-key-here'); //hidden for privacy reasons
define('XERO_SECRET','my-key-here'); //hidden for privacy reasons
define('XERO_PUBLIC_KEY_PATH', 'path/to/public.key');
define('XERO_PRIVATE_KEY_PATH', 'path/to/privatekey.pem');
$xero = new Xero(XERO_KEY, XERO_SECRET, XERO_PUBLIC_KEY_PATH, XERO_PRIVATE_KEY_PATH, 'xml' );
$organisation = $xero->organisation;
//echo the results back
if ( is_object($organisation) ) {
//use this to see the source code if the $format option is "xml"
echo htmlentities($organisation->asXML()) . "<hr />";
} else {
//use this to see the source code if the $format option is "json" or not specified
echo json_encode($organisation) . "<hr />";
}
And my problem is... that the error_log (php) doesn't display any errors a part from a warning:
2012-07-23 21:59:42 Notice : Undefined index: port (at C:\xampp\htdocs\ac3\activecollab\3.1.10\modules\xero_invoice_manager\lib\xero\xero.class.php on 644 line)
The code on xero.class.php line 644
/**
* parses the url and rebuilds it to be
* scheme://host/path
*/
public function get_normalized_http_url() {
$parts = parse_url($this->http_url);
$port = #$parts['port']; //this line says its undefined
$scheme = $parts['scheme'];
$host = $parts['host'];
$path = #$parts['path'];
$port or $port = ($scheme == 'https') ? '443' : '80';
if (($scheme == 'https' && $port != '443')
|| ($scheme == 'http' && $port != '80')) {
$host = "$host:$port";
}
return "$scheme://$host$path";
}
From investigating I've found on print_r the result of $parts in a preformatted tag is..
Array
(
[scheme] => https
[host] => api.xero.com
[path] => /api.xro/2.0/Organisation
)
The same information is used on a live server (for the past couple of months). but the xeroapi class is not working on the test server, does anyone have any advice as to why it isn't connecting? I'm running XAMPP Control Panel with apache on port 80 and PHP Version 5.3.8.
I'm not sure about your port issue.
However, the Xero API require an OAuth set-up, which is presumably done for you in the Xero class. Part of the OAuth stuff is setting a callback domain, this requires you register a callback domain with Xero. Xero allows you to use subdomains of the registered domain and I assume that the Xero class uses request information to set the correct domain.
On localhost, that domain is localhost, which is not a subdomain. You can register localhost, or do what I have done (because I don't have access to the Application account), and set a special local subdomain in your hosts file.
So if you use example.com, then a good 'local' domain is local.example.com. Hope that helps.
recently i noticed that on my new server the gethostbyaddr() function which is used on my site to get the referes' hosts, it makes the page load 5 times slower.
and when I removed it the time out problem is gone
what is wrong with this function and my new Centos linux server config.
and what else i can use instead of this php function to get the host name of my referers.
It may be a temporary slowness in DNS resolution and it may clear itself up later. There really isn't any alternative to gethostbyaddr() other than to make a system call like the following from PHP. (gethostbyaddr() does essentially this anyway)
`nslookup $ip_address`
// Or
`host $ip_address`
You can test to see if resolutions are slow from the command line with :
# choose an IP address you know the resolution of...
$ host 123.123.123.123
If this doesn't return quickly you may have a DNS problem.
Check the contents of /etc/resolv.conf and if you have an alternate DNS server you can point it to, try that one instead.
I wrote this useful replacement for gethostbyaddr():
//faster alternative to gethostbyaddr()
private function gethost( $ip )
{
//Make sure the input is not going to do anything unexpected
//IPs must be in the form x.x.x.x with each x as a number
if( preg_match( '/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip ) )
{
$host = `host -s -W 1 $ip`;
$host = ( $host ? end( explode( ' ', trim( trim( $host ), '.' ) ) ) : $ip );
if( in_array( $host, Array( 'reached', 'record', '2(SERVFAIL)', '3(NXDOMAIN)' ) ) )
{
return sprintf( '(error fetching domain name for %s)', $ip );
}
else
{
return $host;
}
}
else
{
return '(invalid IP address)';
}
}
The trick is to use the host function, but you have to check if the $ip is a real IP to avoid exploits.
I set the timout to 1 second.
It's much faster than using gethostbyaddr, although it is still slow when used in a loop.
What kind of web hosting do you have? Shared, VPS or dedicated. gethostbyaddr() performance is dependent on how effective your web server DNS resolution is. There are some scenarios which might decrease its performance but you would still need to say at least what type of hosting you are using.
I think you should just implement some type of caching system for gethostbyaddr() results (Well, most of DNS servers have built-in caching system, but your can malfunction for some reason) or try to use alternative DNS servers(with system call or better with PHP's sockets).
Unfortunately some isp's don't maintain reverse dns records for some ip addresses, and therefore a dns lookup will always fail. The problem is how long to wait before giving it up.
Some hosting services set the gethostbyaddr function timeout real short, and if a lookup isn't successful, the ip address will be substituted for the host name. This speeds things up, preventing long delays in displaying pages that call this function.
You should always scrutinize log entries that don't show host names, as they rather frequently indicate that the visitor is from an ip address with a reputation for nefarious Internet activity.
As gethostbyaddr() does not support timeouts and my hosting setup does not allow shell commands I decided to use a local API:
<?php
$ip = isset($_GET['ip']) ? filter_var($_GET['ip'], FILTER_VALIDATE_IP) : false;
if ($ip) {
echo json_encode(gethostbyaddr($ip));
}
?>
And now I send a request to this hostAPI.php through file_get_contents() as follows:
<?php
// prepare host url
function isSecure() {
return ((isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) ? 's' : '';
}
$protocol_host = 'http' . isSecure() . '://' . filter_input(INPUT_SERVER, 'HTTP_HOST', FILTER_SANITIZE_URL);
// dns request
$context = stream_context_create(array(
'http' => array(
'timeout' => 0.4,// 400 ms
)
));
$ip = long2ip(mt_rand(0, "4294967295"));
// note: the host url needs public access!
$host = json_decode(#file_get_contents($protocol_host . '/hostAPI.php?ip=' . $ip, false, $context), true);
// output
echo 'IP: ' . $ip . "<br>\n";
echo 'HOST: ' . ($host ? $host : 'Timeout!') . "<br>\n";
echo 'Execution Time: ' . round((microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]) * 1000) . ' ms';
?>
As you can see I set the timeout through stream_context_create().
Sample output:
IP: 56.152.200.204
HOST: Timeout!
Execution Time: 801 ms
IP: 81.139.131.130
HOST: host81-139-131-130.range81-139.btcentralplus.com
Execution Time: 52 ms
I do not know why, but on my setup the 0.4 timeout kicks in after > 800 ms so I needed to double the value to get the final timeout. Maybe someone else can comment that.
Warning
This creates one additional http request on your server for every request on your main script!
After upgrading from XP to 7 it effected PHP's handling of IPv4 versus IPv6 (e.g. 127.0.0.1 is returned as ::1) I had adapted some code to temporarily address this issue. It turns out that I was using gethostbyaddr on the IPv6 patch and thus it was getting stuck timing out for PHP.
Before...
$ip = ip2long6($ip);
$host = gethostbyaddr($ip);
After...
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
You can use Xdebug and WinCacheGrind (I use XAMPP for local testing) to find what is timing out, here is a video tutorial for a quick run-through...
http://www.warpconduit.net/2012/09/01/quick-tip-profiling-php-applications-with-xdebug-wincachegrind-xampp-for-windows/
Hope this saves someone some sanity. :-)