PHP Server Status code error - php

I am trying to make a server status page for my game server and the code ends up not showing if the server is online.
<?PHP
$ts_ip = "177.82.148.141";
$ts_port = "2505";
$output = #fsockopen("$ts_ip", $ts_port, $errno, $errstr, 2);
stream_set_timeout($output, 00002);
if (!$output) {
echo "<FONT COLOR=#DD0000><B>FEB Offline</B></FONT>";
} else {
echo "<FONT COLOR=#00DD00><B>FEB Online</B></FONT>";
}
#fclose($output);
?>
It also gives me this error:
Warning: stream_set_timeout() expects parameter 1 to be resource, boolean given in /home/u918484727/public_html/teste.php on line 6
May someone help me?

"$ts_ip" shouldn't have " round them?

There's probably a better way to handle this but this will make it work.
$ts_ip = "177.82.148.141";
$ts_port = "2505";
$output = #fsockopen($ts_ip, $ts_port, $errno, $errstr, 2);
if (!$output) {
echo "<FONT COLOR=#DD0000><B>FEB Offline</B></FONT>";
} else {
echo "<FONT COLOR=#00DD00><B>FEB Online</B></FONT>";
stream_set_timeout($output, 00002);
#fclose($output);
}
I put $output logic in the else so that your code doesn't attempt to use it as a resource when it returns false.
Also, although it isn't the cause of the problem, as supajason pointed out you should probably use $ts_ip instead of "$ts_ip". You should also refactor your code in other ways, such as removing the # error suppression.

Related

php file_get_contents() returning false with a valid url

I'm currently working on a geocoding php function, using google maps API. Strangely, file_get_contents() returns bool(false) whereas the url I use is properly encoded, I think.
In my browser, when I test the code, the page takes a very long time to load, and the geocoding doesn't work (of course, given that the API doesn't give me what I want).
Also I tried to use curl, no success so far.
If anyone could help me, that'd be great !
Thanks a lot.
The code :
function test_geocoding2(){
$addr = "14 Boulevard Vauban, 26000 Valence";
if(!gc_geocode($addr)){
echo "false <br/>";
}
}
function gc_geocode($address){
$address = urlencode($address);
$url = "http://maps.google.com/maps/api/geocode/json?address={$address}";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
if($resp['status']=='OK'){
$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
if($lati && $longi){
echo "(" . $lati . ", " . $longi . ")";
}else{
echo "data not complete <br/>";
return false;
}
}else{
echo "status not ok <br/>";
return false;
}
}
UPDATE : The problem was indeed the fact that I was behind a proxy. I tested with another network, and it works properly.
However, your answers about what I return and how I test the success are very nice as well, and will help me to improve the code.
Thanks a lot !
The problem was the fact that I was using a proxy. The code is correct.
To check if there is a proxy between you and the Internet, you must know the infrastructure of your network. If you work from a school or a company network, it is very likely that a proxy is used in order to protect the local network.
If you do not know the answer, ask your network administrator.
If there is no declared proxy in your network, it is still possible that a transparent proxy is there. However, as states the accepted answer to this question: https://superuser.com/questions/505772/how-can-i-find-out-if-there-is-a-proxy-between-myself-and-the-internet-if-there
If it's a transparent proxy, you won't be able to detect it on the client PC.
Some website also provide some proxy detectors, though I have no idea of how relevant is the information given there. Here are two examples :
http://amibehindaproxy.com/
http://www.proxyserverprivacy.com/free-proxy-detector.shtml
When you are not return anything function returns null.
Just use that:
if(!is_null(gc_geocode($addr))) {
echo "false <br/>";
}
Or:
if(gc_geocode($addr) === false) {
echo "false <br/>";
}
Take a look at the if statement:
if(!gc_geocode($addr)){
echo "false <br/>";
}
This means that if gc_geocode($addr) returns either false or null, this statement will echo "false".
However, you never actually return anything from the function, so on success, it's returning null:
$address = urlencode($address);
$url = "http://maps.google.com/maps/api/geocode/json?address={$address}";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
if($lati && $longi){
echo "(" . $lati . ", " . $longi . ")"; //ECHO isn't RETURN
/* You should return something here, e.g. return true */
} else {
echo "data not complete <br/>";
return false;
}
} else {
echo "status not ok <br/>";
return false;
}
Alternatively, you can just change the if statement to only fire when the function returns false:
if(gc_geocode($addr)===false){
//...
Above function gc_geocode() working properly on my system, without any extra load. You have called gc_geocode () it returns you lat, long that is correct now you have check through
if(!gc_geocode($addr)){
echo "false <br/>";
}
Use
if($responce=gc_geocode($addr)){
echo $responce;
}
else{
echo "false <br/>";
}

can't get stream_set_timeout to work in foreach array loop

I'm not so familiar with PHP but have been able to get a script running that will check if a certain port is open for a number of local network computers.
the downside is that some pc's are offline and I can't get the timeout of the fsockopen function lower then 1 second (0.001 second would be enough)
I've found the *stream_set_timeout* function but can't seem to get it to work.
I'm pretty sure it's just in the wrong place, and hope someone can point out where it should go.
now I get this error:
Warning: stream_set_timeout() expects parameter 1 to be resource,
boolean given
snippet:
$timeout = 1000;
foreach ($farm as $pc){
$check = #fsockopen($pc, $port);
stream_set_timeout($check,0,$timeout);
if (is_resource($check))
{
echo $pc . " online";
fclose($check);
}
else
{
echo $pc . " offline";
}
}
current solution:
foreach ($farm as $pc){
$check = #fsockopen($pc,$port,$errCode,$errStr,0.001);
if (is_resource($check))
{
echo $pc . " online";
fclose($check);
}
else
{
echo $pc . " offline";
}
}

How to know whenever the connection is reset by peer in php?

I have been working lately on building a TCP server using PHP (I know wrong choice to begin with but this is the work standard), so I have reached a point where there is a reliable prototype to do tests on it and it showed good results. at start I used socket functions to handle to connection for server and it was working good but one of the main things on the project is to make the channel secured so I switched to stream_socket.
what I want is a socket_last_error equivalent in stream_socket group so I can know whenever the connection with client is closed or not. the current situation all processes will wait for timeout timer to release even tho the client is already closed.
I have searched the net and I found that there is no way to figure it out through PHP and I have found that some people opened issue ticket about it asking for socket_last_error equivalent for stream.
https://bugs.php.net/bug.php?id=34380
so is there anyway to know whenever FIN_WAIT signal is raised or not?
Thank you,
I don't think it's possible the stream_socket family, it looks like it's too high level.
I tried making a very hackish solution, I don't know if it will work for you, it's not very reliable:
<?php
set_error_handler('my_error_handler');
function my_error_handler($no,$str,$file,$line) {
throw new ErrorException($str,$no,0,$file,$line);
}
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)\n";
} else {
while ($conn = stream_socket_accept($socket)) {
foreach (str_split('The local time is ' . date('n/j/Y g:i a') . "\n") as $char) {
echo $char;
try {
fwrite($conn,$char);
} catch (ErrorException $e) {
if (preg_match("/^fwrite\(\): send of 1 bytes failed with errno=([0-9]+) ([A-Za-z \/]+)$/",$e->getMessage(), $matches)) {
list($errno,$errstr) = array((int) $matches[1], $matches[2]);
if ($errno === 32) {
echo "\n[ERROR] $errstr"; // Broken pipe
}
}
echo "\n[ERROR] Couldn't write more on $conn";
break;
}
fflush($conn);
}
fclose($conn);
}
fclose($socket);
}
echo "\n";
?>
Launch: php ./server.php
Connect: nc localhost 8000 | head -c1
Server output:
The loca
[ERROR] Broken pipe
[ERROR] Couldn't write more on Resource id #6

