Php How to Make the Whole Form Read Only
Read Time: 17 mins Languages:
In this tutorial, we volition exist creating a uncomplicated web-based chat application with PHP and jQuery. This sort of utility would be perfect for a alive back up organisation for your website.
This tutorial was updated recently to make improvements in the chat app.
Introduction
The chat awarding nosotros will be edifice today volition be quite simple. It will include a login and logout system, AJAX-mode features, and support for multiple users.
Pace 1: HTML Markup
We volition start this tutorial by creating our first file, called index.php.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-viii" /> <title>Tuts+ Chat Application</title> <meta name="description" content="Tuts+ Chat Application" /> <link rel="stylesheet" href="style.css" /> </head> <body> <div id="wrapper"> <div id="carte du jour"> <p class="welcome">Welcome, <b></b></p> <p class="logout"><a id="get out" href="#">Exit Conversation</a></p> </div> <div id="chatbox"></div> <form name="message" activeness=""> <input name="usermsg" type="text" id="usermsg" /> <input name="submitmsg" type="submit" id="submitmsg" value="Send" /> </form> </div> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.ane/jquery.min.js"></script> <script type="text/javascript"> // jQuery Document $(certificate).ready(part () {}); </script> </body> </html> - We starting time our HTML with the usual DOCTYPE, html, caput, and body tags. In the head tag, we add together our title and link to our CSS stylesheet (way.css).
- Within the body tag, we structure our layout inside the
#wrapperdiv. Nosotros volition have three main blocks: a simple menu, our chatbox, and our message input, each with its corresponding div and id.- The
#menudiv will consist of ii paragraph elements. The showtime volition be a welcome to the user and will be on the left, and the second will exist an leave link and will exist on the right. We are using flexbox instead of floating elements for the layout. - The
#chatboxdiv will comprise our chatlog. We will load our log from an external file using jQuery'due southajaxrequest. - The terminal detail in our
#wrapperdiv volition exist our form, which will include a text input for the user message and a submit button.
- The
- Nosotros add our scripts terminal and then that the page will load faster. Nosotros will get-go link to the Cloudflare jQuery CDN, as we will exist using the jQuery library for this tutorial. Our second script tag is what we will be working on. We will load all of our code afterward the document is ready.
Step 2: CSS Styling
Nosotros will now add some CSS to brand our conversation awarding look ameliorate than with the default browser styling. The code below volition be added to our style.css file.
* { margin: 0; padding: 0; } torso { margin: 20px auto; font-family unit: "Lato"; font-weight: 300; } form { padding: 15px 25px; display: flex; gap: 10px; justify-content: middle; } form characterization { font-size: 1.5rem; font-weight: bold; } input { font-family: "Lato"; } a { color: #0000ff; text-ornament: none; } a:hover { text-decoration: underline; } #wrapper, #loginform { margin: 0 motorcar; padding-bottom: 25px; background: #eee; width: 600px; max-width: 100%; border: 2px solid #212121; border-radius: 4px; } #loginform { padding-peak: 18px; text-align: eye; } #loginform p { padding: 15px 25px; font-size: one.4rem; font-weight: bold; } #chatbox { text-align: left; margin: 0 auto; margin-lesser: 25px; padding: 10px; background: #fff; pinnacle: 300px; width: 530px; edge: 1px solid #a7a7a7; overflow: car; border-radius: 4px; border-bottom: 4px solid #a7a7a7; } #usermsg { flex: ane; edge-radius: 4px; border: 1px solid #ff9800; } #proper noun { border-radius: 4px; border: 1px solid #ff9800; padding: 2px 8px; } #submitmsg, #enter{ background: #ff9800; border: 2px solid #e65100; color: white; padding: 4px 10px; font-weight: assuming; edge-radius: 4px; } .fault { color: #ff0000; } #menu { padding: 15px 25px; display: flex; } #menu p.welcome { flex: one; } a#exit { color: white; background: #c62828; padding: 4px 8px; border-radius: 4px; font-weight: bold; } .msgln { margin: 0 0 5px 0; } .msgln span.left-info { color: orangered; } .msgln bridge.chat-time { color: #666; font-size: lx%; vertical-align: super; } .msgln b.user-proper noun, .msgln b.user-proper noun-left { font-weight: bold; background: #546e7a; color: white; padding: 2px 4px; font-size: ninety%; border-radius: 4px; margin: 0 5px 0 0; } .msgln b.user-proper noun-left { background: orangered; } At that place'southward nada special about the above CSS other than the fact that some ids or classes, which nosotros have set a manner for, will be added a bit later on.
As you can see higher up, we are finished building the chat'southward user interface.
Pace 3: Using PHP to Create a Login Form
Now we will implement a simple form that will enquire the user their name before continuing further.
<?php session_start(); if(isset($_POST['enter'])){ if($_POST['proper name'] != ""){ $_SESSION['proper noun'] = stripslashes(htmlspecialchars($_POST['name'])); } else{ repeat '<span form="mistake">Please blazon in a name</bridge>'; } } function loginForm(){ echo' <div id="loginform"> <p>Delight enter your proper noun to continue!</p> <form action="index.php" method="post"> <characterization for="name">Proper name —</label> <input type="text" name="name" id="name" /> <input blazon="submit" name="enter" id="enter" value="Enter" /> </form> </div> '; } ?> TheloginForm() role we created is composed of a unproblematic login form which asks the user for their name. Nosotros then utilize an if and else argument to verify that the person entered a name. If the person entered a name, we set that name as $_SESSION['name']. Since we are using a cookie-based session to shop the name, we must telephone callsession_start() before anything is outputted to the browser.
One thing that you lot may want to pay close attention to is that we have used the htmlspecialchars() function, which converts special characters to HTML entities, therefore protecting the name variable from falling victim to cross-site scripting (XSS). After, we will also add this function to the text variable that will exist posted to the conversation log.
Showing the Login Form
In order to show the login form in example a user has not logged in, and hence has not created a session, we apply some other if and else statement around the#wrapper div and script tags in our original lawmaking. In the reverse example, this will hibernate the login class and show the chat box if the user is logged in and has created a session.
<?php if(!isset($_SESSION['name'])){ loginForm(); } else{ ?> <div id="wrapper"> <div id="menu"> <p class="welcome">Welcome, <b><?php repeat $_SESSION['name']; ?></b></p> <p class="logout"><a id="exit" href="#">Exit Chat</a></p> </div> <div id="chatbox"> <?php if(file_exists("log.html") && filesize("log.html") > 0){ $contents = file_get_contents("log.html"); echo $contents; } ?> </div> <form name="bulletin" activity=""> <input proper name="usermsg" type="text" id="usermsg" /> <input proper name="submitmsg" blazon="submit" id="submitmsg" value="Send" /> </form> </div> <script blazon="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/iii.five.1/jquery.min.js"></script> <script type="text/javascript"> // jQuery Document $(document).fix(function(){ }); </script> <?php } ?>
Welcome and Logout Menu
Nosotros are non yet finished creating the login organisation for this chat awarding. We withal need to permit the user to log out and end the chat session. If you remember, our original HTML markup included a simple card. Let's go back and add some PHP code that volition give the bill of fare more functionality.
Outset of all, permit's add the user's name to the welcome message. Nosotros do this by outputting the session of the user'south proper name.
<p grade="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>
In order to allow the user to log out and end the session, we will jump alee of ourselves and briefly use jQuery.
<script type="text/javascript"> // jQuery Document $(document).prepare(office(){ //If user wants to end session $("#leave").click(office(){ var go out = ostend("Are you lot sure you desire to end the session?"); if(exit==true){window.location = 'index.php?logout=true';} }); }); </script> The jQuery code higher up simply shows a confirmation alert if a user clicks the #exit link. If the user confirms the leave, therefore deciding to finish the session, then we transport them toindex.php?logout=true. This but creates a variable called logout with the value of true. Nosotros need to take hold of this variable with PHP:
if(isset($_GET['logout'])){ //Simple get out bulletin $logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the conversation session.</span><br></div>"; file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX); session_destroy(); header("Location: alphabetize.php"); //Redirect the user } Nosotros at present see if a go variable of 'logout' exists using theisset() part. If the variable has been passed via a URL, such every bit the link mentioned higher up, nosotros proceed to end the session of the user'due south proper noun.
Before destroying the user's name session with thesession_destroy() function, we want to write a unproblematic get out message to the chat log. Information technology volition say that the user has left the chat session. We do this by using thefile_put_contents() function to manipulate ourlog.html file, which, as nosotros will see later on, will be created as our chat log. Thefile_put_contents() office is a convenient manner to write information to a text file instead of usingfopen(),fwrite(), and fclose() each time. Just make certain that you pass appropriate flags likeFILE_APPEND to suspend the data at the cease of the file. Otherwise, a new $logout_message will overwrite the previous content of the file. Please note that we have added a class ofmsgln to the div. Nosotros have already defined the CSS styling for this div.
Subsequently doing this, we destroy the session and redirect the user to the same page where the login form will appear.
Step iv: Handling User Input
After a user submits our course, we want to take hold of their input and write it to our chat log. In order to exercise this, we must utilize jQuery and PHP to work synchronously on the client and server sides.
jQuery
Most everything we are going to do with jQuery to handle our data will circumduct around the jQuery mail request.
//If user submits the grade $("#submitmsg").click(function () { var clientmsg = $("#usermsg").val(); $.mail("post.php", { text: clientmsg }); $("#usermsg").val(""); return false; }); - Before we exercise annihilation, nosotros must grab the user'southward input, or what the user has typed into the
#submitmsginput. This can be achieved with theval()office, which gets the value set in a course field. We at present shop this value in theclientmsgvariable. - Here comes our most important part: the jQuery post asking. This sends a POST request to the postal service.php file that we will create in a moment. It posts the customer's input, or what has been saved into the
clientmsgvariable. - Lastly, we clear the
#usermsginput by setting the value aspect to bare.
Please note that the code to a higher place volition go into our script tag, where nosotros placed the jQuery logout code.
PHP: The post.php File
At the moment, nosotros have Mail service data being sent to the postal service.php file each time the user submits the class and sends a new message. Our goal at present is to catch this data and write it into our chat log.
<? session_start(); if(isset($_SESSION['proper noun'])){ $text = $_POST['text']; $text_message = "<div class='msgln'><span class='conversation-fourth dimension'>".date("g:i A")."</span> <b class='user-name'>".$_SESSION['proper name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>"; file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX); } ?> Earlier we do anything, nosotros have to start thepost.php file with thesession_start() function as we volition be using the session of the user's name in this file.
Using theisset boolean, we bank check if the session for 'name' exists earlier doing anything else. We at present grab the Post data that was existence sent to this file past jQuery. We store this data into the$text variable. This data, like all the overall user input data, will exist stored in the log.html file. We simply use thefile_put_contents() function to write all the information to the file.
The message we volition be writing will be enclosed inside the.msgln div. Information technology will contain the date and time generated by thedate() function, the session of the user's proper name, and the text, which is also surrounded by thehtmlspecialchars() function to forestall XSS.
Footstep 5: Displaying the Chat Log Contents
Everything the user has posted is handled and posted using jQuery; it is written to the chat log with PHP. The only thing left to do is to display the updated chat log to the user withlog.php.
In lodge to save ourselves some fourth dimension, we volition preload the chat log into the#chatbox div if it has any content.
<div id="chatbox"><?php if(file_exists("log.html") && filesize("log.html") > 0){ $contents = file_get_contents("log.html"); echo $contents; } ?></div> We use a similar routine every bit nosotros used in the mail.php file, except this fourth dimension we are only reading and outputting the contents of the file.
ThejQuery.ajax Asking
The AJAX request is the core of everything nosotros are doing. This request not only allows u.s.a. to send and receive data through the class without refreshing the page, but information technology also allows usa to handle the data requested.
//Load the file containing the chat log function loadLog(){ $.ajax({ url: "log.html", cache: faux, success: function(html){ $("#chatbox").html(html); //Insert conversation log into the #chatbox div }, }); } We wrap our AJAX asking inside a office. You will see why in a second. Equally you see above, we will only utilise three of the jQuery AJAX asking objects.
-
url: A string of the URL to asking. We will use our chat log'southward filename of log.html. -
cache: This volition forbid our file from existence cached. It will ensure that we get an updated chat log every time we transport a request. -
success: This will allow us to adhere a part that will pass the information we requested.
As yous run into, we and so movement the HTML data nosotros requested into the#chatbox div.
Auto-Scrolling
As you may have seen in other chat applications, the content automatically scrolls down if the chat log container (#chatbox) overflows. We are going to implement a unproblematic and similar feature, which will compare the container'southward curlicue height before and after we practise the AJAX request. If the scroll height is greater later on the asking, nosotros volition apply jQuery's animate event to scroll the #chatbox div.
//Load the file containing the chat log function loadLog(){ var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Coil peak before the request $.ajax({ url: "log.html", cache: simulated, success: office(html){ $("#chatbox").html(html); //Insert chat log into the #chatbox div //Automobile-scroll var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Roll height after the asking if(newscrollHeight > oldscrollHeight){ $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div } }, }); } Nosotros get-go store the#chatbox div'due south scroll tiptop into theoldscrollHeight variablebefore we brand the request. Afterward our request has returned successfully, we store the #chatbox div's scrolled height into thenewscrollHeight variable.
We then compare both of the roll height variables using anif argument. IfnewscrollHeight is greater than theoldscrollHeight, nosotros utilize the animate effect to scroll the#chatbox div.
Continuously Updating the Chat Log
Now one question may ascend: how will we constantly update the new data existence sent back and along between users? Or to rephrase the question, how will we keep continuously sending requests to update the data?
setInterval (loadLog, 2500); //Reload file every 2500 ms or x ms if you wish to change the second parameter
The reply to our question lies in thesetInterval function. This function will run ourloadLog() function every 2.5 seconds, and theloadLog role will request the updated file and autoscroll the div.
Complete Code
The chat app might non work properly for you if the right code is not placed inside the right files and in the right order. To avoid any confusion, I am posting the whole code that will go into two separate files chosen alphabetize.php andpost.php.
Here is the code forindex.php:
<?php session_start(); if(isset($_GET['logout'])){ //Simple go out message $logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</bridge><br></div>"; file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX); session_destroy(); header("Location: alphabetize.php"); //Redirect the user } if(isset($_POST['enter'])){ if($_POST['name'] != ""){ $_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name'])); } else{ echo '<span course="mistake">Delight type in a proper noun</span>'; } } part loginForm(){ echo '<div id="loginform"> <p>Please enter your name to continue!</p> <form activeness="alphabetize.php" method="post"> <label for="proper name">Name —</label> <input type="text" proper name="proper noun" id="proper name" /> <input type="submit" name="enter" id="enter" value="Enter" /> </form> </div>'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Tuts+ Chat Application</title> <meta proper name="description" content="Tuts+ Chat Application" /> <link rel="stylesheet" href="style.css" /> </head> <torso> <?php if(!isset($_SESSION['name'])){ loginForm(); } else { ?> <div id="wrapper"> <div id="menu"> <p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p> <p class="logout"><a id="go out" href="#">Exit Chat</a></p> </div> <div id="chatbox"> <?php if(file_exists("log.html") && filesize("log.html") > 0){ $contents = file_get_contents("log.html"); echo $contents; } ?> </div> <form name="message" action=""> <input name="usermsg" type="text" id="usermsg" /> <input name="submitmsg" type="submit" id="submitmsg" value="Send" /> </form> </div> <script blazon="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/three.5.1/jquery.min.js"></script> <script blazon="text/javascript"> // jQuery Document $(document).ready(function () { $("#submitmsg").click(office () { var clientmsg = $("#usermsg").val(); $.postal service("post.php", { text: clientmsg }); $("#usermsg").val(""); render false; }); office loadLog() { var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Roll height before the request $.ajax({ url: "log.html", enshroud: simulated, success: function (html) { $("#chatbox").html(html); //Insert chat log into the #chatbox div //Auto-scroll var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height subsequently the request if(newscrollHeight > oldscrollHeight){ $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div } } }); } setInterval (loadLog, 2500); $("#exit").click(office () { var get out = confirm("Are you certain yous want to finish the session?"); if (get out == true) { window.location = "index.php?logout=true"; } }); }); </script> </body> </html> <?php } ?> Hither is the code forpost.php:
<?php session_start(); if(isset($_SESSION['name'])){ $text = $_POST['text']; $text_message = "<div class='msgln'><span class='chat-time'>".date("g:i A")."</span> <b grade='user-proper name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>"; file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX); } ?> The code that goes intomanner.css is already available in Footstep 2 of the tutorial.
If the code you have does not seem to exist working, make sure information technology matches the code provided here. Please note that all three files—index.php,post.php, and style.css—are located in the same directory.
Awesome Online Conversation PHP Scripts From CodeCanyon
Would yous rather download an online chat PHP script instead of creating one yourself? And so you'll want to check out these premium templates from CodeCanyon:
1. Alive Conversation Unlimited
Live Conversation Unlimited is a bestselling simple PHP chat box for a reason. It'southward very lightweight to go on your site load speeds down and tin can be installed on unlimited domains. The online chat PHP script also offers multi-lingual support through the WPML and Polylang plugins. You can also enable email notifications so you can be ready to chat with visitors.
2. TotalDesk: Helpdesk, Live Chat, Noesis Base and Ticket Arrangement
TotalDesk is a complete help desk solution for your business. Not but does it allow y'all make your ain chat box, but it also includes a ticket and notification arrangement, among other things. You can create a searchable cognition base for your site'southward visitors, so they tin solve common problems on their own. TotalDesk also integrates well with WooCommerce and Slack.
3. XeroChat: Facebook Chatbot, eCommerce and Social Media Direction Tool
If Facebook Messenger is function of your business concern's marketing strategy, you'll want to learn about XeroChat. Information technology'south designed with the messaging platform in mind and integrates well with it. This online chat PHP script lets you build responsive and interactive chatbots with ease. It's so fully featured that you tin even fix eCommerce stores with the included code. Add XeroChat to your online business strategies.
4. Chat Back up Board: PHP Chat Application
Finally, there's Support Lath, a PHP chat script that uses bogus intelligence to assist serve your customers. Communicate direct with your audience with ease thanks to its shine integration with other platforms. Y'all'll salvage time and increment date with this unproblematic PHP chat box.
Even More PHP Script Templates
PHP forms and scripts are a great fashion to round out your website. If y'all're looking for more templates that will save you time, bank check out some of these items from Envato:
Larn Near PHP Scripts From Envato Tuts+
Are you looking to learn fifty-fifty more about the PHP scripting language? Then Envato Tuts+ is the all-time place to beginning (and finish). Our talented instructors accept put together many PHP courses, tutorials, and guides that you can use to grow your knowledge base. Here are a few to get you started:
Finished
We are finished! I hope that you lot learned how a bones conversation system works, and if yous have any suggestions on anything, I'll happily welcome them. This chat organisation is a uncomplicated as you can get with a chat application. Y'all tin work off this and build multiple chat rooms, add an administrative dorsum finish, add emoticons, etc. The sky is the limit!
Likewise, if y'all need a professional person app or plugin for your next projection, y'all can take a look at one of the many chat scripts we have for sale on CodeCanyon.
Below are a few links you might desire to check out if you are thinking of expanding this chat awarding:
- Secure Your Forms With Form Keys: prevent XSS (cross-site scripting) and cross-site request forgery.
- Submit a Course Without Page Refresh Using jQuery: expand on our AJAX asking.
- How to Make AJAX Requests With Raw JavaScript: larn how requests work behind the scenes with raw JavaScript.
This mail service has been updated with contributions from Monty Shokeen and Nathan Umoh. Monty is a full-stack developer who also loves to write tutorials, and to learn about new JavaScript libraries. Nathan is a staff writer for Envato Tuts+.
stallardsuplusentep.blogspot.com
Source: https://code.tutsplus.com/tutorials/how-to-create-a-simple-web-based-chat-application--net-5931
0 Response to "Php How to Make the Whole Form Read Only"
Postar um comentário