I've made a more simple ping statues system for my servers.
Right now my PHP function does a simple fsockopen and show Green/Red echo if up/down.
This ping status is only shown when the site is loaded.
Question : Can I somehow refresh and execute the function again without the whole page reload?
I mean to have live status of servers changing if it goes down, without reloading the whole page.
<?php
function pingstate($host, $port) {
if (!$socket = #fsockopen($host, $port, $errno, $errstr, 0.1)){
echo "<p class='pingRed'><i class='fa fa-circle'></i></p>";
} else {
echo "<p class='pingGreen'><i class='fa fa-circle'></i></p>";
fclose($socket);
}
}
?>
Example of output I use on other page than the function.
This part works great but I have to "reload" the page everytime I want new status of the ping.
$host = $row['host'];
$port = 80;
echo "<tr>
<td>" .$row['eq']."</td>
<td>".$row['ChargePoint']."</td>
<td>".$row['ip_addres']."</td>
<td>".$row['host']."</td>
<td><i class='fa fa-dashboard'></i></td>
<td><a href='http://".$row['host']."/' target='_blank'><i class='fa fa-gear'></i></a></td>
<td>";
echo pingstate($host, $port);
echo "</td></tr>";
I was thinking of maybe JavaScript that reloads the table row?
How can this be done, I googled but cannot find for reload functions..
Please help me with explanation, I really want to learn.
Thank you!
First things first: its real bad coding style to use PHP to echo html. You should avoid it if possible.
My structure would look like this:
create a file called server_check.php and use your checking code inside like this:
if (!$socket = #fsockopen($_GET["HOST"], $_GET["PORT"], $errno, $errstr, 0.1)){
echo json_encode("offline");
die;
} else {
echo json_encode("online");
fclose($socket);
die; }
echo json_encode("no ping possible");
Next step is to create a html file with the following content. I'm using jQuery for simplifying your problem. You may use vanilla javascript if you prefer that.
let server_list = {
"example.com": 111,
"example1.com": 111
};
function checkServer() {
for (const [key, value] of Object.entries(object)) {
$.ajax({
url: "server_check.php",
data: {
HOST: key,
PORT: value
}
}).done(function(data) {
$('#'+key).text(data);
});
}
}
setInterval(checkServer, 10000); //Checks server each 10 secs
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> Info about Server EXAMPLE.COM Server is
<p id="example.com">NOT CHECKED</p>
Server EXAMPLE1.COM Server is
<p id="example1.com">NOT CHECKED</p>
EDIT: Please be aware of several security issues and non existent error handling. Please read on several topics (GET/POST/HTTP requests) and ajax in general before using this in a productive environment. If you have further questions feel free to ask them right away.
Related
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
Any help is certainly appreciated.Thank You
Also it's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
There's multiple ways of doing so. I personally would use AJAX. On a 'form submit', run a javascript function calling an AJAX request to a .php file to check the form information, all using post method. Calculate all the $_POST['variables'] checking for your defined errors. You would have an html element print the errors via AJAX request.
If there are 0 errors then in the request back return a string as so that your javascript function can look for if its ready to go. If ready to go, redirect the user to where ever you please.
AJAX is not hard and I only suggested the idea sense you put javascript in your tags.
Another method:
Having all your code on one .php file. When you submit the form to the same .php file check for the errors (at the top of the file). If $_POST['variables'] exist, which they do after you submit the form, you echo your errors in the needed places. If zero errors then you redirect the page.
I'm working on making a website (developing locally) that requires a login for users; I've used php-login.net framework as my starting point and have my code talking to MySQL and creating sessions just fine.
I've gone through most every SO question regarding php sessions and ajax; but I still can't get my code to work how I want.
Now, I'm using ajax to call some other php scripts after the user successfully logs in, however it's not working properly. In firefox, with all the cookies, history, etc cleared, it looks like the session variables aren't maintained with the ajax call. However, if I log-out and then log back in, the session variables seem to be passed properly across ajax.
For example:
In my logged_in.php script, I'm using ajax to call another script: view_samples.php.
logged_in.php
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButtons.js
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
url: "view_samples.php",
cache: false,
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>
When I log in with a browser that hasn't logged in before, I see it sets a session ID X; however when the button is pressed and the ajax call is made, I see a new session ID Y. I then log-out and log back in and see that my session ID is Y (before ajax) and that my session ID is Y when I click the button (after ajax).
I've also noticed that if I keep logging-in & out without pressing the view samples button, a new session id generated each time. However, as soon as I press the button, a whole new session id is created which seems to always be the one that is set if I log-out and then back in.
What am I missing? What's the proper way to go about ensuring the first session that is created is maintained throughout ajax calls? Should I POST the session id to the called script?
This is how I solved things (as Freaktor's comment above didn't resolve the issue) - I'm manually passing the session ID through AJAX and then setting it in the new PHP script. I'm wondering if anyone could comment on the security of this (as I'm not entirely sure how this all works)?
This and this post were helpful.
logged_in.php
<script>var session_id = '<?php echo session_id();?>';</script> <!-- store our session ID so that we can pass it through ajax -->
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButton.js
var data = {func:'getData1',session_id:session_id}; // manually send the session ID through ajax
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
type: "POST",
data: data,
url: "view_samples.php",
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_id($_POST['session_id']); // get the session ID sent by AJAX and set it
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>
Thanks for all the answers, seems like AJAX is the solution, I'll give it a try. But what about JSON? Isn't JSON an even better solution? If it is, why is AJAX more preferable?
I'm looking for a way to update this part of php code every 5 seconds, which would regenerate this bootstrap list group. what would be a good way to do it? I figure I couldn't just wrap it in window.setInterval, and refreshing the entire page is not an option. Thanks in advance.
<?php
$i=0;
// Display all room
foreach ($rooms as $room) {
$room_num = $room['room_num'];
$room_type = $room['room_type'];
$note = $room['note'];
echo '
<a class="list-group-item" >
<h4 class="list-group-item-heading" id="room_num' .$i. '" ><p>'.$room_num." - " .$room_type.'</p></h4>
<p class="list-group-item-text" id="note' .$i. '" ><p>'.$note.'</p></p>
</a>
';
$i++;
}
$rooms = "";
getList();
?>
All on the same 'page.php'
php part:
<?
if ($_POST["whatever"])
{
echo 'your shizzle here'
exit;
}
?>
Javascript part: (with jquery)
<script>
setInterval(function()
{
$.post( "page.php", { whatever: 1}, function( data ) {
document.getElementById('someid').innerHTML = data;
});
},5000);
</script>
html part
<div id = "someid"></div>
Another way to do it could be using an iframe :) But iframes won't be used in the future I think.
Basically when you write php code inside javascript, it always run once, when the page is loaded. After this you just writing php code to the browser which is simply do not understand (Php is processed on the server, and the output is Html, Css, and Javascript, which the browser can interpret)
So, if you need to update data from the server without reloading the page, the only way to do this is with Ajax Requests, that basically connect to the server within the page and get data from it.
In your case, Save the PHP code which ever you want to execute in a file say php_temp.php
Now just do
setInterval(function(){
$.get("php_temp.php", function(data){
console.log(data) // data stores whatever php_temp.php echoes
});
},5000);
more on Ajax: Ajax Basics
So I have a notifications system set up and it all works perfect except when I come to clearing the notification. Its clears ok when the div opens but it also clears if I refresh the page without the div been opened at all, I'm not wanting the notification to clear until the user has opened the notifications div. How would I go about doing this?
Any help or someone that could point me in the right direction will be greatly appreciated
Thank you
I have been using this line of code to clear the notification
<?php user_core::clear_notifications($user1_id); ?>
And this code is the OnClick toggle()
<div class="alert_header_item_container">
<a onclick="toggle('alert_dropdown');">
<div class="alert_header_item" id="alerts"></div>
<?
$sql = "SELECT * FROM notifications WHERE notification_targetuser=".$user1_id." AND notification_status = '1'" ;
$chant= mysqli_query($mysqli,$sql);
$num = mysqli_num_rows($chant);
if($num==1) {
echo '<div class="alert_header_item_new" id="alerts"></div>';
} else {
echo "";
}
?>
</a>
The issue you're having is this:
PHP does not load or execute Javascript. Here is an order of
execution:
The user requests data from your web server.
Your web server executes your PHP script, which outputs some HTML/Javascript.
The web server sends the HTML/Javascript to the user's browser.
The user's browser renders the HTML and executes the Javascript. So yes, the PHP will
finish executing before the Javascript is executed.
Basically your PHP is completed before you even toggle the onclick event.
What you really want to be doing is something like this:
Structure your HTML something like this.
<div class="alert_header_item_container">
<a id="read-notifications">
<div class="alert_header_item" id="alerts"></div>
</a>
</div>
Now we'd run an ajax request (when the document loads) to fetch the notifications
$(document).ready(function(){
$.ajax({
type: 'post',
url: 'notifications.php',
data: {id: user_id},
}).success(function(data){
$('alerts').html(data);
});
});
Which would call notifications.php where you'd run your php/sql to fetch the notifications:
<?php
$user1_id = $_POST['id']; // then sanitize as needed
$sql = "SELECT * FROM notifications WHERE notification_targetuser=" . $user1_id . " AND notification_status = '1'";
$chant = mysqli_query($mysqli, $sql);
$num = mysqli_num_rows($chant);
if ($num == 1) {
while($row = mysqli_fetch_assoc()){
// make notifications markup
}
echo MARKUP_FROM_ABOVE
}
?>
As for the onclick event, you'd do something like this (to a seperate php file that will update the notifications to set them to read (which is probably 0 ?)):
$(document).on('click', 'a#read-notifications', function(e) {
$.ajax({
type: 'post',
url: 'readnotifications.php',
data: {id: user_id},
}).success(function(data) {
// do what you need to do as notifications were read.
});
});
And on readnotifications.php you'd run an sql query that would update the notifications for $_POST['id'] (The user id) to 0 (read).
After looking around on a Google without any success, i feel posting here may be a good idea as I have used this site to answer previous questions.
Anyways, I am currently working on an HTML5 canvas game using; PHP, MYSQL, Html5, and JavaScript.
I have MYSQL databases setup and an PHP page displaying player high-scores, and usernames.
My question is how would I go about displaying the high-scores inside the canvas once the game is over.
As well as saving the high score when the game ends. I've looked on W3SCHOOLS site about AJAX but I'm still unsure of what codes to use inside the JavaScript file.
These are my php/script codes. or at-least the ones that are relevant:
// Here's the savescore.php file
<?php
include 'connect.php';
$user_score = ($_POST['user_score']);
$user_name = ($_POST['user_name']);
if(mysql_query("INSERT INTO users VALUES('$user_name','$user_score')"))
echo "Score Successfully Saved";
else
echo "Score Saving Failed";
?>
// Here's some of the index.php file
<link rel="stylesheet" href="css.css">
</HEAD>
<body>
<div id="menu">
<a class="item" href="/index.php">Home</a>
<?php
include 'connect.php';
session_start();
if($_SESSION['signed_in'])
{
echo 'Hello ' . $_SESSION['user_name'] . '. Not you? Sign out';
include 'chat.php';
}
else
{
echo 'Sign in or create an account.';
}
?>
</div>
<BODY>
<canvas id="canvasGAMEOVER" width="800" height="599"> </canvas>
<script src="game.js"> </script>
// here's whats inside inside game.js... well the part I want to be able to save score
var score = 0;
function drawGAMEOVER() {
}
I have used google and looked at tutorials for AJAX, I found I have been able to connect to the server using AJAX only using:
<form action="savescore.php">
user_name: <input type="text" name="user_name"><br>
user_score: <input type="text" name="user_score"><br>
<input type="submit" value="Submit">
</form>
inside the index.php page, but I am not sure if its possible to grab the 'user_name' they logged in with (displayed on the index.php page) as well as this.score (displayed inside the javascript file.)
Could anyone tell me how this is possible... if not maybe a better way of doing this?
Any help/reply is much appreciated thanks in advance.
If you are using jquery you can use $.get to get all highscores.
http://api.jquery.com/jQuery.get/