PHP & Web Development Blogs

Search Results For: apis
Showing 1 to 5 of 5 blog articles.
4980 views · 1 years ago

![Why Cloudways is the Perfect Managed Hosting for PHP Applications](https://images.ctfassets.net/vzl5fkwyme3u/3VLCUBagZPfSLyxyt1AvvP/89e3b904a450454545eb885e2e0e76b4/cloudways.jpg?w=1000)

#### The following is a sponsored blogpost by [Cloudways](https://www.cloudways.com/en/?id=431739)

Developing an application is not the sole thing you should bank on. You must strive to find the best hosting solution to deploy that application also. The application’s speed is dependent on the hosting provider, that is why I always advise you to go for the best hosting solution to get the ultimate app performance.

Now a days, it is a big challenge to choose any web hosting, as each hosting has its own pros and cons which you must know, before considering it finally for the deployment. I don’t recommend shared hosting for PHP/Laravel based applications, because you always get lot of server hassles like downtime, hacking, 500 errors, lousy support and other problems that are part and parcel of shared hosting.

For PHP applications, you must focus on more technical aspects like caching, configs, databases, etc. because these are essential performance points for any vanilla or framework-based PHP application. Additionally, if the app focuses on user engagement (for instance, ecommerce store), the hosting solution should be robust enough to handle spikes in traffic.

Here, I would like to introduce Cloudways [PHP server hosting](https://www.cloudways.com/en/php-cloud-hosting.php?id=431739) to you which provides easy, developer and designer friendly managed hosting platform. With Cloudways, you don't need to focus on PHP hosting, but must focus on building your application. You can easily launch cloud servers on five providers including DigitalOcean, Linode, Vultr, AWS and GCE.

### Cloudways ThunderStack

Being a developer, you must be familiar with the concept of stack - an arrangement of technologies that form the underlying hosting solution.

To provide a blazing fast speed and a glitch-free performance, Cloudways has built a PHP stack, known as ThunderStack. This stack consists of technologies that offer maximum uptime and page load speed to all PHP applications. Check out the following visual representation of ThunderStack and the constituent technologies:

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/5v08m0nwsFPv7niXjmRX0M/ca3aba8d814578baf676bd58c3933dc8/cloudways_image1.png?w=1000)

As you can see, ThunderStack comprises of a mix of static and dynamic caches with two web servers, Nginx and Apache. This combination ensures the ultimate experience for the users and visitors of your application.

### Frameworks and CMS

The strength and popularity of PHP lies in the variety of frameworks and CMS it offers to the developers. Realizing this diversity, Cloudways offers a hassle-free installation of major PHP frameworks including Symfony, Laravel, CakePHP, Zend, and Codeigniter. Similarly, popular CMS such as WordPress, Bolt, Craft, October, Couch, and Coaster CMS - you can install these with the 1-click option. The best part is that if you have a framework or CMS that is not on the list, you can easily install it through Composer.

### 1-Click PHP Server & Application Installation

Setting up a stack on an unmanaged VPS could take an entire day!

When you opt for Cloudways managed cloud hosting, the entire process of setting up the server, installation of core PHP files and then the setup of the required framework is over in a matter of minutes.

Just [sign up at Cloudways](https://www.cloudways.com/en/?id=431739), choose your desired cloud provider, and select the PHP stack application.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/2Dp11Kg9FOkHkFbjUub7Tj/f0c4c125a8c683c51a548fdd287c8330/cloudways_image2.png?w=1000)

As you can see, your LAMP stack is ready for business in minutes.

Many PHP applications fail because essential services are either turned off or not set up properly. Cloudways offers a centralized location where you can view and set the status of all essential services such as:

* Apache

* Elasticsearch

* Memcached

* MySQL

* PHP-FPM

* Nginx

* New Relic

* Redis

* Varnish

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/1zvZI0b7zuPbBacp4ALAax/a5150babfbe2972c96beca3ac71395f2/cloudways_image3.png?w=1000)

Similarly, you can manage SMTP add-ons without any fuss.

### Staging Environment

With Cloudways, you can test your web applications for possible bugs and errors before taking it live.

Using the staging feature, developers can first deploy their web sites on test domains where they can analyze the applications performance and potential problems. This helps site administrators to fix those issues timely and view the application performance in real-time.

A default sub domain comes pre-installed with the newly launched application, making it easy for the administrators to test the applications on those testing subdomains. Overall, it's a great feature which helps developers know about the possible errors that may arise during the live deployment.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/5gTrIsw9KjhocjtZMWVePB/a8274899ee55d7068329c551af362fdf/cloudways_image4.png?w=1000)

### Pre-Installed Composer & Git

PHP development requires working with external libraries and packages. Suppose you are working with Laravel and you need to install an external package. Since Composer has become the standard way of installing packages, it comes preinstalled on the Cloudways platform. Just launch the application and start using Composer in your project.

Similarly, if you are familiar with Git and maintain your project on GitHub or BitBucket, you don’t need to worry about Git installation. Git also comes pre-configured on Cloudways. You can start running commands right after application launch.

### Cloudways MySQL Manager

When you work with databases in PHP, you need a database manager. On the Cloudways platform, you will get a custom-built MySQL manager, in which you can perform all the tasks of a typical DB manager.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/415qced8tKK8FWEsWGPhAm/ec1947d0b21ac8cd572613d0a1fa88dc/cloudways_image5.png?w=1000)

