PHP & Web Development Blogs

Search Results For: class
Showing 6 to 10 of 27 blog articles.
8336 views · 3 years ago
Laravel Eloquent Relationship Part 2

As you all know, Laravel Eloquent Relationships are powerful and easy methods introduced by Laravel for helping developers to reduce the complexity when connecting with multiple tables. While connecting with multiple tables, this method is very easy for developers for creating the application

Here you can see the next three methods of the eloquent relationships:
   
. Has Many Through Relationship
    . One to Many Polymorphic
    . Many to many Polymorphic

HAS MANY THROUGH ELOQUENT RELATIONSHIP

Has many through is a little bit complicated while understanding. I will provide a shortcut method to provide access data of another mode relationship. We will create a user table, post table, and country table and they will be interconnected with each other.

Here we will see Many through relationship will use hasManyThrough() for the relation


Create Migrations


Users table

 Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->integer('country_id')->unsigned();

$table->rememberToken();

$table->timestamps();

$table->foreign('country_id')->references('id')->on('countries')

->onDelete('cascade');

});


Posts table

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->integer('user_id')->unsigned();

$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

});


Countries table

Schema::create('countries', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->timestamps();

});


Create Models


Country Model

<?php


namespace App;

use Illuminate\Database\Eloquent\Model;


class Country extends Model

{

public function posts(){

return $this->hasManyThrough(

Post::class,

User::class,

'country_id',
'user_id',
'id',
'id'
);

}

}


Now we can retrieve records by

$country = Country::find(1); 

dd($country->posts);


ONE TO MANY POLYMORPHIC RELATIONSHIP

One to many polymorphic relationships used one model belongs to another model on a single file. For example, we will have tweets and blogs, both having the comment system. So we need to add the comments. Then we can manage both in a single table


Here we will use sync with a pivot table, create records, get all data, delete, update, and everything related to one too many relationships.

Now I will show one too many polymorphic will use morphMany() and morphTo() for relation.


Create Migrations

Posts table

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Videos Table

