Sending data from server to client?

I have a php server file and an HTML client file, the HTML file sends ajax requests to the server to retrieve data every 500 ms , although this works as expected, resulting in high memory and processor usage on the client device.

Php

 if(isset($_POST['id']) && $_POST['id'] != '' ) { $id = $_POST['id']; $select = $con->prepare("SELECT * FROM data WHERE id=?"); $select->bind_param('s', $id); $select->execute(); $result = $select->get_result(); while($row = $result->fetch_assoc()) { echo $row['column 1'] . "\t" . $row['column 2'] . "\n"; } } 

AJAKS

 function send(){ var formdata = new FormData(), id = document.getElementById('id').value; formdata.append('id', id); var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhr.open('post', 'server.php', true); xhr.send(formdata); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ console.log(xhr.responseText); } } } setInterval(function(){send()}, 500); 

I would like to find an alternative solution for ajax, instead of sending numerous requests to the server and receiving the same data most of the time, it would be much more effective if the server could interact with the client when changing or updating data.

I cannot use PHP Socket or HttpRequest medthods as they are not installed on my hosting server and I am not sure if it works later. The only way I can think of is to use SESSIONS .

according to this, the PHP server stores all user sessions in the same directory on the server, so it may be possible to change the session variables for a specific user directly to a file. however, the problem is that the data in these files is serialized, and I'm not sure how to de-serialize the data and re-serialize it, and then save the new data!

Even if I managed to find a way to store updates in the session file, I still need to use setInterval to listen for the change of the session variable every 500ms , although it is not ideal, but it will be much better than using XMLHttpRequest in terms of memory and processor usage.

So what's the best way to do this? Any help would be greatly appreciated.


UPDATE:

I realized that SESSION does not work, because it can only be read by the server, and not by the client, so I need to send an ajax request to the server to get the variables that I was trying to avoid.

I tried a lengthy poll, but I had a lot of problems with it, flush and ob_flush() do not work on my server, and I can not change the ini settings. When trying an infinite loop, I cannot make it break when data changes:

 if(isset($_GET['size']) && $_GET['size'] != '') { $size = (int)$_GET['size']; $txt = "logs/logs.txt"; $newsize = (int)filesize($txt); while(true) { if($newsize !== $size) { $data = array( "size" => filesize($txt), "content" => file_get_contents($txt)); echo json_encode($data); break; } else{ $newsize = (int)filesize($txt); usleep(400000); } } } 

it continues to move back and forth, even if the size of the logs.txt does not change! how can i make it break and echo data to increase size?

UPDATE 2:

it turned out that php cache has a file size when calling the filesize() method, so the specified loop will work indefinitely, the solution for this is to use the clearstatcache() method, which will clear the saved file size cache, allowing the loop to cancel file size changes.

+8
performance ajax php session
source share
5 answers

Well, after many tests and lengthy research, I came to the conclusion that the PHP server can never interact with the specified client directly unless the client first sends a request to the server.

The only reliable solution I found was to use an infinite loop that will only break when data changes, this will significantly reduce the frequency of ajax requests to the server, which will increase performance and reduce the use of memory and processor on the client device, this is how it goes:

PHP 1 (processes updating data or inserts new data into the database):

 $process = $_POST['process']; $log = "/logs/logs.txt"; if($process == 'update'){ //execute mysqli update command and update table. $str = "Update on " . date('d/m/Y - H:i:s') . "\n";//add some text to the logs file (can be anything just to increase the logs.text size) file_put_content($log, $str, FILE_APPEND);//FILE_APPEND add string to the end of the file instead or replacing it content } else if($process == 'insert'){ //execute mysqli insert command and add new data to table. $str = "Added new data on" . date('d/m/Y - H:i:s') . "\n"; file_put_content($log, $str, FILE_APPEND); } 

The above code inserts / updates the data, creates a log.txt file if it does not exist, and adds additional text to it for each request. log.txt will be used later in the infinite loop "below" and will break the loop when resized.

PHP 2 (processes requests for reading data):

 if(isset($_POST['id']) && $_POST['id'] != '' && isset($_POST['size']) && $_POST['size'] != '') { $id = (string)$_POST['id']; $init_size = (int)$_POST['count']; $size = file_exists('logs/logs.txt') ? (int)filesize('logs/logs.txt') : 0;//$size is logs.txt size or 0 if logs.txt doesn't exist(not created yet). $select = $con->prepare("SELECT * FROM data WHERE id=?"); $select->bind_param('s', $id); while(true){ //while(true) will loop indefinitely because condition true is always met if($init_size !== $size){ $select->execute(); $result = $select->get_result(); while($row = $result->fetch_assoc()) { $data['rows'][] = array( "column 1" => $row['column 1'], "column 2" => $row['column 2'], ); } $data['size'] = $size; echo json_encode($data); break; //break the loop when condition ($init_size != $size) is met which indicates that database has been updated or new data has been added to it. } else{ clearstatcache(); //clears the chached filesize of log.txt $size = file_exists('logs/logs.txt') ? (int)filesize('logs/logs.txt') : 0; usleep(100000) //sleep for 100 ms } } } 

AJAX:

 var size = 0; //declares global variable size and set it initial value to 0 function send(s){ var formdata = new FormData(), id = document.getElementById('id').value; formdata.append('id', id); formdata.append('size', s); var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhr.open('post', 'server.php', true); xhr.timeout = 25000; //set timeout on xmlhttprequest to 25 sec, some servers has short execution tiemout, in my case it 27 sec so i set the value to 25 sec. xhr.send(formdata); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ var data = JSON.parse(xhr.responseText); size = data.size; console.log(data.rows); setTimeout(function(){send(size)}, 100); //re-initiate the request after receiving data } } xhr.ontimeout = function(){ xhr.abort(); //abort the timed out xmlhttp request setTimeout(function(){send(size)}, 100); } send(size); 

This is not an ideal solution, but it reduced my xmlhttp requests from 2 / sec to a minimum of 1/25 sec, hoping that someone could come up with a better solution.

+5
source share

Previously, we had the opportunity to use sockets in browsers, we used the Long-poll. The basic idea is that instead of having the browser execute requests at regular intervals, the browser sends a request to the server, but the server will not respond until something worthwhile appears to share with it in the browser. This means that the request can be left open for 10 ms or for several hours.

After the server answers something, it is the browser job that creates the new ajax request. Thus, there is always a line open to the server.

See this question for more details.

+4
source share

Answering part of your question about direct session editing ...

To directly manipulate a user session, I assume that you know and can track any user session identifier (possibly in your database upon login).

When you need to edit a user session directly on the server:

  • Get the last user session from the database.
  • Call session_close() to close the current session (if any).
  • Call `session_name ($ sessionId) 'with the session identifier.
  • Call session_open() to open this session. $_SESSION must be populated with session data. You do not need to disassemble anything.
  • Make your changes to the session.
  • Call session_close() to reinitialize the data.

In addition, you can directly open the session file, unserialize() it, edit the data and re- serialize() .

+1
source share

You can create an ajax request for a php script that will only return data if there is any new data. Until there is no new data, the script continues to run in a loop until it is.

+1
source share

I think that today we need to use Websocket for this issue. without requesting the server, you can get data if something changes it to the server

see link

0
source share

All Articles