However, if you wish to install and use another database manager like PHPMyAdmin, you can install it by following this simple guide on installing [PHPMyadmin](https://www.cloudways.com/blog/installation-phpmyadmin/?id=431739).

### Server & Application Level SSH

If you use Linux, you typically use SSH for accessing the server(s) and individual applications. A third-party developer requires application and server level access as per the requirements of the client. Cloudways offers SSH access to fit the requirements of the client and users.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/1IpSR4TrckMFJjYQ1m5upz/030f71f106b7db97ce16de10aba2c17b/cloudways_image6.png?w=1000)

### PHP-FPM, Varnish & Cron Settings

Cloudways provides custom UI panel to set and maintain PHP-FPM and Varnish settings. Although the default configuration is already in place, you can easily change all the settings to suit your own, particular development related requirements. In Varnish settings, you can define URL that you want to exclude from caching. You can also set permissions in this panel.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/2W8XQvGa3CZAPBwUY4sqca/8a6b041c6dc850cc2715bb19eb17a464/cloudways_image7.png?w=1000)

Cron job is a very commonly used component of PHP application development process. On Cloudways platform, you can easily set up Cron jobs in just a few clicks. Just declare the PHP script URL and the time when the script will run.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/32fN2IkC1X3HEC2Ly685nz/6fb9607bab9beaa81bff1b7fe4061edf/cloudways_image8.png?w=1000)

### Cloudways API & Personal Assistant Bot

Cloudways provides an internal API that offers all important aspects of the server and application management. Through Cloudways API, you can easily develop, integrate, automate, and manage your servers and web apps on Cloudways Platform using the RESTful API. Check out some of the [use cases developed](https://www.cloudways.com/blog/category/use-cases/api/?id=431739) using Cloudways API. You just need your API key and email for authentication of the HTTP calls on API Playground and custom applications.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/5Uxx5XySaV2um2AnJjvbcg/0a4e997995d6644aa90c850a41db2720/cloudways_image9.png?w=1000)

Cloudways employs a smart assistant named CloudwaysBot to notify all users about server and application level issues. CloudwaysBot sends the notifications on pre-approved channels including email, Slack and popular task management tools such as Asana and Trello.

### Run Your APIs on PHP Stack

Do you have your own API which you want to run on the PHP stack? No problem, because you can do that, too with Cloudways! You can also use REST API like [Slim](https://www.cloudways.com/blog/simple-rest-api-with-slim-micro-framework/?id=431739&utm_source=phpjabber&utm_medium=referral), [Silex](https://www.cloudways.com/blog/create-rest-api-silex/?utm_source=phpjabber&utm_medium=referral&id=431739), [Lumen](https://www.cloudways.com/blog/creating-rest-api-with-lumen/?utm_source=phpjabber&utm_medium=referral&id=431739), and others. You can use APIs to speed up performance and require fast servers with lots of resources. So, if you think that your API response time is getting slower due to the large number of requests, you can easily scale your server(s) with a click to address the situation.

### Team Collaboration

When you work on a large number of applications with multiple developers, you need to assign them on any specific application. Cloudways provides an awesome feature of team collaboration through which you can assign developers to specific application and give access to them. You can use this tool to assign one developer to multiple applications. Through team feature, you can connect the team together and work on single platform. Access can be of different type; i.e. billing, support and console. You can either give the full access or a limited one by selecting the features in Team tab.

![alt_text](https://images.ctfassets.net/vzl5fkwyme3u/3Yn7GSeHrLvSbPf42RTR2n/269328c371e80f3ac87984cf46b6e9ac/cloudways_image10.png?w=1000)

### Final Words

Managed cloud hosting ensures that you are not bothered by any hosting or server related issues. For practical purposes, this means that developers can concentrate on writing awesome code without worrying about underlying infrastructure and hosting related issues. Do [sign up](https://www.cloudways.com/en/?id=431739) and check out Cloudways for the best and the most cost-effective cloud hosting solution for your next PHP project!

7727 views · 1 years ago

![PHP CHAT WITH SOCKETS](https://images.ctfassets.net/vzl5fkwyme3u/71dBtxsZPdBnAn8UgQTyRR/75ca0c2ab27af41ffc82b17d1be264d7/AdobeStock_265642631.jpeg?w=1000)

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 it **increases 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

/ /remove semicolon from very start of the extension like

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:

```php

$host = 'localhost'; / /host

$port = '9000'; / /port

$null = NULL; / /null var

```

### 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:

```php

function send_message($msg)

{

global $clients;

foreach($clients as $changed_socket)

{

@socket_write($changed_socket,$msg,strlen($msg));

}

return true;

}

/ /Unmask incoming framed message

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;

}

/ /Encode message for transfer to client.

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;

}

/ /handshake new client.

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')));

/ /hand shaking header

$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:

```php

/ /Create TCP/IP stream socket

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

/ /reuseable port

socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);

/ /bind socket to specified host

socket_bind($socket, 0, $port);

/ /listen to port

socket_listen($socket);

/ /create & add listning socket to the list

$clients = array($socket);

```

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

```php

/ /start endless loop, so that our script doesn't stop

while (true) {

/ /manage multiple connections

$changed = $clients;

/ /returns the socket resources in $changed array

socket_select($changed, $null, $null, 0, 10);

/ /check for new socket

if (in_array($socket, $changed)) {

$socket_new = socket_accept($socket); / /accpet new socket

$clients[] = $socket_new; / /add socket to client array

$header = socket_read($socket_new, 1024); / /read data sent by the socket

perform_handshaking($header, $socket_new, $host, $port); / /perform websocket handshake

socket_getpeername($socket_new, $ip); / /get ip address of connected socket

$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); / /prepare json data

send_message($response); / /notify all users about new connection

/ /make room for new socket

$found_socket = array_search($socket, $changed);

unset($changed[$found_socket]);

}

/ /loop through all connected sockets

foreach ($changed as $changed_socket) {

/ /check for any incomming data

while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)

{

$received_text = unmask($buf); / /unmask data

$tst_msg = json_decode($received_text, true); / /json decode

$user_name = $tst_msg['name']; / /sender name

$user_message = $tst_msg['message']; / /message text

$user_color = $tst_msg['color']; / /color

/ /prepare data to be sent to client

$response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color)));

send_message($response_text); / /send data

break 2; / /exist this loop

}

$buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ);

if ($buf === false) { / / check disconnected client

/ / remove client for $clients array

$found_socket = array_search($changed_socket, $clients);

socket_getpeername($changed_socket, $ip);

unset($clients[$found_socket]);

/ /notify all users about disconnected connection

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

send_message($response);

}

}

}

/ / close the listening socket

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

```php

$host = 'localhost'; / /host

$port = '9000'; / /port

$subfolder = "php_ws/"; / /project subfolder name, you may change it with project directory or make it blank

/ /#add trail slash if there is any subfolder defined otherrwise make it blank

$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:

```html

<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:

```html

<script src="https:/ /ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script language="javascript" type="text/javascript">

/ /create a new WebSocket object.

var msgBox = $('#message-box');

var wsUri = "ws:/ /".$host.":".$port."/php-ws/server.php";

websocket = new WebSocket(wsUri);

websocket.onopen = function(ev) { / / connection is open

msgBox.append('<div class="system_msg" style="color:#bbbbbb">Welcome to my "Chat box"!</div>'); / /notify user

}

/ / Message received from server

websocket.onmessage = function(ev) {

var response = JSON.parse(ev.data); / /PHP sends Json data

var res_type = response.type; / /message type

var user_message = response.message; / /message text

var user_name = response.name; / /user name

var user_color = response.color; / /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; / /scroll message

};

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>'); };

/ /Message send button

$('#send-message').click(function(){

send_message();

});

/ /User hits enter key

$( "#message" ).on( "keydown", function( event ) {

if(event.which==13){

send_message();

}

});

/ /Send message

function send_message(){

var message_input = $('#message'); / /user message text

var name_input = $('#name'); / /user name

if(message_input.val() == ""){ / /empty name?

alert("Enter your Name please!");

return;

}

if(message_input.val() == ""){ / /emtpy message?

alert("Enter Some message Please!");

return;

}

/ /prepare json data

var msg = {

message: message_input.val(),

name: name_input.val(),

color : '<?php echo $colors[$color_pick]; ?>'

};

/ /convert and send data to server

websocket.send(JSON.stringify(msg));

message_input.val(''); / /reset message input

}

</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.

8369 views · 1 years ago

![Securing PHP RESTful APIs using Firebase JWT Library](https://images.ctfassets.net/vzl5fkwyme3u/4oaGx3XTrH7kq4KkQbQPQ6/87f8b47b39e42dfdd93e111aa4f91e9f/AdobeStock_191967596.png?w=1000)

Hello Guys,

In our [Last Blog Post](https://nomadphp.com/blog/69/create-simple-restful-apis-using-php-amp-mysql), 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 / / you may change this key ```

Now create a method in your class named generateToken as following:

```

public function generateToken($UiD)

{

$payload = array(

'iss' => $_SERVER['HOST_NAME'],

'exp' => time()+600, / / token expiry time in timestamp We have used current we have used 10 minutes as expiry time

'uId' => $UiD

);

try{

$jwt = JWT::encode($payload, $this->Secret_Key,'HS256'); / / last parameter is the Engryption Algorithm name

$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.';

/ / generate and add jWT token using following method we created in class / /

$jwt=$obj->generateToken($UserData[0]['id']);

if($jwt['status']==true)

{

/ / if token generated successfully then add token in JWT key in response

$return['JWT']=$jwt['Token'];

}

else{

/ / if token generation failed then unset the return user data and add false status

unset($return['_data_']);

$return['status']=0;

$return['message']='Error:'.$jwt['Error'];

}

/ / generate and add jWT token using following method we created in class / /

```

### 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](https://www.w3school.info/blogimages/JWT_LOGIN_API.png)

### 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) / / verify that the user id coming in after login api is equals to the decoded payload user id, if matched then the token is fine and data not tempered

{

$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']))

{

/ / Authenticate the JWT before fetching the data

$resp=$obj->Authenticate($_POST['JWT'],$_POST['Uid']);

if($resp['status']==false)

{

$return['status']=0;

$return['message']='Error:'.$resp['Error'];

}

/ / Authenticate the JWT before fetching the data

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](https://www.w3school.info/blogimages/JWT_userBlogs_API.png)

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](https://www.w3school.info/blogimages/JWT_userBlogs_API_TOKEN_EXPIRY.png)

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 = ""; / / set your passwrd here

private $database = "news";

public $connection;

private $Secret_Key="*$%43MVKJTKMN$#"; / / you may change this key

/ / get the database connection

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, / / token expiry time in timestamp We have used current we have used 10 minutes as expiry time

'uId' => $UiD

);

try{

$jwt = JWT::encode($payload, $this->Secret_Key,'HS256'); / / last parameter is the Engryption Algorithm name

$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) / / verify that the user id coming in after login api is equals to the decoded payload user id, if matched then the token is fine and data not tempered

{

$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;

}

}