Schema::create('videos', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Comments Table

Schema::create('comments', function (Blueprint $table) {

$table->increments('id');

$table->string("body");

$table->integer('commentable_id');

$table->string("commentable_type");

$table->timestamps();

});


Create Models

Post Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Post extends Model

{



public function comments(){

return $this->morphMany(Comment::class, 'commentable');

}

}

Video Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Video extends Model{



public function comments(){

return $this->morphMany(Comment::class, 'commentable');

}

}

Comment Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model{



public function commentable(){

return $this->morphTo();

}

}


Create Records


$post = Post::find(1); 

$comment = new Comment;

$comment->body = "Hi Harikrishnan";

$post->comments()->save($comment);


$video = Video::find(1);

$comment = new Comment;

$comment->body = "Hi Harikrishnan";

$video->comments()->save($comment);



Now we can retrieve records


$post = Post::find(1); 

dd($post->comments);



$video = Video::find(1);

dd($video->comments);



MANY TO MANY POLYMORPHIC RELATIONSHIPS

Many to many polymorphic is also a little bit complicated like above. If we have a tweet, video and tag table, we need to connect each table like every tweet and video will have multiple persons to tag. And for each and every tag there will be multiple tweet or videos.

Here we can understand the creating of many to many polymorphic relationships, with a foreign key schema of one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and etc..


Here morphToMany() and morphedByMany() will be used for many to many polymorphic relationships

Creating Migrations

Posts Table

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Videos Table

Schema::create('videos', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Tags table

Schema::create('tags', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

Taggables table

Schema::create('taggables', function (Blueprint $table) {

$table->integer("tag_id");

$table->integer("taggable_id");

$table->string("taggable_type");

});


Creating ModelsPost Model


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{



public function tags(){

return $this->morphToMany(Tag::class, 'taggable');

}

}


Video Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Video extends Model

{



public function tags(){

return $this->morphToMany(Tag::class, 'taggable');

}

}

Tag Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model

{



public function posts(){

return $this->morphedByMany(Post::class, 'taggable');

}





public function videos(){

return $this->morphedByMany(Video::class, 'taggable');

}

}

Creating Records

$post = Post::find(1); 
$tag = new Tag;
$tag->name = "Hi Harikrishnan";
$post->tags()->save($tag);


$video = Video::find(1);
$tag = new Tag;
$tag->name = "Vishnu";
$video->tags()->save($tag);


$post = Post::find(1);
$tag1 = new Tag;
$tag1->name = "Kerala Blasters";
$tag2 = new Tag;
$tag2->name = "Manajapadda";
$post->tags()->saveMany([$tag1, $tag2]);


$video = Video::find(1);
$tag1 = new Tag;
$tag1->name = "Kerala Blasters";
$tag2 = new Tag;
$tag2->name = "Manajappada";
$video->tags()->saveMany([$tag1, $tag2]);


$post = Post::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->attach([$tag1->id, $tag2->id]);


$video = Video::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$video->tags()->attach([$tag1->id, $tag2->id]);


$post = Post::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->sync([$tag1->id, $tag2->id]);


$video = Video::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$video->tags()->sync([$tag1->id, $tag2->id]);



Now we can retrieve records

$post = Post::find(1); 
dd($post->tags);


$video = Video::find(1);
dd($video->tags)


$tag = Tag::find(1);
dd($tag->posts);


$tag = Tag::find(1);
dd($tag->videos);



Hence we completed all the relationships. In the above blog how has many through relationship, one to many polymorphic relationships and many to many polymorphic are working. This feature is introduced from Laravel 5.0 onwards and till the current version. Without the model, we can’t able to do this relationship. If we are using an eloquent relationship it will be very useful while developing an application.
8732 views · 3 years ago


Welcome back! If you’re new to this series have a look at Part 1 here


Today’s focus is on templating, the aesthetic that will make or break your web application.

Having a clean design with well defined CSS that’s responsive and user friendly goes a long way.

Developers often stick to their lane but delving into templating will bode in your favor, you can indeed
create a functional and launch-worthy application all on your own!

Let’s jump into it!

Structured structure


Everything you tackle should be found with ease down the line. Therefore careful planning is fundamental to the success and sustainability of your project. You’ll also find that clearly defining your work lends itself to more productivity overall as you spend less that explaining your work during a handover / looking for a specific piece of code or resource. You’ll probably end up spending more time on actual work.
Finding your own unique pattern with file structure and CSS identifiers will also work in your favor as something unique to your process will most likely be easier to remember and form a tactile relationship with.

Our project’s current structure looks like this:



>If you need to backtrack, Part 1 is a great place to start!

In part 1, we created our index.php which displays info from our database.

Let’s take this a step further and create a header and a footer for our index.php

Create a file called header.php and save this to your includes folder.

Next, create a file called footer.php and save this to your includes folder.

Your file structure should now look like this.



A header above all the rest


The header file will be a file we reuse throughout your web application. This file will contain important information that’s vital to the functionality and aesthetic of your website.
The type of info you’ll expect to see in a header.php file:
Script includes
Such as JQuery and important libraries
CSS includes
CSS files loaded from internal or external sources
Meta information
Contains important information that’s readable by search engines.
The basic structure of the beginning of your app, including your menu, and your logo.
For now, how header is going to have a basic layout.

Let’s get our HTML on!

<html>
<head>
<title>My Awesome CMS – Page Title</title>
</head>
<body>


A footer that sets the bar

Create a file called footer.php and save it to your includes folder (yourcms/includes/footer.php).

Add this code to your new file.

</body>
</html>


Next, let’s focus on the gravy… The CSS


CSS, when written beautifully, can truly set you apart.

You can tell your web application to load various styles to specific elements by defining unique identifiers.
Styles that are only used once are denoted with a # (a CSS “ID”) whereas styles that are reused multiple times are denoted with a . (a CSS “class”)

The best way to delve into the realm of CSS is to learn by experience.

Let’s create!


First, we need to create and load our CSS file. Remember our nifty new pal header.php? This created a convenient way to load our CSS file!

Add the following code to your header.php just above the </head> tag.

<link href=”../assets/css/style.css” type=”text/css” rel=”stylesheet”/> 


The ../ in the link to our stylesheet means we have to leave the current directory (the directory that header.php is in) and look for the assets/css/ directories.

Go ahead and create the css folder under your assets folder.

Next we’re going to create some simple CSS to test things out.

It’s time to add some style!


We are going to create two divs.
A div is a divider / section in HTML.
Add this to your index.php (located in your CMS’ root folder) above the <?php tag.

<div id="myfirstid"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>


Then, create a CSS file

Add this:

#myfirstid{
Background:lightblue;
Font-family:Arial;
Font-size:44px;
Font-weight: Bold;
}
.myfirstclass{
Font-size:15px;
Color: darkblue;
}


Save your newly created CSS to assets/css/ as style.css.

Pulling it all together, let’s see what we can do!


Let’s apply what we just learned to our index.php. But first, we should add our header.php and footer.php files.

Including everyone


Add this to the top of your index.php file:

include(‘includes/header.php’);


Remove the <divs> we used for practice earlier, we have something better in store!

Add this to the bottom of your index.php:

include(‘includes/footer.php’);


Next, let’s modify our code so we can add some style to the data we retrieve from our database.

Modify the following line:
foreach($getmydata as $mydata){ echo "Title: "; echo $mydata['title']; echo "<br/>"; echo "Content: "; echo $mydata['content']; echo "<br/>"; echo "Author: "; echo $mydata['author']; echo "<br/>"; echo "<br/>";


as follows:
?>

<div id=”myfirstid”>
<?php
foreach($getmydata as $mydata){
echo "<div class=”myfirstclass”>Title: ";
echo $mydata['title'];
echo "<br/>";
echo "Content: ";
echo $mydata['content'];
echo "<br/>";
echo "Author: ";
echo $mydata['author'];
echo "</div><br/><br/>";
}?>
</div>
<?php


Your full index.php should now look like this:

<?php
include('includes/header.php');
include('includes/conn.php');

if ($letsconnect -> connect_errno) { echo "Error " . $letsconnect -> connect_error;

}else{

$getmydata=$letsconnect -> query("SELECT * FROM content");

?>
<div id="myfirstid">
<?php
foreach($getmydata as $mydata){
echo "<div class=”myfirstclass”>Title: ";
echo $mydata['title'];
echo "<br/>";
echo "Content: ";
echo $mydata['content'];
echo "<br/>";
echo "Author: ";
echo $mydata['author'];
echo "</div><br/><br/>";
}
?>
</div>
<?php
}

$letsconnect -> close();
include('includes/footer.php');
?>


Go ahead, test it out!

There’s a lot to unpack and I will break things down a little more during our next tutorial!

Challenge


Study the final index.php and try to form a few theories about why closing a php tag is necessary before adding raw html.

Next Up: #CodeWithMe Part 4: Building A Good Base

10974 views · 3 years ago


It took me quite some time to settle on my first blog post in this series and I found myself thinking about the most requested functionality in my career – The good ‘ol Custom CMS – typically geared towards clients that want a straight forward, secure solution that can be expanded upon in a modular format and that’s their IP.

This will be our starting point. A blank slate to build something epic with clean code and even cleaner design. And in the spirit of building from scratch, I will refrain from using classes or a framework. The main reasoning behind this is to truly get everyone acquainted with and excited about PHP development.

Join me as I transform rudimentary code into something extraordinary that can be morphed into just about any Content, PHP, and MySQL driven project. So without further ado, let’s jump into it!

The bare necessities


If you’re just getting started with development, there’s a nifty bite sized server called UniformServer that will be your best friend throughout your coding career. PHPMyAdmin (an awesome visual db management tool) comes built in so if you’re looking for a work right out of the box solution, this is it.

Alternatively, you can opt for XAMPP or use an alternative server of your choice.

Now here’s where the exciting stuff begins, mapping things out.


I don’t see this done/encouraged often enough. Feel free to grab a piece of paper to logically map out your steps or produce a rough draft of where you’d like this project to go.

In this tutorial, I would like to achieve the following:



DB, DB, Set up your DB.


This requires a bit of planning but let’s start of with the basic structure we need to see this through.

We are going to need a user table and a content table and are a few ways to tackle this.

If you’re using the PHPMyAdmin tool you can create your database, add user permissions (Click on Permissions after creating your database), and create a table with ease.



If you’re like me and prefer to look at good ‘ol SQL then writing an SQL statement is the preferred approach.


CREATE TABLE <code>mydbname</code>.<code>content</code> ( <code>ID</code> INT(11) NOT NULL AUTO_INCREMENT , <code>title</code> VARCHAR(100) NOT NULL , <code>content</code> LONGTEXT NOT NULL , <code>author</code> VARCHAR(50) NOT NULL , PRIMARY KEY (<code>ID</code>)) ENGINE = MyISAM COMMENT = 'content table';


Understanding the SQL statement

In a nutshell we are creating a table with important fields. Namely:

####

ID | Title | Content | Author

#######

The ID field is our unique identifier.Now we can move on to the file structure.

Everything has a place in the file structure game


You can use a structure that speaks to your coding style / memory.

I tend to use the following:



Choose a name for your CMS, which should be placed at the webroot of your localhost/server.

Replicate the folder structure as per the above example.

Next, we’re going to create a basic connection file.


You can create a conn.php file in your root/includes folder.

The connection file will provide crucial information to connect to the database.

Type the following into your conn.php file, remember to include your own database credentials.


<?php

$letsconnect = new mysqli("localhost","dbuser","dbpass","dbname");

?>


Let’s go to the homepage (index.php)


Create a file called index.php at the root of your CMS folder.

I will be adding comments in my code to help you understand what each line does.

Comments are a useful tool for developers to add important notes private to their code.

We need to pull information from the database so it’s imperative that we include our connection file.


<?php

include('includes/conn.php');

if ($letsconnect -> connect_errno) { echo "Error " . $letsconnect -> connect_error;

}else{

$getmydata=$letsconnect -> query("SELECT * FROM content");

foreach($getmydata as $mydata){ echo "Title: "; echo $mydata['title']; echo "<br/>"; echo "Content: "; echo $mydata['content']; echo "<br/>"; echo "Author: "; echo $mydata['author']; echo "<br/>"; echo "<br/>";

}

}

$letsconnect -> close();

?>


Let’s get a (very) basic backend up and running


Create a file called index.php in your backend folder.

We need to create a basic form to capture our data.

Let’s code some HTML!


<html>

<head><title>Backend - Capture Content</title></head>

<body>

<form action="<?php $_SERVER[‘PHP_SELF’];?>" method="post">

<input type="text" name="title" placeholder="Content Title here" required/>

<textarea name="content">Content Here</textarea>

<input type="text" name="author" placeholder="Author" required/>

<input type="submit" value="Save My Data" name="savedata"/>

</form>

</body>

</html>


Next, we need to process the form data.


Type the following just above the
<form> 
tag.


<?php

if(isset($_POST['savedata'])){

include('../includes/conn.php');

if ($letsconnect->connect_error) {

die("Your Connection failed: " . $letsconnect->connect_error);

}else{

$sql = "INSERT INTO content(title,content,author)VALUES ('".$_POST["title"]."', '".$_POST["content"]."', '".$_POST["author"]."')";

if (mysqli_query($letsconnect, $sql)) {

echo "Your data was saved successfully!";

} else { echo "Error: " . $sql . "" . mysqli_error($letsconnect);

} $letsconnect->close();

}

}

?>


Note, this is a basic MySQL query to insert data. However, before using this in production it's important to add proper escaping and security to prevent SQL injections. This will be covered in the next article.


Congrats you made it to the end of tutorial 1!


Test out your creation, modify your content, and play around.

Go to your sitename/index.php to see your frontend after capturing data via sitename/backend/index.php

Next Up:


codewithme Now With Security, Functionality, and Aesthetics in mind.


Conclusion


Coding doesn’t have to be daunting and it’s my aim to divide a complex system into bitesized tutorials so you can truly use the knowledge you’ve acquired in your own projects.
24436 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.
36866 views · 4 years ago
Securing PHP RESTful APIs using Firebase JWT Library

Hello Guys,

In our Last Blog Post, we have created restful apis,But not worked on its security and authentication. Login api can be public but after login apis should be authenticate using any secure token. one of them is JWT, So i am providing the Steps for Create and use JWT Token in our already created API.


Now its time To Implement JWT Authentication IN our Api, So these are the steps to implement it in our already created Apis


Step 1:Install and include Firebase JWT(JSON WEB TOKEN) in our project with following composer command        


 composer require firebase/php-jwt 


include the composer installed packages
require_once('vendor/autoload.php');


use namespace using following:
 use \Firebase\JWT\JWT; 



Step 2: Create a JWT server side using Firebase Jwt Library's encode method in Login action , and return it to Client



Define a private variable named Secret_Key in Class like following:

 private {
$payload = array(
'iss' => $_SERVER['HOST_NAME'],
'exp' => time()+600, 'uId' => $UiD
);
try{
$jwt = JWT::encode($payload, $this->Secret_Key,'HS256'); $res=array("status"=>true,"Token"=>$jwt);
}catch (UnexpectedValueException $e) {
$res=array("status"=>false,"Error"=>$e->getMessage());
}
return $res;
}


In our login action , if the user has been logged in successfully then with the status,_data_ and message just replace the login success code with following code:

$return['status']=1;
$return['_data_']=$UserData[0];
$return['message']='User Logged in Successfully.';

$jwt=$obj->generateToken($UserData[0]['id']);
if($jwt['status']==true)
{
$return['JWT']=$jwt['Token'];
}
else{
unset($return['_data_']);
$return['status']=0;
$return['message']='Error:'.$jwt['Error'];
}





Step 3: Now with every request after login should have the JWT token in its Post(even we can receive it in get or authentication header also but here we are receiving it in post)



No afetr successfully login you will get the JWt Token in your response,Just add that Token with every post request of after login api calls. So we will do it using postman, Find the screenshot 1 for checking the JWT Token is coming in login api response

JWT DEMO LOGIN API RESPONSE


Step 4:After reciving the JWt in every after login api call, we need to check whether the token is fine using JWT decode method in After login Apis like
UserBlogs
is a After login Api, So for verify that we are creating Authencate method in class like following:


 public function Authenticate($JWT,$Curret_User_id)
{
try {
$decoded = JWT::decode($JWT,$this->Secret_Key, array('HS256'));
$payload = json_decode(json_encode($decoded),true);

if($payload['uId'] == $Curret_User_id) {
$res=array("status"=>true);
}else{
$res=array("status"=>false,"Error"=>"Invalid Token or Token Exipred, So Please login Again!");
}
}catch (UnexpectedValueException $e) {
$res=array("status"=>false,"Error"=>$e->getMessage());
}
return $res;

}


Step 5: Cross check the response returned by Authenticate method in
UserBlogs
Action of api , replace the
UserBlogs
Action inner content with following code:


 if(isset($_POST['Uid']))
{

$resp=$obj->Authenticate($_POST['JWT'],$_POST['Uid']);
if($resp['status']==false)
{
$return['status']=0;
$return['message']='Error:'.$resp['Error'];
}
else{
$blogs=$obj->get_all_blogs($_POST['Uid']);
if(count($blogs)>0)
{
$return['status']=1;
$return['_data_']=$blogs;
$return['message']='Success.';
}
else
{
$return['status']=0;
$return['message']='Error:Invalid UserId!';
}
}
}
else
{
$return['status']=0;
$return['message']='Error:User Id not provided!';
}


Ah great its time to check out the UserBlogs Api, please find the screenshoot for that, Remember we need to put the JWt Token in POST Parameter as we have already recived that Value in Login Api call.

JWT DEMO Authentication in userBlogs API Call

Now if you want to verify that token is expiring in given time(10 minutes after generation time/login time), i am just clicking the same api with same token after 10 minutes and you can see there will not return any data and it is returning status false with following message :


JWT DEMO Authentication in userBlogs API Call


Also if you want to eloborate it more then i suggest you to try with modify Uid value with same token , you will another authentication issue and also if you modify the JWT token also then also you will not get the desired result and get authentication Issue

Thanks for reading out if you want the complete code of this file then please find following:
<?php 
header("Content-Type: application/json; charset=UTF-8");
require_once('vendor/autoload.php');
use \Firebase\JWT\JWT;

class DBClass {

private $host = "localhost";
private $username = "root";
private $password = ""; private $database = "news";

public $connection;

private $Secret_Key="*$%43MVKJTKMN$#";
public function connect(){

$this->connection = null;

try{
$this->connection = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->username, $this->password);
$this->connection->exec("set names utf8");
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}

return $this->connection;
}

public function login($email,$password){

if($this->connection==null)
{
$this->connect();
}

$query = "SELECT id,name,email,createdAt,updatedAt from users where email= ? and password= ?";
$stmt = $this->connection->prepare($query);
$stmt->execute(array($email,md5($password)));
$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);
return $ret;
}

public function get_all_blogs($Uid){

if($this->connection==null)
{
$this->connect();
}

$query = "SELECT b.*,u.id as Uid,u.email as Uemail,u.name as Uname from blogs b join users u on u.id=b.user_id where b.user_id= ?";
$stmt = $this->connection->prepare($query);
$stmt->execute(array($Uid));
$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);
return $ret;
}

public function response($array)
{
echo json_encode($array);
exit;
}

public function generateToken($UiD)
{
$payload = array(
'iss' => $_SERVER['HOST_NAME'],
'exp' => time()+600, 'uId' => $UiD
);
try{
$jwt = JWT::encode($payload, $this->Secret_Key,'HS256'); $res=array("status"=>true,"Token"=>$jwt);
}catch (UnexpectedValueException $e) {
$res=array("status"=>false,"Error"=>$e->getMessage());
}
return $res;
}

public function Authenticate($JWT,$Current_User_id)
{
try {
$decoded = JWT::decode($JWT,$this->Secret_Key, array('HS256'));
$payload = json_decode(json_encode($decoded),true);

if($payload['uId'] == $Current_User_id) {
$res=array("status"=>true);
}else{
$res=array("status"=>false,"Error"=>"Invalid Token or Token Exipred, So Please login Again!");
}
}catch (UnexpectedValueException $e) {
$res=array("status"=>false,"Error"=>$e->getMessage());
}
return $res;

}
}