Variable is not printing to the screen when I use echo in PHP

I'm trying to print the host/ip to the screen. But, it's printing: "Resource id #2" instead. I'm using SSH2_connection(). I read the doc page and know the the function parameters are host, port, methods ... but when I try fread($host), the host/ip is still not printing can someone give me some direction on this? Thanks!
Code:
<?php
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
if(!($ssh = ssh2_connect('10.5.32.12', 22))) {
echo "fail: unable to establish connection\n";
} else {
if(!ssh2_auth_password($ssh, 'root', '********')) {
echo "fail: unable to authenticate\n";
} else {
echo "Okay: Logged in ... ";
$content = fread($ssh); //Line in question (want ip address to show here)
echo "$content <br>"; //Line in quesion
$stream = ssh2_exec($ssh, 'find / -name *.log -o -name *.txt');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
fclose($stream);
echo $data; // user
}
}
?>
I believe you need the parenthesis around the variabls as well when using double quotes. "{$content} <br>"
Have you tested with your own debug methods whether the $content variable contains information? You can set a value for the variable to test whether your echo statement is correct syntax.
$content = fread($ssh);
fread() reads from a file and puts the info into a resource handler for use later. I don't think you are using this in the right way currently.
I don't see where $ssh is being defined, but I assume it holds the IP you are wanting to output? If that is the case, just replace
$content = fread($ssh);
With:
echo $ssh;

Handle error when getimagesize can't find a file

when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.
I'm not sure how try catch works, but I want to do something like:
try: getimagesize($img) $works = true
catch: $works = flase
Like you said, if used on a non-existing file, getimagesize generates a warning :
This code :
if ($data = getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
will get you a
Warning: getimagesize(not-existing.png) [function.getimagesize]:
failed to open stream: No such file or directory
A solution would be to use the # operator, to mask that error :
if ($data = #getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
As the file doesn't exist, $data will still be false ; but no warning will be displayed.
Another solution would be to check if the file exists, before using getimagesize ; something like this would do :
if (file_exists('not-existing.png') &&
($data = getimagesize('not-existing.png'))
) {
echo "OK";
} else {
echo "NOT OK";
}
If the file doesn't exist, getimagesize is not called -- which means no warning
Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.
For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.
Finally :
I would allow errors to be displayed on your developpement server,
And would not display those on your production server -- see display_errors, about that ;-)
Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:
ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
print "NOT OK";
# We could even print out the warning here, just as PHP would do
print "$resize_warning";
} else {
print "OK"
}
Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.
I'm sorry that raise such old topic. Recently encountered a similar problem and found this topic instead a solution. For religious reasons I think that '#' is bad decision. And then I found another solution, it looks something like this:
function exception_error_handler( $errno, $errstr, $errfile, $errline ) {
throw new Exception($errstr);
}
set_error_handler("exception_error_handler");
try {
$imageinfo = getimagesize($image_url);
} catch (Exception $e) {
$imageinfo = false;
}
This solution has worked for me.
try {
if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
{
return $photoUrl;
}
} catch (\Exception $e) { return ''; }
Simple and working solution based on other answers:
$img_url = "not-existing.jpg";
if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
print_r($img_size);
echo "OK";
} else {
echo "NOT OK";
}

Categories