所有文件都应该有php扩展名或者php输出一个字符串吗? [关闭]
I'm wanting to show the server status of an ip on every page, but to check the status I need an php script. This script is what I found on the internet
<?php
$server='google.be:80';
$split=explode(':',$server);
$ip=$split[0];
$port=(empty($split[1]))?'80':$split[1];
$server=$ip.':'.$port;
$fp = @fsockopen($ip, $port, $errno, $errstr, 1);
if($fp){
echo $server.' is online';
fclose($fp);
}
else{
echo $server.' is offline';
}
?>
I want the echoes to be formatted like my css is formatted, so I could just replace the echoes with
?>
<p>Server is offline<p>
<?php
and
?>
<p>Server is online<p>
<?php
but then I would have to make every html file an php file, would you recommend that or is there a different way to handle this?
You could use jQuery AJAX to send the PHP data to your HTML page. You could json_encode the response and receive that data as a JSON object and get the data out of it.
EDIT: In a production enviroment and for efficiency, it would be best if you convert the HTML files to PHP files, it will be worth the labour. However this little snippet below could be used for other functionality if modified or built upon so it's a learning experience for you to see basic jQuery AJAX calls.
The following code is a working example of calling your PHP file and getting back the result. Seeing a basic example of using jQuery and AJAX will help you get a firm grounding of how to use it.
check_server.php
<?php
$server='google.be:80';
$split=explode(':',$server);
$ip=$split[0];
$port=(empty($split[1]))?'80':$split[1];
$server=$ip.':'.$port;
$fp = fsockopen($ip, $port, $errno, $errstr, 1);
$result = new stdClass();
if($fp){
$result->result = 'success';
fclose($fp);
}
else{
$result->result = 'offline';
}
echo json_encode($result);
?>
index.html
<html>
<head>
<title>Website</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$.ajax({
url : "check_server.php",
type : "POST",
dataType: "json",
success : function(results){
if (results.result === 'success')
{
$('#status').append('Server online.');
}
else
{
$('#status').append('Server offline.');
}
},
error : function()
{
$('#status').append('An error has occurred.');
}
});
</script>
</head>
<body>
<div id="status"></div>
</body>
</html>
It is not possible to implement PHP in a HTML file. To create HTML in a .php file is the best solution to solve this.
You can use HTML in a PHP file and you do not have to use PHP in the file if you name it a PHP file.
On my server all the files are a PHP since I need to include PHP functions such as echo username and such and I believe it doesn't hurt to convert .Html to .php. Another thing is that the following page provides information on styling PHP echoes with CSS.
I think it would be better have all php files.