PHP & Web Development Blogs

Search Results For: message
Showing 1 to 5 of 12 blog articles.
20 views · 1 months ago


For any development project to be successful, it’s important to choose the right technology and programming language. Most of the time, developers get confused about which programming language to choose.

Nowadays, PHP and Python have gained popularity among the programming languages for web development projects. However, choosing one between PHP vs Python is a difficult task. Recently, this has become a good topic for discussion.

Here, in this blog, we will compare the two popular programming languages: PHP vs Python. Let’s see which one turns out to be the best choice for web development.


What is Python?

Python is an open-source programming language developed in the year 1991 by Guido Van Rossum. It is one of the most commonly used languages due to its high level and easy-to-understand syntax.

According to the survey by Stack Overflow, Python is one of the most preferred programming languages. These Python app examples highlight its robustness and suitability for building scalable and innovative solutions across different platforms. Most of the companies and developers around the world are using Python web development.

What is PHP?

PHP or Hypertext Pre-processor, is an open-source server scripting language that is used for creating interactive and engaging web pages. This programming language comes with many features, libraries, plugins, and add-ons that increase community support and functionalities.

PHP language was developed by Rasmus Lerdorf in the year 1995. Earlier, PHP was named as Personal Home Page, which was later changed to Hypertext Pre-processor. An advantage of using PHP language is it supports all web browsers.

PHP is a practical, flexible, and fast programming language that can handle dynamic content on HTML sites, session tracking, and databases.

Features: PHP vs Python

PHP

* Open-source language, anyone can download and use it for free.
* PHP is easy to use and code than other programming languages.
* It is more efficient than other scripting languages like ASP and JSP.
* Offers access to log in by creating a summary of the recent user accesses.
* Provides database integration and supports distinct databases such as MySQL and Oracle.
* It has predefined error-reporting constants that generate warning or error messages.

Python

* Python is an easy-to-learn programming language.
* Provides an ideal structure and support for large applications.
* It can operate on different hardware platforms utilizing the same user interface.
* Python can be integrated with C, C++, and Java programming code.
* It’s easy to incorporate low-level modules in Python interpreter.
* Python offers high-level dynamic types of data and support for dynamic type checking.
* Its features support automatic garbage collection.
* It supports an interactive mode of testing and debugging.


Pros and Cons: PHP vs Python

Here, we will compare the pros and cons of PHP vs python for web development.

Pros of PHP

* Has a large ecosystem.
* Flexible and platform-independent.
* Several open-source PHP frameworks are available to use for free.
* Offers many pluggable frameworks, Open-source and object-oriented.
* Supports different database interfaces such as No SQL, PostgreSQL, and so on.
* It is supported by many operating systems and works cross-platform.
* Encourages top-notch debugging.
* Provides in-built SQL support.
* Offers support for database collection modules.
* It supports all operating systems like Windows, Linux, and UNIX.

Cons of PHP

* Delayed and wired performance.
* Not apt for content-based applications.
* Utilizes weak typing that can lead to false knowledge and data to users.
* Its core behavior can’t be changed.
* There’s no IOT alliance.
* Fewer security protocols and features.

Pros of Python

* Easy to learn and maintain.
* An open-source and uniformly unfolding language.
* Enables cross-platform code reusability.
* Object-oriented and versatile language to deploy.
* Offers WORA functionality.
* Helps in developing GUI apps.
* Has automatic garbage collection.
* It can be integrated easily with other languages, such as Java or C++.
* Provides libraries like Tenseorflow for math-intensive tasks.

Cons of Python

* Creates delays in web app testing.
* It utilizes an enormous amount of memory to help developers in easy development.
* Operates slower than other web development languages.
* Not of much use in mobile computing browsers and mobile app development.
* It has dynamic typing, which makes error detection more difficult.
* It’s too large for a simple and small app or website.
* Run time errors occurs due to duck typing.

When Should You Select PHP?

PHP is a commonly used server-side scripting language among developers. The best use cases in which you should select PHP:
* For developing blogs, websites, and web applications.
* Work effectively on the server side.
* Less investment.

When Should You Select Python?

* Python programming language has gained popularity in recent times. Below we have given some of the best cases in which you should choose Python.
* For operating in the areas of robotics and data science.
* When you want accurate and extensive data analytics.
* Developing websites using the Django framework.

Why opt for PHP?

Here, we will give you some reasons why you should opt for the PHP programming language.
* Open-source language, easy to download and use.
* Easy to learn and operates effectively on the server side.
* This scripting language can run on distinct platforms such as Windows, Mac OS X, Linux, and UNIX.
* It’s compatible with every server, like IIS, Apaches, and so on.
* Supports a broad range of databases.

Why opt for Python?

As you know, there are many advantages and disadvantages of using Python. Here, we will tell you why you should choose Python for web development.
* Python language is easy to use and maintain.
* Python syntax is quick to understand and debug as well. Therefore, its source code is easier to maintain.
* It has a garbage collection feature and memory addresses accordingly.
* It comes with many pre-built libraries.
* Python supports GUI apps such as Django, Tkinter, WXPython, etc.
* It’s a versatile and portable language. You can run Python on different types of operating systems or platforms.
* Python comes with a database-friendly interface that can store a colossal amount of data for commercial DBMS systems.
* It has an interactive shell that helps in unit testing before deploying a product.

Comparison: PHP vs Python

Above, we have given the features and pros & cons of PHP vs Python. In this section, we will give you a comparison between PHP vs Python in accordance with different parameters.

Parameters
Python
PHP
Release
    .
    .
Learning curve
Easier
Steep
Language type
Specialized for web development
General purpose programming language
Syntax
Clear & concise
Complex
Security
High
Medium
Readability
High
Low
Database connectivity
Faster
Slower
Debugging
Fast
Slower
Performance
Lesser support
Faster
Supported Frameworks
Flask, Django, Web2Py
Laravel, Zend, Codelgniter
GitHub Stars
    . 9k
    . 5k
TIOBE Rating
    . st position
    . th position
Forks
    . 5 k
    . 9k
Major Users
Instagram, YouTube, Quora, Reddit
Facebook, Yahoo, Flickr, Tumblr


This comprehensive comparison between PHP vs Python can help you to choose the right language for web development. Now, we will compare some other elements that would give you a clear picture of both PHP vs Python.

1. Ease of Learning

Python is an easier language to learn compared to PHP. If you are a beginner, then Python is a good choice as you can learn it quickly. Python programs are shorter as well as easy to write in comparison to other languages.

PHP programming language is made for creating sophisticated web apps. It’s not a general-purpose language, and it takes time to learn it.

2. Ease of Use

Python is an open-source programming language that is versatile and portable. Python’s syntax is simple, and coding is easy to learn compared to PHP. But PHP is not just an ordinary programming language it’s used for creating dynamic web pages with HTML. This makes PHP more difficult to use than Python.

3. Community Support

Both PHP and Python provide good community support. PHP has been in the market for a long time and has a large community of developers. Therefore, you can immediately get support if you opt for PHP.

However, there are even many Python developers who constantly develop python apps. So, the community support in Python is also good. Consequently, we can’t say whether PHP or Python is better at providing community support.

4. Flexibility

Nowadays, web apps backed by Machine Learning are in high demand. Also, ML is a significant part of Python. Python provides many machine-learning libraries, such as Tensorflow, Theano, Pandas, and Scikit-learn. Additionally, these libraries are rapid, unique, & robust and work effectively with a web framework.

Nonetheless, Python programming language can be used in many other fields apart from web development. But when it comes to PHP, it’s best for web development. Therefore, we can say Python is a better choice here.

Our skilled developers delivers the most promising web development firms to make dynamic websites for your business.

5. Speed to Market

Python provides a comprehensive set of modules and third-party libraries to help developers finish the project faster. One of the popular web frameworks written in Python is Django. It utilizes the MVC pattern to allow developers to create apps fast using a significant division of concerns and reusability.

PHP also has a vast set of tools, frameworks, and libraries. Laravel is a popular PHP framework that allows the MVC pattern. Additionally, it comes with many helpful functionalities for web development, like routing, templating, authentication, and so on.

6. Web Frameworks

You get robust and well-designed web development frameworks both in PHP and Python. Most of the big businesses utilize web frameworks that PHP provides. For example, Laravel and Symfony are mature web frameworks, and a huge community supports them. So, we can say PHP makes web development easy.

Python also has many exceptional frameworks that are highly scalable, easy to use, fast and secure. It’s two most popular web frameworks are Flask and Django. If you want a shorter development period, then you can choose Django over PHP-based frameworks.

7. Library Management

Python uses Pip to handle and deal with packages. Pip ensures that Python app development is easy, rapid, and meets development needs. Python has powerful library management compared to PHP. It has a wide range of packages and tools that assist and make web app development easier. So, in terms of library management, Python clearly wins it.

8. Security

When it comes to security, most businesses prefer using Python. For instance, Django offers many pre-built security features that aid in safeguarding the apps from distinct security breaches & threats.

Apart from that, many government organizations rely on Python as their secret hacking tool. Most of the security problems are addressed by its large community support. However, PHP is less strong than Python in aspects of security.

9. Environment Management

In terms of handling environments, Python is the best programming language. It has a Virtualenv system that aids in installing different versions of the language and switching between them immediately.
PHP has no comparison with Python when it comes to handling environments. There’s an analog of PHP, VirtPHP, but it’s archived and not maintained. Therefore, most of the developers opt for Python.

10. Debugging

Python has an in-built debugger called Python Debugger or PDB. It utilizes many debugging strategies. PDB enables dynamic typing and lets developers work effortlessly without stating things at the start of a program.
PHP also comes with an XDebug package for handling bugs and error-checking the codes. But PHP development is quite slow in identifying and removing bugs. Therefore, it often experiences security issues.


The Bottom Line PHP vs Python: Which One You Choose for Web Development?


From the blog, you must have inferred that both PHP and Python are good for web development. However, there are many aspects in which Python wins over PHP. But this doesn’t mean that you only have to opt for Python. The selection of programming language majorly depends on the complexity and needs of the project.

Sphinx Solutions is a leading and trusted web app development company. Our team of web developers can help you create the best web apps for your business based on your specifications. Schedule a call with our experts to get an estimation for your web app development project, or email us at [email protected].

PHP vs Python: FAQs

1. Why choose Python over PHP?
Python is chosen over PHP for web app development due to many reasons, such as ease to use, simple syntax, flexibility, security, high performance, etc.
2. Which programming language is secure: PHP vs Python?
Python is a preferred programming language when it comes to security as it has many security features compared to PHP.
3. Why is Python used mostly?
Python is a general-purpose programming language and is utilized in web development, mobile app development, AI, ML, game development, big data, and so on.
Browse More Related Article
    . React and Nodejs: The Best Combination for Web Application Development
    . A Timeless Guide on How to Expand Your Native App to a Web App
6064 views · 3 years ago
Web Sockets in PHP

In his talk Websockets in PHP, John Fransler walks us through the use of WebSockets in PHP.

While discussing bi-directional real-time application development, John notes that PHP is often not invited to the table due to its lack of native support. Of all the possible attempts to bring in PHP on this stage of real-time development, Ratchet, a PHP WebSocket library, comes closest. "Ratchet is a loosely coupled PHP library providing developers with tools to create real-time, bi-directional applications between clients and servers over WebSockets."* Ahem!

Today's dynamic world


In today's dynamic content world of the internet, it is required to serve real-time bi-directional messages between clients and servers. WebSockets are simple, full-duplex, and persistent. They work over Http and are a standard today.

WebSockets have compatibility with 96.5% of clients globally

There's a very high chance your client has the necessary plumbing to access your content via WebSockets. WebSockets gives the ability to have real-time data on to your clients without the need for polling.

To understand WebSockets, John takes an example of a Javascript client and Ratchet Server. Javascript has everything built in to allow access to a socket. For example, you can use the send method on a WebSocket variable to send a message to the server, or if you want to respond to a message from the server, you use the OnConnection method.

While on the Server, John uses Ratchet, which is built on React PHP. A server script is then configured and set up to run and listen on a port for incoming HTTP requests. For messages, JSON is used, and to find public methods, a router is set up. He then goes on to instantiate the server-side script in Ratchet.

There are four functions of a Ratchets message component interface that are used in this example:

OnOpen gets called when a new connection is made.

OnClose gets called when a client quits. It's essential to keep an eye on memory management, and essential to keep tidying up as you move through the code.

OnError gets called when there is an exception faced by the user.

OnMessage gives the text of the JSON message, which is being exchanged with the client.

For Initialization, Jason continues to walk through the example. He shows how one can loop through the clients, both inside the server and outside the server. Outside the server, it’s a feature of React PHP. On database access, and with traditional standard synchronous MySQL in PHP, what usually happens is that it forces the code to wait for the query to return a result and do nothing — Fortunately, with Asynchronous MySQLi, that is not the case.

John gets into the details explaining Variables, References & Pointers. He also gives a demo where a central site has updated information on the Bitcoin and ether prices. A client terminal reflects the last values. Now the client doesn't have to poll the server for new values. When there is a change in the Bitcoin or ether values, the server pushes down the client's update. No polling helps with a lot of overheads and gets closer to real-time.

Using Supervisord


For Long-running applications - Jason recommends running a supervisord, use proxy to expose the port, and add a site certificate. Supervisord keeps an eye out for the server running the service; it can be used to restart the service and log any service issues. Recommended proxies are AWS load balancer, Nginx, and HA Proxy. For scalability, use multiple smaller WebSocket servers and a smaller number of clients per server used and load balancing. If one has to support a chat feature to allow clients to talk to each other in near real-time, it is recommended to use Redis. The Redis server proxies the messages between the server nodes.

The talk concludes with John summarizing best practices on error handling and takes QnA on various aspects of WebSockets such as handling load balancers and asynchronous calls to MSQLi.

The presentation for this video, along with the code, is hosted at John Curt's GitHub. More info about John's current areas of interest can be found on John's Blog.

Watch the video now


Related videos
8280 views · 3 years ago


Recently I was faced with a task to post data from a .csv file to an external REST API. I’m just going to log in to this article about what I did to get the job done.

Let’s start by creating a template for uploading the file. For this article’s sake, lets make the changes in the dashboard.blade.php file.


<form method="post" enctype="multipart/form-data"> @csrf <div class="custom-file"> <input type="file" accept=".csv" name="excel" class="custom-file-input" id="customFile" /> <label class="custom-file-label" for="customFile">Choose file</label > </div> <div> <button type="submit" class="btn btn-primary btn-sm" style="margin-top: 10px" >Submit> </div>

</form>

Note : Don’t forget to add enctype=”multipart/form-data”!



Once the user has submitted the file, we need a new router to process the file and send its content to the REST API. Let’s start by creating a Controller.


php artisan make:controller UploadController


Now in the web.php file,


Route::post('/upload', [UploadController::class, 'upload'])->name('upload')->middleware('auth');


In the UploadController.php , create a function named upload. We will be writing all the code inside this function. Also, we need an action for the form.


<form method="post" action="{{route('upload')}}" enctype="multipart/form-data">


Now inside the upload function, we need to get the submitted file and parse its contents.

Get the submitted file,


$file = $request->file('excel');


Parse the submitted file,


if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { ..... }

}


We will be using a dummy REST API to create users — https://reqres.in/api/users. This is the request body required to create a user.


{ "name": "test", "job": "test"

}


Keeping this in mind, we will create a sample .csv template to be submitted. The fields need to be two, namely Name and Job.



We need to send the values from this file as the request body to the API. So let’s add the code to loop through the content of this file.


if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { Http::post('https://reqres.in/api/users', [ 'name' => $data[0], 'job' => $data[1], ]); }

}


This will create each student for each row of the file. But we don’t need to send the data of the first row of the file.

Full code:


public function upload(Request $request){ $file = $request->file('excel'); if($file){ $row = 1; $array = []; if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { if($row > 1){ Http::post('https://reqres.in/api/users', [ 'name' => $data[0], 'job' => $data[1], ]); array_push($array,$data[0]); } $request->session()->flash('status', 'Users '.implode($array,", ").' created successfully!'); $row++; } } }else{ $request->session()->flash('error', 'Please choose a file to submit.'); } return view('dashboard');

}


This will post the data starting from the second row of the file, display a success message once the users are created, and an error message if the submit button is clicked without choosing a file.

Full template:


<div class="container max-w-7xl mx-auto sm:px-6 lg:px-8" style="width: 50%"> @if (session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endif @if (session('error')) <div class="alert alert-error"> {{ session('error') }} </div> @endif <form action="{{route('upload')}}" method="post" enctype="multipart/form-data"> @csrf <div class="custom-file"> <input type="file" accept=".csv" name="excel" class="custom-file-input" id="customFile" /> <label class="custom-file-label" for="customFile">Choose file</label> </div> <div> <button type="submit" class="btn btn-primary btn-sm" style="margin-top: 10px">Submit</button> </div> </form>

</div>




That’s it, thanks for reading :)
4400 views · 3 years ago


People that visit your website face an invisible threat each time they log on. Small businesses are especially vulnerable to digital data breaches, and that can change the way your customers feel about you. But, although you cannot stop hackers from trying, there are things you can do as a business owner to make your website a safer experience for everyone. Keep reading for tips.

Mature digitally.


You may be ahead of the times when it comes to products and services, but, chances are, your website hasn't fully kept up. It's time to learn all you can about the internet and digital security. If you are already somewhat tech savvy, a PHP Security Course from Nomad PHP can help you better understand everything from cryptography to website error messages.

Adapting to today's digital environment means transforming your website to quickly and easily identify threats via machine learning and network monitoring. And, as Upwork explains, digital maturity not only keeps your website safe, but adopting this mindset can also increase your efficiency and accuracy by reducing human errors.

Understand the threats.


It is not enough to simply keep up with your website, you also have to understand the types of threats that are out there. You're likely familiar with ransomware and phishing, but, it's also a good idea to know how a website can get hacked. Your site's content management system and vulnerabilities within your operating system are all weak points that hackers can easily identify.

Insist on security measures.


When customers log into your website, they input their credentials. Each time they do so, you can best protect their information by keeping your systems up to date. You'll also want to ensure that your site is hosted on a secure service and that you have an SSL certificate installed.

If you are not already, have your IT department or managed IT services perform regular website security checks. PhoenixNAP, an IT services provider, notes that those websites working via WordPress should also be safely outfitted with the most recent security plug-ins.

Eliminate spam.


If your website allows for comments that are not manually approved, anyone on the internet can post. This leaves it open for hackers and other unscrupulous individuals to comment with spam and malicious links that your customers may inadvertently click on. While many of these simply exist as a way for the commenter to drive traffic to another website, others are designed to draw your readers' attention, gain their trust, and access their personal information.

Prioritize passwords.


Your customers' passwords are the keys by which they open the door to your website. Unfortunately, many people do not treat them with as much care as they do the keys they use in the non-digital world.

It's true, passwords can be a pain, but you are not doing yourself or your customers any favors by allowing simple one-word passcodes to access your site. Instead, design your site to require a strong password. How-To Geek asserts that this will have a minimum of 12 characters and include a combination of upper and lower case letters, symbols, and numbers.

While you will likely rely on your IT experts to secure your website, the truth is that it is ultimately up to you to ensure this is done. So even if you are not a digital mastermind, knowing all you can about web security can help you be a better business owner. Your customers will be safer, and a secure website is just one way to strengthen your business's online presence and keep up with today's -- and tomorrow's -- technology.
24598 views · 4 years ago
PHP CHAT WITH SOCKETS

Hey Friends,

I am sharing a very interesting blog on how to create a chat system in php without using ajax. As we all know ajax based chat system in php is not a good solution
because itincreases the server load and redundant xhr calls on our server.

Instead, I am going to use sockets for incoming messages from and send messages to another user. So lets try them out using the following steps:


Step 1: Cross check in php.ini that sockets extension is enabled


;extension=sockets
extension=sockets


Step 2: Create server.php file


This file will handle the incoming and outgoing messages on sockets, Add following variables in top of the file:

$host = 'localhost';
$port = '9000';
$null = NULL; 


Step 3: After it add helper methods


The following code for handshake with new incoming connections and encrypt and decrypt messages incoming and outgoing over sockets:

function send_message($msg)
{
global $clients;
foreach($clients as $changed_socket)
{
@socket_write($changed_socket,$msg,strlen($msg));
}
return true;
}
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}
elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}
else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
function mask($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);

if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
function perform_handshaking($receved_header,$client_conn, $host, $port)
{
$headers = array();
$lines = preg_split("/

/", $receved_header);
foreach($lines as $line)
{
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
{
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake

" .
"Upgrade: websocket

" .
"Connection: Upgrade

" .
"WebSocket-Origin: $host

" .
"WebSocket-Location: ws://$host:$port/php-ws/chat-daemon.php

".
"Sec-WebSocket-Accept:$secAccept



";
socket_write($client_conn,$upgrade,strlen($upgrade));
}


Step 4: Now add following code to create bind and listen tcp/ip sockets:


$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, 0, $port);
socket_listen($socket);
$clients = array($socket);


Ok now a endless loop that will use for handeling incominga nd send messages:

while (true) {
$changed = $clients;
socket_select($changed, $null, $null, 0, 10);

if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); $clients[] = $socket_new;
$header = socket_read($socket_new, 1024); perform_handshaking($header, $socket_new, $host, $port);
socket_getpeername($socket_new, $ip); $response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); send_message($response);
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}