$return=array();
$obj = new DBClass();
if(isset($_GET['action']) && $_GET['action']!='')
{
if($_GET['action']=="login")
{
if(isset($_POST['email']) && isset($_POST['password']))
{
$UserData=$obj->login($_POST['email'],$_POST['password']);
if(count($UserData)>0)
{
$return['status']=1;
$return['_data_']=$UserData[0];
$return['message']='User Logged in Successfully.';

$jwt=$obj->generateToken($UserData[0]['id']);
if($jwt['status']==true)
{
$return['JWT']=$jwt['Token'];
}
else{
unset($return['_data_']);
$return['status']=0;
$return['message']='Error:'.$jwt['Error'];
}

}
else
{
$return['status']=0;
$return['message']='Error:Invalid Email or Password!';
}
}
else
{
$return['status']=0;
$return['message']='Error:Email or Password not provided!';
}
}
elseif($_GET['action']=="UserBlogs")
{
if(isset($_POST['Uid']))
{

$resp=$obj->Authenticate($_POST['JWT'],$_POST['Uid']);
if($resp['status']==false)
{
$return['status']=0;
$return['message']='Error:'.$resp['Error'];
}
else{
$blogs=$obj->get_all_blogs($_POST['Uid']);
if(count($blogs)>0)
{
$return['status']=1;
$return['_data_']=$blogs;
$return['message']='Success.';
}
else
{
$return['status']=0;
$return['message']='Error:Invalid UserId!';
}
}
}
else
{
$return['status']=0;
$return['message']='Error:User Id not provided!';
}
}
}
else
{
$return['status']=0;
$return['message']='Error:Action not provided!';
}
$obj->response($return);
$obj->connection=null;
?>

SPONSORS