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

How to Implement Live Chat in PHP Tutorial TutsPlus Chat App How to Implement Live Chat in PHP Tutorial TutsPlus Chat App How to Implement Live Chat in PHP Tutorial TutsPlus Chat App

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.

  • 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#wrapper div. Nosotros volition have three main blocks: a simple menu, our chatbox, and our message input, each with its corresponding div and id.
    • The#menu div 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#chatbox div will comprise our chatlog. We will load our log from an external file using jQuery'due south ajax request.
    • The terminal detail in our#wrapper div volition exist our form, which will include a text input for the user message and a submit button.
  • 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.

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.

How to Implement Live Chat in PHP Tutorial TutsPlus Chat App Interface How to Implement Live Chat in PHP Tutorial TutsPlus Chat App Interface How to Implement Live Chat in PHP Tutorial TutsPlus Chat App Interface

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.

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.

How to Implement Live Chat in PHP Tutorial TutsPlus Chat App Login Screen How to Implement Live Chat in PHP Tutorial TutsPlus Chat App Login Screen How to Implement Live Chat in PHP Tutorial TutsPlus Chat App Login Screen

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.

How to Implement Live Chat in PHP Tutorial Tutsplus Chat App Welcome How to Implement Live Chat in PHP Tutorial Tutsplus Chat App Welcome How to Implement Live Chat in PHP Tutorial Tutsplus Chat App Welcome

In order to allow the user to log out and end the session, we will jump alee of ourselves and briefly use jQuery.

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:

How to Create Online Chat Application in PHP Tutorial Tutsplus Chat App Logout Prompt How to Create Online Chat Application in PHP Tutorial Tutsplus Chat App Logout Prompt How to Create Online Chat Application in PHP Tutorial Tutsplus Chat App Logout Prompt

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.

  1. Before we exercise annihilation, nosotros must grab the user'southward input, or what the user has typed into the #submitmsg input. This can be achieved with theval() office, which gets the value set in a course field. We at present shop this value in the clientmsg variable.
  2. 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 theclientmsg variable.
  3. Lastly, we clear the#usermsg input 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.

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.

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.

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.

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?

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.

How to Create Online Chat Application in PHP Tutorial Tutsplus Chat App Network How to Create Online Chat Application in PHP Tutorial Tutsplus Chat App Network How to Create Online Chat Application in PHP Tutorial Tutsplus Chat App Network

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:

Hither is the code forpost.php:

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.

LiveChat Unlimited Online Chat PHP LiveChat Unlimited Online Chat PHP LiveChat Unlimited Online Chat PHP

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.

TotalDesk Chat for Website PHP TotalDesk Chat for Website PHP TotalDesk Chat for Website PHP

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.

XeroChat Simple PHP Chat Box XeroChat Simple PHP Chat Box XeroChat Simple PHP Chat Box

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.

Support Board Online Chat PHP Support Board Online Chat PHP Support Board Online Chat PHP

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.
How to Create Online Chat Application in PHP Tutorial Tutsplus Chat App How to Create Online Chat Application in PHP Tutorial Tutsplus Chat App How to Create Online Chat Application in PHP Tutorial Tutsplus Chat App

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel