11xza
11xza

Reputation: 15

how do i put a php text on top of html

I have a simple chatting system, and what i want to do is put new messages on top of html. My script puts new messages on bottom and i want to change it.

<?php
 session_start();
 if(isset($_SESSION['name'])){
 $text = $_POST['text'];
 
 $text_message = "<div class='msgln'><span class='chat-time'>".date("m.d.y")."</span><br> <b 
 class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<p></div>";
 file_put_contents("../log.html", $text_message, FILE_APPEND | LOCK_EX);
 }
?>

The script prints text on the clean log.html file

Upvotes: 1

Views: 300

Answers (2)

Thien Nguyen
Thien Nguyen

Reputation: 135

You are doing file content append with file_put_contents() function, so the content newly added to the file will eventually goes to the bottom.

I will suggest a workaround for your problem. First save your log.html file content to a variable, override the newly added message to the file (overwrite the whole file), lastly append the log file content you have saved to the file. This way you can make the new content always appear on top of the file.

<?php
 session_start();
 if(isset($_SESSION['name'])){
 $text = $_POST['text'];
 $file_content = file_get_contents("../log.html");
 $text_message = "<div class='msgln'><span class='chat-time'>".date("m.d.y")."</span><br> <b 
 class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<p></div>";
 file_put_contents("../log.html", $text_message);
 file_put_contents("../log.html", $file_content, FILE_APPEND | LOCK_EX);
 }
?>

Upvotes: 1

Juakali92
Juakali92

Reputation: 1143

Simply remove the FILE_APPEND flag which instead of overwriting the file will append to the end and then use a file_get_contents() to join both strings of text.

<?php
 session_start();
 if(isset($_SESSION['name'])){
 $text = $_POST['text'];
 
 $text_message = "<div class='msgln'><span class='chat-time'>".date("m.d.y")."</span><br> <b 
 class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<p></div>";
 file_put_contents("../log.html", $text_message.file_get_contents("../log.html"), LOCK_EX);
 }
?>

Upvotes: 1

Related Questions