Clearing a chat window - php

I have created a chat window using php, ajax, and jquery. It successfully reads and writes to a file called chatlog.html. I have made a button that clears the chat. It works fine, but all of the clients' chats don't clear until someone speaks. How would I fix this?
chat.php is here since I can't format it correctly: http://pastebin.com/AEwjeZ3w
sendchatmsg.php:
<?php
session_start();
if (isset($_SESSION['username'])) {
$text = $_POST['cmsg'];
$fp = fopen("chatlog.html", "a");
fwrite($fp, "<div><b>" . $_SESSION['username'] . "</b>: " . stripslashes(htmlspecialchars($text)) . "<br></div>");
fclose($fp);
}
?>
clearchat.php:
<?php
unlink("chatlog.html");
?>

You can write empty file to it when you clear it.
clearchat.php:
$fp = fopen("chatlog.html", "w");
fwrite($fp, " ";
fclose($fp);

Reload the chat log in user's screen once the clear chat event completes.
$("#clearchat").click(function() {
$.post("clearchat.php",function(res){
loadLog();
});
});

Related

Run PHP code after ending the HTTP request

I'm writing a simple code to simply show to clients, data that is actually loaded from another HTTP server. The problem is that loading it from the remote server can take up to multiple seconds, and I don't want that much page load delay. So, I make my server cache a copy of this data. So that whenever a client sends a request to my server, it sends the ready-loaded copy and then loads a new copy from the remote server to update the local copy in case any changes were made.
So here's my pseudo code:
if(file_exists($cache_path)){
echo file_get_contents($cache_path);
// I need to end the HTTP request and close the connection here while continuing with the code.
$uptodate_content = file_get_contents("https://docs.google.com/document/export?format=pdf&id=$id");
// I don't want the user to wait for nothing, until this line.
}
else {
$uptodate_content = file_get_contents("https://someremotehost.com/someresource");
echo $uptodate_content;
}
echo file_put_contents($cache_path, $uptodate_content);
Hi I think the best solution is using a queue For example if you use the the queue, you can send it to the queue and then your consumer can pick it from the queue when it has time and user do not need to wait for it
This link is helpful
And this link will help you to use redis for this problem
This is a bad practice.
The connection can never end and you should be careful with such code
The better method is to run a cron job/queue every houerget data from remote server, or alternatively the remote server will trigger a trigger when updating data.
<?php
ob_end_clean();
header("Connection: close");
ignore_user_abort();
ob_start();
//your code
//your code
//your code
echo "response foo bar";
$obSize = ob_get_length();
header("Content-Length: $obSize");
ob_end_flush();
flush();
session_write_close();
// Do processing here
request_to_remote_server();
One way of doing it:
First, create a new PHP file, let's call it update.php, and write the following:
if (isset($argv[1])) {
storeDocumentToCache($argv[1]);
}
And in your current file, change the code to:
echo readDocumentFromCache($id) ?? storeDocumentToCache($id);
In old PHP versions (<7) it should be:
$content = readDocumentFromCache($id);
echo isset($content) ? $content : storeDocumentToCache($id);
Then require the following helper functions in both files (and set $cache_path):
function readDocumentFromCache($id, $fetch = true)
{
$cache_path = "?";
if (file_exists($cache_path)) {
return file_get_contents($cache_path);
}
if ($fetch) {
execInBackground("php " . __DIR__ . "/update.php $id");
}
return null;
}
funciton storeDocumentToCache($id)
{
$cache_path = "?";
$uptodate_content = file_get_contents("https://docs.google.com/document/export?format=pdf&id=$id");
file_put_contents($cache_path, $uptodate_content);
return $uptodate_content;
}
function execInBackground($cmd)
{
if (substr(php_uname(), 0, 7) == "Windows") {
pclose(popen("start /B " . $cmd, "r"));
} else {
exec($cmd . ' > /dev/null 2>/dev/null &');
}
}

Downloading a file while loading another page

The context is this:
The user click on a button
The page is refreshed with new information on the page (echo is used to print html code).
A file.txt is created
The download of the created file should start automatically
With the code below, the file is created and the remaining part of the page is presented, but no download starts. Also, if I click on the link, the download doesn't start, but the txt file is opened in the browser (whilst I want to force the download).
On the other hand, if I comment the javascript and uncomment the header instructions, I refresh the correct page and download the txt file, but the content of that file is wrong (it contains the html code echoed in the rest of the page).
=================NOT WORKING CODE==================
echo "
<form name=\"fn\" action=\"index.php?option=com_comp\" method=\"post\">
// more not related stuff
<input type=\"image\" src=\"".JURI::root().
"components/com_comp/images/download_icon.png\" .
"\" name=\"downloadaddresses\">DOWNLOAD_RESULTS
// more not related stuff";
if($_POST['downloadaddresses_x']!=0) {
$myfilename = "tmp/results.txt";
$fh = fopen($myfilename, 'w');
$recipients = $_POST['recipients'];
$semicolon_separated = implode(";", $recipients);
fwrite($fh, $semicolon_separated);
fclose($fh);
/*header('Content-disposition: attachment; filename='.$myfilename);
header("Content-type: application/octet-stream");*/
echo "<a href=\"".$myfilename."\" id=\"downloadlink\">
This download should start automatically!</a>";
echo "<script type=\"text/javascript\">
newwindow=function{
window.open('".$myfilename."','name','height=400,width=200');
if (window.focus) {newwindow.focus()}}
</script>";
}
========================MORE CODE THAT DOES NOT WORK==================
<script type="text/javascipt">
var el = document.getElementById('downloadlink');
if (document.createEvent) {
var event = document.createEvent(\"MouseEvents\");
event.initEvent(\"click\", true, true);
el.dispatchEvent(event);
}
else if (el.click) {
el.click();
}
</script>
Instead of this click simulation code:
<script type="text/javascipt">
var el = document.getElementById('downloadlink');
if (document.createEvent) {
var event = document.createEvent(\"MouseEvents\");
event.initEvent(\"click\", true, true);
el.dispatchEvent(event);
}
else if (el.click) {
el.click();
}
</script>
Can you use this:
<script type="text/javascript">
location.href = document.getElementById('downloadlink').getAttribute('href');
</script>

Content on page disappears

I have a simple script of code that reads a PHP file and when it get's changed it's supposed to say CHANGED on the page which I will change to refresh the page or change the content. For now, it shows the content, the function repeats once or twice and then it just shows nothing. Any help?
Here is the code:
<?php
$handle = fopen("../chat/real/chatserver.php", "r");
$contents = fread($handle, filesize("../chat/real/chatserver.php"));
fclose($handle);
$newcontents = $contents;
echo $contents;
?>
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("<?php $handle = fopen('../chat/real/chatserver.php', 'r');
$newcontents = fread($handle,filesize('../chat/real/chatserver.php'));fclose($handle);?>");
document.write("<?php if(!($contents==$newcontents)){echo 'Changed';} ?>");
setTimeout('checkchanged()',3000);
}
</script>
Link to example
Thanks for the help
This is because you can't include PHP in your JavaScript in order to execute it by the client. Yes, you can include PHP values, but that's it. Have a look at the source code in your browser:
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("");
document.write("");
setTimeout('checkchanged()',3000);
}
</script>
As you can see, the function document.write gets called with an empty string "". This is because everything that is in <?php ?> gets executed on the server, not on the client, before the resulting page gets sent to the client.
Since every PHP code is parsed only once $contents==$newcontents will be true, so you'll never see Changed.
To achieve something like a chat server you'll need new http request. Have a look at AJAX.

Check if user is logged in from different domain

Thanks to stackoverflow I got my little project going, but I am in need of some advice again. I would like to check if a user is logged on domain1.com and return a message on domain2. There is a lot more to the code. Below I have included a basic example of it.
index.php on http://domain2.com
<script type="text/javascript" src="http://domain1.com/test.php?js"></script>
test.php is on http://domain1.com.
<?php
if (isset($_GET['js'])){
header("Content-type:text/javascript");
?>
function doAjax(){
$.getJSON("http://domain1.com/index.php/home/callback.php?name=name&callback=?",
function(message) {
alert("Data Saved");
});
}
document.write('<button onclick="doAjax();">Submit</button>');
<?php } ?>
<?php exit; } ?>
callback.php is on http://domain1.com. This is where I would like to check if the user is logged in or not. If the user is logged in, the file gets written, if not I want to send a message to domain2.com asking for login.
<?php
$callback = $_GET['callback'];
$name = $_GET['name'];
$myFile = "txt/tester.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, $name);
fclose($fh);
header("Content-Type: application/javascript");
?>
<?php echo $callback; ?>("Message from the server");
This last part I got from a previous question. <?php echo $callback; ?>("Message from the server"); If that's the message to domain2, how do I call it?
So, basically, domain 2 is expecting a JSONP object from callback.php on domain 1. To format your message in a JSON object, enclose your message in an associative array (e.g: $msg = array('message' => 'This is the callback message');, and then pass it back to domain 2 with echo $_GET['callback'].'('.json_encode($msg).')'; Also, set the Content-Type in your header() declaration to application/json.

Check if form file exists on page load using PHP

So I have a simple form that takes a user input, passes it to a separate PHP script that does some processing on a different domain, and posts a txt file if successful. Example:
<form method="GET" action="inventory_check.php" target="_blank">
Part Number <input type="text" name="part" /><input type="submit" value="Check Inventory" />
</form>
<?php
$filename = $userInput;
if (file_exists('ftpMain/'.$filename.'')) {
$handle = fopen("ftpMain/".$filename."", "r");
$output = fread($handle, filesize('ftpMain/'.$filename.''));
fclose($handle);
$output = trim($output, '&l0O(10U');
$output = trim($output, 'E ');
echo $output;
}
else {
echo 'Failure.';
}
?>
So, inventory_check.php obviously is an inventory lookup for us, however, it's contained on another server (different domain) so it completes its processing and posts it to a file, that I read, cleanup, and display. Now my issue is twofold, I need to grab and keep the input from the user to find the filename and the second is I need to page to either reload or recheck if the file exists. What is the best approach to do this?
Note: We use an awful in house DBMS, so posting and retrieving from a DB is not an option, it took us a while to get it to read the input and FTP it correctly, so it looks like this is the only path.
Why don't you make the request in your server A? by using curl, so you could get the response right after the query.
Firstly, you'll need to get the user's input properly, and sanitize it. I'll leave out the details of the sanitize() method, as that's not really what you're asking.
<?php
if(isset($_POST)) {
$part_number = sanitize($_POST['part']);
$filename = "ftpMain/$part_number";
if (file_exists($filename)) {
$handle = fopen($filename, "r");
$output = fread($handle, filesize($filename));
fclose($handle);
/* Do things with output */
} else {
echo 'Failure.';
}
}
?>
However, you say that the file is on another server - looking for ftpMain/... is only going to look for a directory called ftpMain in your current directory. Is the file publicly available on the internet? If it is, you could do something like this:
<?php
$url = "http://yourserver.com/parts/$part_number.txt";
$response = get_headers($url, 1);
if ($response[0] == 'HTTP/1.1 200 OK') {
/* The file exists */
} else {
/* The file does not exist */
}
?>
I hope I've understood your question correctly - this assumes that the form action is pointing to itself. That is, your file with this code is also called inventory_check.php.

Categories