/ / receive the requests here / /

$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.';

/ / generate and add jWT token using following method we created in class / /

$jwt=$obj->generateToken($UserData[0]['id']);

if($jwt['status']==true)

{

/ / if token generated successfully then add token in JWT key in response

$return['JWT']=$jwt['Token'];

}

else{

/ / if token generation failed then unset the return user data and add false status

unset($return['_data_']);

$return['status']=0;

$return['message']='Error:'.$jwt['Error'];

}

/ / generate and add jWT token using following method we created in class / /

}

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']))

{

/ / Authenticate the JWT before fetching the data

$resp=$obj->Authenticate($_POST['JWT'],$_POST['Uid']);

if($resp['status']==false)

{

$return['status']=0;

$return['message']='Error:'.$resp['Error'];

}

/ / Authenticate the JWT before fetching the data

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;

?>

```

4982 views · 1 years ago

Conferences are always looking for speakers - it can be hard to keep track of them all and the requirements they have. I wanted to put together this quick guide to make it easy for you to apply. Make sure to apply because as Wayne Gretzky said “You miss 100% of the shots you don’t take”!!!

![](https://sayingimages.com/wp-content/uploads/you-can-do-it-if-you-do-it-meme.jpg)

## phpDay 2019

First we have phpDay 2019 which will take place on May 10 & 11 at Hotel San Marco in Verona, Italy. Some facts about this call for papers:

* **Submission deadline:** February 4, 2019

* **Submit via:** https://cfp.phpday.it/

* For more info on the conference: https://2019.phpday.it/

* Twitter: (@phpday)

* Speaker package includes: Full conference pass (jsDay + phpDay), speaker dinner the first night, lunch, reception and activities included in regular conference.

* For speakers remote to the Area: A refund of up to €200 for travel costs (or €500 from US or extra-EU), 2 complimentary hotel nights (+1 hotel night for speakers presenting multiple talks or US/extra-EU) and Taxi fare from/to the airport.

* **In Submission**: make sure your talk title and abstract define the exact topic you want to talk about and what you hope people will learn from the session.

* **Talk Ideas**: APIs (REST, SOAP, etc.), Architectures, Continuous Delivery, Databases, Development, Devops, Frameworks, Internals, PHP 7.x / PHP 8, Security, Testing and UI/UX.

## ScotlandPHP

Next we have ScotlandPHP which will take place on November 8 & 9 at Edinburgh International Conference Centre in Edinburgh, Scotland.

* **Submission deadline:** April 22, 2019

* **Submit via:** https://cfs.scotlandphp.co.uk/

* For more info on the conference: https://conference.scotlandphp.co.uk/

* Twitter: (@scotlandphp)

* Speaker package: Full conference pass, lunch, receptions and activities included in regular conference.

* For speakers remote to the Area: Complimentary airfare/travel, 2 complimentary hotel nights and we'll pick you up and drop you off to/from the airport so you don't have to worry about it.

* Speakers will be provided with a projector, a wireless lapel microphone and a screen for their presentation (size depends on the room). Speakers should bring any equipment they need to connect to projectors (VGA). It is also suggested that you reduce your dependency on the in-house internet connection as possible. We will however provide HDMI and Mini Display Port connections for all speakers on request. If you need something different or your selected talk needs audio equipment just let us know. We'll work it out.

* Looking for talks and workshops (November 8th).

* **Talk Ideas**: Virtualization and environments, Javascript, Alternate PHP run-times, PHP internals, Development principles, Security, Mobile-first design, Testing (unit, functional, etc.), Version control, User Experience/Usability, Building APIs (REST, SOAP, whatever), Continuous Integration, Framework-related topics, and Professional development.

## Global diversity CFP day

In 2019 there will be numerous workshops hosted around the globe encouraging and advising newbie speakers to put together your very first talk proposal and share your own individual perspective on any subject of interest to people in tech.

* Twitter: (@gdcfpday)

* **Save the Date**: March 2, 2019

* **Register here**: https://www.globaldiversitycfpday.com/?utm_source=scotphp

## CoderCruise

Then there is CoderCruise which will take place on August 19-23. It's a cruise that takes off from Port Canaveral, Florida and goes to the Bahamas.

* Twitter: (@codercruise)

* **Submission deadline**: March 3, 2019

* **Submit via**: https://www.papercall.io/codercruise-2019

* For more info on the conference: https://www.codercruise.com/

* This is a polyglot conference so looking for speakers on a wide variety of languages (PHP, JavaScript, Java, Python, etc.) and on various tech topics.

## PHP Conference Asia 2019

There is also PHP Conference Asia 2019, which will take place on June 24-25 at Microsot Singapore.

* **Submission deadline**: March 8, 2019

* **Submit via:** https://cfp.phpconf.asia/

* For more info on the conference: https://2019.phpconf.asia/

* Twitter: (@PHPConfAsia)

* Speaker package includes: Speaker package: Full conference pass, lunch, receptions and activities included in regular conference. We'll pick you up and drop you off to/from the airport so you don't have to worry about it. Speakers' dinner on the first evening of the conference (24th June 2019). Transport to and from the conference venue will be included

* For speakers remote to the Area: 2 complimentary hotel nights and

we can consider providing grants to partially cover the air-fare for speakers who might have financial difficulties. This is on a case-by-case basis.

* Speakers will be provided with a projector, a wireless hand-held microphone and a screen for their presentation. Speakers should prepare their slides in 4x3 aspect ratio. Speakers should bring any equipment they need to connect to projectors (HDMI). It is also suggested that you reduce your dependency on the in-house internet connection as possible.

* **In Submission**: Make sure your talk title and abstract define the exact topic you want to talk about and what you hope people will learn from the session.

* **Talk Ideas**: Virtualization and environments, Javascript, Alternate PHP run-times, PHP internals, Development principles, Security, Mobile-first design, Testing (unit, functional, etc.), Version control, User Experience/Usability, Building APIs (REST, SOAP, whatever), Continuous Integration, Framework-related topics, and Professional development.

## Cascadia PHP

Another conference to apply to is Cascadia PHP, which will take place on September 19-21 at University Place Hotel & Conference Center in Portland, Oregon.

* **Submission deadline**: April 15, 2019

* **Submit via:** https://cfp.cascadiaphp.com/

* For more info on the conference: https://www.cascadiaphp.com/venue

* Twitter: (@CascadiaPHP)

* Speaker package includes: Speaker package: Full conference pass, lunch, receptions and activities included in regular conference. * For speakers remote to the Area: Complimentary airfare/travel, 2 complimentary hotel nights and we'll pick you up and drop you off to/from the airport so you don't have to worry about it.

* Speakers will be provided with a projector, a wireless lapel microphone and a screen for their presentation (size depends on the room). Speakers should bring any equipment they need to connect to projectors (VGA). It is also suggested that you reduce your dependency on the in-house internet connection as possible.

* **In Submission**: make sure your talk title and abstract define the exact topic you want to talk about and what you hope people will learn from the session.

* **Talk Ideas**: PHP internals, Version control, Framework-related topics, Building APIs (REST, SOAP, whatever), Mobile-first design, Professional development, Testing (unit, functional, etc.), Alternate PHP run-times, Development principles, Continuous Integration, Getting involved in the PHP community, User Experience/Usability, Technology at large, Security, Connecting to Different APIs, Development Tools, Virtualization and environments, Javascript, Modern hosting practices, Language Features, Databases, Refactoring legacy applications, Running/contributing to open source projects, AI and AR, and User Groups.

## Nomad PHP

Last but not least - this is an ongoing call for papers. This is perfect if you want to present from the comfort of your office, home or really wherever you are. It’s via RingCentral meetings and will be live and recorded. This is for none other than Nomad PHP.

* Twitter: (@nomadphp)

* Deadline: Anytime :D

* Talk length: 45 - 60 minutes.

* Talks should be unique to Nomad PHP and not available in video format online.

* Talk should not be recorded or made available elsewhere online for at least 3 months following your talk.

* The talk will be featured on our page and promoted via social media.

* Speakers will receive a financial stipend.

* Upon being selected we will reach out with further details.

* **Talk ideas**: AI & Machine Learning, APIs, Containerization, Databases, DevOps, Documentation, Frameworks, Performance, Security, Serverless, Testing, Tools, Upgrading/ Modernization, and more.

* **Submit here**: https://www.papercall.io/nomadphp

Now that you have some information - make sure to apply to all of these options! Can't wait to see all of your awesome talks you present :D!

9000 views · 1 years ago

![Create Simple RESTful APIs using PHP & MySQL](https://images.ctfassets.net/vzl5fkwyme3u/5s6X92LpF8dGGVZEnXGRK0/387bfe60541987d308e8201ca5bb5d3f/api_blog_post.png?w=1000)

Hi Guys,

I am sharing you the way to create simple resful apis using php and mysql. We are creating 2 apis here

First is to Loggin a existing user and second is to get list of written blogs by logged in user.

#### Create any database, i am taking ```news``` as the database name here, After it create following 2 tables inside it.

```

CREATE TABLE `users` (

`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

`name` varchar(100),

`email` varchar(100),

`password` varchar(100),

`createdAt` datetime NOT NULL,

`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

CREATE TABLE `blogs` (

`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

`user_id` int(11),

`title` varchar(255),

`summary` Tinytext,

`body` Text,

`createdAt` datetime NOT NULL,

`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

```

#### Now putting some dummy data to read via the api

```

--create 2 entries in users table--

INSERT INTO `news`.`users` (`id`, `name`, `email`, `password`, `createdAt`, `updatedAt`) VALUES (1, 'jeetendra singh', '[email protected]', MD5('123456'), '2018-12-28 02:05:12', CURRENT_TIMESTAMP), (2, 'Manvik Singh chaudhary', '[email protected]', MD5('654321'), '2018-12-28 03:08:11', CURRENT_TIMESTAMP);

-- create 2 blogs by userid 1--

INSERT INTO `news`.`blogs` (`id`, `user_id`, `title`, `summary`, `body`, `createdAt`, `updatedAt`) VALUES (1, '1', 'Blog title 1 by jeetendra', 'Blog summary 1 by jeetendra', 'Blog body 1 by jeetendra', '2018-12-28 02:00:00', CURRENT_TIMESTAMP), (2, '1', 'Blog Title 2 by jeetendra ', 'Blog summary 2 by jeetendra ', 'Blog body 2 by jeetendra ', '2018-12-28 05:10:21', CURRENT_TIMESTAMP);

-- create 2 blogs by userid 2

INSERT INTO `news`.`blogs` (`id`, `user_id`, `title`, `summary`, `body`, `createdAt`, `updatedAt`) VALUES (3, '2', 'Blog title 1 by manvik', 'Blog summary 1 by manvik', 'Blog body 1 by manvik', '2018-12-28 02:00:00', CURRENT_TIMESTAMP), (4, '2', 'Blog Title 2 by manvik ', 'Blog summary 2 by manvik ', 'Blog body 2 by manvik ', '2018-12-28 05:10:21', CURRENT_TIMESTAMP);

```

#### After creating this create a index.php and put this code for Db connection, login and get all blog method

```

<?php

header("Content-Type: application/json; charset=UTF-8");

class DBClass {

private $host = "localhost";

private $username = "root";

private $password = ""; / /set your passwrd here

private $database = "news";

public $connection;

/ / get the database connection

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;

}

}

/ /recieve the requests here / /

$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.';

}

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']))

{

$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;

?>

```

#### Now api file is set, just make the urls pretty(readable form) using .htaccess file, put following code in it

```

RewriteEngine On

RewriteRule ^api/(.*) index.php?action=$1

```

#### Now your Simple Restful Apis are ready to use, Now Let me show you the postman screenshot where i have used these apis.

**Login Api Call:**

![LOGIN API CALL](https://www.w3school.info/blogimages/login_api.png)

**User Post/Blog Api Call**

![USER BLOGS](https://www.w3school.info/blogimages/UserBlogs_api.png)

    SPONSORS

    Faster PHP Cloud Hosting