foreach ($changed as $changed_socket) {

while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
{
$received_text = unmask($buf); $tst_msg = json_decode($received_text, true); $user_name = $tst_msg['name']; $user_message = $tst_msg['message']; $user_color = $tst_msg['color'];
$response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color)));
send_message($response_text); break 2; }

$buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) { $found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);

$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' disconnected')));
send_message($response);
}
}
}
socket_close($socket);


So you are ready with server side socket program, Now its time to move on front side where we will implement w3c provided client side Web Socket Apis,

Step 5: create a file named index.php for frontend usage with following initial code


$host = 'localhost';
$port = '9000';
$subfolder = "php_ws/";
$colors = array('#007AFF','#FF7000','#FF7000','#15E25F','#CFC700','#CFC700','#CF1100','#CF00BE','#F00');
$color_pick = array_rand($colors);
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="chat-wrapper">
<div id="message-box"></div>
<div class="user-panel">
<input type="text" name="name" id="name" placeholder="Your Name" maxlength="15" />
<input type="text" name="message" id="message" placeholder="Type your message here..." maxlength="100" />
<button id="send-message">Send</button>
</div>
</div>
</body>
</html>


Now add some basic styling in the head section using following code:

<style type="text/css">
.chat-wrapper {
font: bold 11px/normal 'lucida grande', tahoma, verdana, arial, sans-serif;
background: #00a6bb;
padding: 20px;
margin: 20px auto;
box-shadow: 2px 2px 2px 0px #00000017;
max-width:700px;
min-width:500px;
}
#message-box {
width: 97%;
display: inline-block;
height: 300px;
background: #fff;
box-shadow: inset 0px 0px 2px #00000017;
overflow: auto;
padding: 10px;
}
.user-panel{
margin-top: 10px;
}
input[type=text]{
border: none;
padding: 5px 5px;
box-shadow: 2px 2px 2px #0000001c;
}
input[type=text]#name{
width:20%;
}
input[type=text]#message{
width:60%;
}
button#send-message {
border: none;
padding: 5px 15px;
background: #11e0fb;
box-shadow: 2px 2px 2px #0000001c;
}
</style>


Ok Style is all set now need to add a jquery script and create web socket object and handle all events on it as following code need to add before closing of bosy tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var msgBox = $('#message-box');
var wsUri = "ws://".$host.":".$port."/php-ws/server.php";
websocket = new WebSocket(wsUri);

websocket.onopen = function(ev) { msgBox.append('<div class="system_msg" style="color:#bbbbbb">Welcome to my "Chat box"!</div>'); }
websocket.onmessage = function(ev) {
var response = JSON.parse(ev.data);
var res_type = response.type; var user_message = response.message; var user_name = response.name; var user_color = response.color; switch(res_type){
case 'usermsg':
msgBox.append('<div><span class="user_name" style="color:' + user_color + '">' + user_name + '</span> : <span class="user_message">' + user_message + '</span></div>');
break;
case 'system':
msgBox.append('<div style="color:#bbbbbb">' + user_message + '</div>');
break;
}
msgBox[0].scrollTop = msgBox[0].scrollHeight; };

websocket.onerror = function(ev){ msgBox.append('<div class="system_error">Error Occurred - ' + ev.data + '</div>'); };
websocket.onclose = function(ev){ msgBox.append('<div class="system_msg">Connection Closed</div>'); };
$('#send-message').click(function(){
send_message();
});

$( "#message" ).on( "keydown", function( event ) {
if(event.which==13){
send_message();
}
});

function send_message(){
var message_input = $('#message'); var name_input = $('#name');
if(message_input.val() == ""){ alert("Enter your Name please!");
return;
}
if(message_input.val() == ""){ alert("Enter Some message Please!");
return;
}
var msg = {
message: message_input.val(),
name: name_input.val(),
color : '<?php echo $colors[$color_pick]; ?>'
};
websocket.send(JSON.stringify(msg));
message_input.val(''); }
</script>


Ok All set, Now need to run the server.php file using following php-cli utility,make sure you have php cli utility installed in your system:

php -q c:\xampp\htdocs\php-ws\server.php


Now you may access the front index.php file via the browser url like following and see a chatbox and connection status, you may use the same url or different browser to check the chat system is working or not.

SPONSORS

PHP Tutorials and Videos