PDF view in browser and export as file – PHP

If you link a PDF file saved in your server with an anchor tag and give it a “download” attribute. It will make the file downloadable. When user clicks on it, it will be downloaded on his computer. But in some cases, you want to view the PDF file in the browser. Rather than downloading it in client’s system.

FPDF

We are going to use the library named FPDF you can download it from it’s official site. You will get ZIP file in your download, extract it and you will get just 1 folder. You need to copy that folder in your project root folder where it can be accessible. In that folder you will also find a folder named “font” that will be used if you want to add more fonts in your PDF file. By default it came up with 14 fonts at the time of writing this.

Create invoice PDF

So we are going to create a simple invoice page which is a common example in E-commerce sites. There, once you buy any product then an invoice has been generated which contains all the order details. It typically contains company logo, buyer name & address, all products which were added in cart and their quantity & price. Lastly, it has total sum of all products. Some also have shipping cost so they display grand total which is the sum of all products price and the shipping cost.

In order to create PDF view in your browser you first needs to include the fpdf.php inside your downloaded folder. Then you need to create an instance of FPDF class, we will be using this object throughout this tutorial. Then needs to add a page in PDF. Otherwise it will throw an exception that no page has been found in PDF. Lastly you will render the PDF in browser by calling the output() function with your PDF instance. We will be using index.php to display the PDF file. But you might be creating a separate file for viewing PDF. Paste the following code in your index.php file:

<?php

// Include the PDF class
require_once "fpdf181/fpdf.php";

// Create instance of PDF class
$pdf = new FPDF();

// Add 1 page in your PDF
$pdf->AddPage();

// Render the PDF in your browser
$pdf->output();

?>

Create header

Header will contain an image which can be served as a logo on top left and on right. You can either display the name of company or the subject of report. Example of subject of report can be “report”, “invoice”, “letter” etc. In order to insert image in your PDF file you need to call the Image(src, x, y, width, height) function. Here, src will be the source of image which needs to be placed, typically we place company logo in PDF. X & Y are the co-ordinates where image will be placed and width & height are self-explanatory I believe. Paste the following code after AddPage() function and before the output() function:

<?php

// Place image on top left with 100px width
$pdf->Image("logo.jpg", 10, 10, 100);

// Set Arial Bold font with size 22px
$pdf->SetFont("Arial", "B", 22);

// Give margin from left
$pdf->SetX(160);

// Write text "Invoice" with 0 width & height (it will still be visible)
$pdf->Cell(0, 0, "Invoice");

// Move the cursor to next line
$pdf->Ln();

?>

Output – PDF view in browser

PDF view in browser

Display database data in PDF

Suppose some customer have purchased something from your website and you have saved his selected products in your database. Now, you need to show these values from database inside the PDF. We are going to show the database data in table format. We will be using Cell() function with PDF instance and it’s parameters are: Cell(x, y, text, border, ln, alignment, fill). It’s explanation is given below. First we are going to create a header for table which will be highlighted from other rows of the table:

XMargin from left
YMargin from top
textText which needs to be displayed
borderBorder around the text (1 means 1px)
lnWhere should next cell starts (0 means to right, 1 means next line)
AlignmentAlignment of text (can be “L” for left, “R” for right, “C” for center and “J” for justify)
FillWhether this cell nexts to be filled or not (true / false)
<?php

// Sets the background color to light gray
$pdf->SetFillColor(209, 207, 207);

// Cell
$pdf->Cell(50, 10, "Product Code", 1, 0, "L", true);
$pdf->Cell(50, 10, "Quantity", 1, 0, "L", true);
$pdf->Cell(50, 10, "Price", 1, 0, "L", true);
$pdf->Ln();

?>

Output

Now we will run the query on database and display all returned records in table rows. But first we need to make the font from bold to normal because bold only looks good for headings.

<?php

// Setting the font to Arial normal with size 16px
$pdf->SetFont("Arial", "", 16);

// Connecting with database
$conn = mysqli_connect("localhost", "root", "", "classicmodels");

// Getting records from database
$result = mysqli_query($conn, "SELECT * FROM orderDetails WHERE orderNumber = '10101'");

// Iterate through each record
while ($row = mysqli_fetch_object($result))
{
	// Create cells with 50px width, 10px height and 1px border
	$pdf->Cell(50, 10, $row->productCode, 1);
	$pdf->Cell(50, 10, $row->quantityOrdered, 1);
	$pdf->Cell(50, 10, $row->priceEach, 1);

	// Moving cursor to next row
	$pdf->Ln();
}

?>

Output – PDF view in browser

In these type of cases you may also wanted to show the total of all products which includes the sum of all products unit price multiplied by quantity. Also you also want to add the shipping cost if the product needs to be delivered physically. So first we will add all the product’s price in a variable and then we will add the shipping cost in it. Then we will display 3 sections, 1 for product’s total price, 1 for shipping cost and 1 for grand total which will be sum of total price and shipping cost. We are going to highlight the grand total section too because it is the final price and it needs to get attention:

<?php

$total = 0;
while ($row = mysqli_fetch_object($result))
{
	// ..... display cells here

	$total += $row->priceEach * $row->quantityOrdered;
}

$pdf->Ln();
$pdf->SetX(60);
$pdf->Cell(50, 10, "Total", 1);
$pdf->Cell(50, 10, "$" . $total, 1);
$pdf->Ln();

$pdf->SetX(60);
$pdf->Cell(50, 10, "Shipping", 1);
$pdf->Cell(50, 10, "$9", 1);
$pdf->Ln();

$pdf->SetX(60);
$pdf->Cell(50, 10, "Grand Total", 1, 0, "L", true);
$pdf->Cell(50, 10, "$" . ($total + 9), 1, 0, "L", true);
$pdf->Ln();

?>

Output – PDF view in browser

At this point, if you access the “Invoice.pdf” from the address bar. You will be able to view the PDF file in your browser. Now we need to make it downloadable.

Downloading the PDF

To download the PDF as external file or exporting the file in your computer, you need to do few steps. First you need to change your output() function and make it to accept two arguments, first will be the name of file that will be save in your server and second will be the character F which indicates that user wants to create a file and instead of displaying in browser. Then you need to pass some headers which will download the file, and finally you can remove the file from server if you want. Because in some cases you just want the file to get downloaded by user and not to keep in your server.

<?php

// Creates a file in server
$pdf->output("Invoice.pdf", "F");

// Tell that the file will be PDF
header("Content-type: application/pdf");

// Set the file as attachment and set its name to "Invoice.pdf"
header("Content-disposition: attachment; filename = Invoice.pdf");

// Read the source file (which needs to be downloaded)
readFile("Invoice.pdf");

// Delete the file from server
unlink("Invoice.pdf");

?>

That’s it. If you face any problem in following this tutorial, please feel free to ask in the comments section below.

Check out our tutorial on using 10 common Javascript libraries used in almost every web project.

[wpdm_package id=’184′]

jQuery ratings plugin with database & average calculation

There is a jQuery ratings plugin called “Starrr”. It allows you to get feedback input from the user by displaying him stars. Lower stars means they didn’t liked your product or service. And higher stars means they liked your product or services.

Let’s get started

First you need to download and integrate a small and lightweight Javascript library in your project. The name of library is Starrr and you can download it from here. You may get the downloaded file in ZIP format so unzip it (of course). In the unzipped folder, you will find a folder named “dist”. You will find 2 files, one is CSS and second will be of JS. You need to copy both these files and place them in your project folder. To setup the star ratings in your website, you need to include 3 CSS files and 2 JS files.

CSS

  1. Bootstrap
  2. Font Awesome
  3. Starrr

JS

  1. jQuery
  2. Starrr

So paste the following code at the top of file where you want to show ratings. We have used the CDN for Bootstrap, Font Awesome and jQuery for direct integration. But you can download them in your project and give relative path if you want. If you are already working on some project, then most probably you already have those CSS & JS files. Because they are used mostly in design part.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" href="starrr.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="starrr.js"></script>

Database integration

You might already have a database with all the data and you just want to integrate this star ratings in it. So you might have an E-commerce site where you want to give ratings to products, or may have an online Job Portal where you want to give ratings to Clients or Freelancers etc. So for the sake of simplicity we are are creating simple products with just 2 fields, you might have a lot of other fields too but it will give you enough idea how to implement in your project. Create a new database in your phpMyAdmin named tutorials and run the following queries to create 1 table named products and other ratings where all ratings of each product will be stored:

--
-- Database: `tutorials`
--

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `name` text NOT NULL
);

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`) VALUES
(1, 'Macintosh'),
(2, 'iMac'),
(3, 'iPod'),
(4, 'Apple II');

-- --------------------------------------------------------

--
-- Table structure for table `ratings`
--

CREATE TABLE `ratings` (
  `id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `ratings` int(11) NOT NULL
);

Display all products

Now you need to display all products stored in your database. We are just displaying product name but surely you will be displaying other details too. Along with each product we will create a form to get product ID and show 5 stars from where user can give ratings and a submit button.

<?php
	// Connecting with database
	$conn = mysqli_connect("localhost", "root", "", "tutorials");

	// Getting all products
	$result = mysqli_query($conn, "SELECT * FROM products");

	// Displaying each product
	while ($row = mysqli_fetch_object($result)) {
?>

	<p>
		<?php
			echo $row->name;
		?>
	</p>

	<form method="POST" onsubmit="return saveRatings(this);">
		<input type="hidden" name="product_id" value="<?php echo $row->id; ?>">

		<div class="starrr"></div>

		<input type="submit">
	</form>

<?php
	}
?>

<script>
	$(function () {
		$(".starrr").starrr();
	});
</script>

Run the project now and you will be able to see all products stored in your database along with 5 stars to give ratings. Now you need to save ratings in ratings table when user click on submit button.

Save ratings

Our form creates a hidden input field where it is storing product ID, so now we first need to get the ratings and save those ratings in that particular product. This jQuery ratings plugin will return the value as an integer. You need to change the starrr() function to attach an change event that will be fired when user change his ratings and we will save that in a variable. Then we will attach an submit event in form and call an AJAX request and send the product ID and rating of user.

Creates a new file named save-ratings.php that will store the ratings in database. You can also store user ID if you have login & registration system in your website, by getting the user ID from session or from cookies. So make the following changes in your above code and it will be able to save ratings in database:

index.php

var ratings = 0;
$(function () {
	$(".starrr").starrr().on("starrr:change", function (event, value) {
		ratings = value;
	});
});

function saveRatings(form) {
	var product_id = form.product_id.value;

	$.ajax({
		url: "save-ratings.php",
		method: "POST",
		data: {
			"product_id": product_id,
			"ratings": ratings
		},
		success: function (response) {
			// whatever server echo, that will be displayed here in alert
			alert(response);
		}
	});

	return false;
}

save-ratings.php

<?php

$product_id = $_POST["product_id"];
$ratings = $_POST["ratings"];

$conn = mysqli_connect("localhost", "root", "", "tutorials");

mysqli_query($conn, "INSERT INTO ratings (product_id, ratings) VALUES ('$product_id', '$ratings')");

// whatever you echo here, will be displayed in alert on user side
echo "Saved";

Go ahead and give ratings to some products and check your ratings table in your database, you will see your ratings along with product ID. This is where you can store user ID too from session or cookies if you are using login or sign up features.

Display average rating

We are already creating a loop to display all products, this is where we will get all ratings of each product and calculate it’s average and display as stars. jQuery “starrr” ratings plugin also allows you to initialize the stars widget with an integer valule. So go ahead and paste the following code in your product’s while loop block:

while ($row = mysqli_fetch_object($result)) {

	// Getting ratings of current product using ID
	$result_ratings = mysqli_query($conn, "SELECT * FROM ratings WHERE product_id = '" . $row->id . "'");

	// Adding total ratings from each user
	$ratings = 0;
	while ($row_ratings = mysqli_fetch_object($result_ratings))
	{
		$ratings += $row_ratings->ratings;
	}

	// Calculating average from all ratings
	$average_ratings = 0;
    $ratings_count = mysqli_num_rows($result_ratings);
	if ($ratings_count > 0)
	{
		$average_ratings = $ratings / $ratings_count;
	}
?>

	<!-- This is where product stars will be displayed -->
	<!-- data-rating attribute will be used in Javascript below -->
	<div class="ratings" data-rating="<?php echo $average_ratings; ?>"></div>

	<!-- Product name and other fields -->

	<!-- Form goes here -->

<?php
	}
?>
	
<script>
	// Getting all div with ratings class
	var rating = document.getElementsByClassName("ratings");

	// Loop through all divs
	for (var a = 0; a < rating.length; a++)
	{

		// Display star on each div based on data-rating attribute value
		// readOnly will prevent the user changing it's value
		$(rating[a]).starrr({
			readOnly: true,
			rating: rating[a].getAttribute("data-rating")
		});
	}
<script>

That’s it, you have successfully added a star rating widget in your website. Everyone will be using this according to his project requirements and everyone will have different scenarios based on his needs. So if you have any problem, feel free to ask in the comments section below.

Another jQuery ratings plugin

You can also get the feedback from your users by displaying them emojis. User can select an emoji to describe his experience with your product or service. You can learn how to integrate that in your website from here.

Google Maps in PHP without API Key – By Coordinates & By Address

Demo

Google maps can be embedded in your website using PHP without providing API key. You just need to enter your address. Or you can enter coordinates, longiude and latitude.

Google Maps is a web mapping service developed by Google. It offers satellite imagery, aerial photography, street maps, 360° panoramic views of streets, real-time traffic conditions. Also, route planning for traveling by foot, car, bicycle and air, or public transportation.

By using the Google Maps API, it is possible to embed Google Maps into an external website, on to which site-specific data can be overlaid. Although initially only a JavaScript API, the Maps API was expanded to include an API for Adobe Flash applications. But this has been deprecated. Adobe Flash was a service for retrieving static map images, and web services for performing geocoding, generating driving directions, and obtaining elevation profiles. Over 1,000,000 web sites use the Google Maps API, making it the most heavily used web application development API. In September 2011, Google announced it would deprecate the Google Maps API for Flash.

As of 21 June 2018, Google increased the prices of the Maps API and requires a billing profile. But some people didn’t find themselve comfortable with providing their credit card information. Or they are just students who want to use Google Map services. So by following the below tutorial you will be able to show Google Map in your website without providing API key. You just need to enter either address or co-ordinates like latitude and longitude.

Google maps by address without API key

Create a simple form that will have an input field for entering address via input field. And a submit button which when clicked will submit the form.

<form method="POST">
	<p>
		<input type="text" name="address" placeholder="Enter address">
	</p>

	<input type="submit" name="submit_address">
</form>

Now we need to create a PHP block that will be executed when the form submits. In that block, we will get the address entered by user in a separate variable. Since address might have spaces so we will be converting those spaces into + sign. Lastly, we will create an iFrame tag to render the map. &output=embed is important since it tells the Google Map’s server that we are going to embed the map in an iFrame.

<?php
	if (isset($_POST["submit_address"]))
	{
		$address = $_POST["address"];
		$address = str_replace(" ", "+", $address);
		?>

		<iframe width="100%" height="500" src="https://maps.google.com/maps?q=<?php echo $address; ?>&output=embed"></iframe>

		<?php
	}
?>

Google maps by latitude and longitude without API key

Create a simple form that will have 2 input fields for entering latitude and longitude via input field. And a submit button which when clicked will submit the form.

<form method="POST">
	<p>
		<input type="text" name="latitude" placeholder="Enter latitude">
	</p>

	<p>
		<input type="text" name="longitude" placeholder="Enter longitude">
	</p>

	<input type="submit" name="submit_coordinates">
</form>

Now we need to create a PHP block that will be executed when the form submits. In that block, we will get the latitude and longitude co-ordinates entered by user in separate variables. Lastly, we will create an iFrame tag and pass those co-ordinates to render the map. Make sure to separate the values using comma (,).

<?php
	if (isset($_POST["submit_coordinates"]))
	{
		$latitude = $_POST["latitude"];
		$longitude = $_POST["longitude"];
		?>

		<iframe width="100%" height="500" src="https://maps.google.com/maps?q=<?php echo $latitude; ?>,<?php echo $longitude; ?>&output=embed"></iframe>

		<?php
	}
?>

Fetch user location in Javascript

If you want to fetch the user’s location in Javascript, you have to use Javascript Geolocation API. Just call the following function:

navigator.geolocation.getCurrentPosition(function (position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
});

It will return the latitude and longitude of the user that you can embed in iframe and it will render the map on the browser.

Note: Your browser will ask for permission to access your location. You need to allow it to return the co-ordinates.

Conclusion

Although it has some limitations, for example you cannot update the marker once the map is fully loaded. In order to change the location of marker, you can re-draw the map again. But it will give you enough functionality so that if you are receiving latitude and longitude of user’s location from some android/iOS application and you wanted to show that location on admin panel. You can easily do that by following this tutorial. That’s all for now, if you face any problem or need any help feel free to ask in the comments section below.

Realtime Web-based Chat in Firebase

Following this tutorial, you will be able to do realtime chat in Firebase in your website. We will be using Javascript in this tutorial.

Firebase

Firebase provides the ability to use non-relational database which means data will be stored in objects and arrays. It uses JSON format to save data in database. The structure of data is similar to as stored in Mongo DB where each table is known as collection. Each row is resembled with documents inside collection.

By default, Firebase provides 15 GB of data where you can store text, images and documents too. One of the biggest advantage of using Firebase is that it has built-in support for realtime notifications. That means that when a new item is added or removed it will automatically be notified in respective events. So Firebase ease the process of setting up Socket, Node JS and Mongo DB.

Firebase console

Goto Firebase Console and create a new project. Set the name of project and click “Continue”, you can disable the analytics for now. After that, click on “web” icon to integrate Javascript API in your project. Set the name of your project again and DO NOT set Firebase hosting. Because you will be running on your own localhost or hosting server. Then you will be displayed a code which you can copy and paste at the top of your project.

In your firebase console, goto “Database” tab from left menu and click on “Realtime Database”. For now, you can setup the database in test mode. The code you copied from Firebase console will only have firebase-app.js. But you will also need firebase-database.js in order to use database. We will be using file named “index.php” where all chat operations are performed. Below code has some empty values but when you copy from Firebase console then they will be filled automatically as per your project.

index.php

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js"></script>

<!-- include firebase database -->
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-database.js"></script>

<script>
	// Your web app's Firebase configuration
	var firebaseConfig = {
		apiKey: "",
		authDomain: "",
		databaseURL: "",
		projectId: "",
		storageBucket: "",
		messagingSenderId: "",
		appId: ""
	};
	// Initialize Firebase
	firebase.initializeApp(firebaseConfig);
</script>

Sending chat message in Firebase

Open your browser console by right click on empty area of page and select “Inspect Element” from context menu and open the “Console” tab. Make sure your internet is connected and check if there is any error. When it comes to sending message, for the sake of simplicity we will be saving username and message in the database. First we need to get the name of user when page opens. We can use Javascript built-in prompt() function to do that. Then we need to create a simple form with an input field to send message. When that form submits then we will call a function that will save the data in Firebase database.

The autocomplete field will make sure not to display old entered values in this field. At the end of sendMessage() make sure to return false. Otherwise the form will submits to itself and the page refreshed. firebase.database() will return an instance of Firebase database. You can either store it in a separate variable to re-use it or you can call it every-time you need to perform some action in database. When the data is saved then Firebase will fire an event that will be called when a new child is added. We will discuss that in details in next step.

The code below will create a new node named “messages”. It will give it a unique ID and save username and message in it. The nodes in database are called as “Childs” in Firebase database.

<script>
	// Your web app's Firebase configuration
	var firebaseConfig = {
		apiKey: "",
		authDomain: "",
		databaseURL: "",
		projectId: "",
		storageBucket: "",
		messagingSenderId: "",
		appId: ""
	};
	// Initialize Firebase
	firebase.initializeApp(firebaseConfig);

	var myName = prompt("Enter your name");
</script>
	
<!-- create a form to send message -->
<form onsubmit="return sendMessage();">
	<input id="message" placeholder="Enter message" autocomplete="off">

	<input type="submit">
</form>
	
<script>
	function sendMessage() {
		// get message
		var message = document.getElementById("message").value;

		// save in database
		firebase.database().ref("messages").push().set({
			"sender": myName,
			"message": message
		});

		// prevent form from submitting
		return false;
	}
</script>

Display messages from chat in Firebase

To display database data from Firebase we need to attach a listener called “child_added”. The main benefit of using this listener is that it simplifies the process of fetching the old messages from database. It is also used to listen to new incoming messages. So this event will be called in 2 situations.

  1. When the page loads it will get all messages saved in database.
  2. And second, when a new child is added in Firebase database.

Code below will create a list where all messages needs to be displayed and attach a listener which will be called automatically when the page loads. On each iteration it will return a snapshot object which is a Firebase database object and it contains child’s key and value.

On each iteration we are creating a new list and appending at the end of UL tag. As the child’s key is unique throughout the database, so we will be adding this as an ID to list item. This will be used when we try to delete message, it will be covered in detail in next step. We will be displaying delete button only if the message is sent from current user which means you can delete only those messages which are sent by you.

Button tag will have an attribute data-id which will be used to get the unique ID of message and an onclick event is attached which will be called when that button is pressed. At the end we are displaying sender’s name and message content.

<!-- create a list -->
<ul id="messages"></ul>
	
<script>
	// listen for incoming messages
	firebase.database().ref("messages").on("child_added", function (snapshot) {
		var html = "";
		// give each message a unique ID
		html += "<li id='message-" + snapshot.key + "'>";
		// show delete button if message is sent by me
		if (snapshot.val().sender == myName) {
			html += "<button data-id='" + snapshot.key + "' onclick='deleteMessage(this);'>";
				html += "Delete";
			html += "</button>";
		}
		html += snapshot.val().sender + ": " + snapshot.val().message;
		html += "</li>";

		document.getElementById("messages").innerHTML += html;
	});
</script>

Delete messages from chat in Firebase

Since we have already created a button to delete message, now we need to create a function that will be called when that button is pressed. We are going to delete the message from database and notify all other users that, that message has been removed. You can either remove that message node from list item or you can simply change the text of message to “This message has been removed” like WhatsApp does.

Next time you refresh the page, that message will be removed altogether. First we are getting the unique ID of message from the data-id attribute of button. Then we call the remove() function of Firebase instance and it will remove that message child from database. As soon as the child is removed, Firebase has an event named “child_removed” which will be called with deleted child key and value. So we are attaching that listener which will return the deleted child key and value which can be used to remove or alter that node from list item.

Now a delete button will be displayed along with your sent messages, when clicked it will be removed from Firebase database and a message will be displayed saying “This message has been removed”.

function deleteMessage(self) {
	// get message ID
	var messageId = self.getAttribute("data-id");

	// delete message
	firebase.database().ref("messages").child(messageId).remove();
}

// attach listener for delete message
firebase.database().ref("messages").on("child_removed", function (snapshot) {
	// remove message node
	document.getElementById("message-" + snapshot.key).innerHTML = "This message has been removed";
});

That’s how you can do real-time chat in Firebase using Javascript. If you do not want to use Firebase and do chat with your own server. You need to follow this tutorial.

Firebase Storage – Upload, Download, and Delete

Get YouTube channel videos, statistics and comments

You can get your YouTube channel statistics using YouTube Javascript SDK. You can also get comments of each video by providing its ID.

YouTube Data API allows you to get statistics from your YouTube channel. You can get all videos from your channel and you can get individual video detail. Video detail will contain video title, description, thumbnails, tags, views, likes, dislikes and comments. Comments section will include name of author, thumbnail image of user. Also, the comment he has posted and the time that comment was posted. Google provides an API which uses GET method to send requests and it can be used with Javascript and PHP.

YouTube channel statistics – Javascript SDK

When it comes with Javascript, you can use jQuery AJAX request to get the data. And when it comes to PHP, you can use built-in CURL method to send that request. Today, we will be using Javascript API to first list at-least 50 videos from your YouTube channel. Every video will have a button which when clicked will show the details of that video.

The detail of video includes video title, description, thumbnails, tags, published date, date when last time the video was updated. You can also get comments of individual video. You will get name of person who commented, his profile image, comment text and the date the comment was published.

Goto Google Developers Console and enable YouTube Data API. YouTube Data API is running on version 3 at the time of writing this. After that you need to get your API key which you can get from left menu. There was an option labeled as “Credentials”. You will see a list of all API keys already created and you use any old API key.

Create new API key

You can create a new API too by simply clicking the button at top right corner, it will be labeled as “Create Credentials”. Copy that API, we will need that later. Also goto youtube.com and click on your profile icon on top right and goto “My channel” and you can get your channel ID from URL, copy that too. Download jQuery from here and paste in your project folder. Create a file named “index.php” this will be the only file that we will be using in whole tutorial.

First you need to include jQuery in your file because we will be sending an AJAX request to call Google Api. To get videos you will need API key and your channel ID whose videos needs to be fetched. Replace variables apiKey and channelId with your API key and channel ID respectively. These will be send as parameter in the API along with some other parameters.

Part parameter specifies which fields needs to be fetched, here we wanted each video ID so that we can get it’s further details later and snippet will contain title which will be visible in the list. An ul list is created and all videos are appended in it with a clickable button which when clicked should send the video ID so we can get details of video using that ID.

index.php

<!-- include jquery -->
<script src="js/jquery.js"></script>

<ul id="videos"></ul>

<script>
	var apiKey = "";
	var channelId = "";

	var url = "https://www.googleapis.com/youtube/v3/search?key=" + apiKey + "&channelId=" + channelId + "&part=id,snippet&maxResults=50";

	// call ajax to get the videos
	$.ajax({
		url: url,
		method: "GET",
		success: function (response) {
			console.log(response);
			var html = "";

			for (var a = 0; a < response.items.length; a++) {
				html += "<li>";
					html += "<button onclick='videoSelected(this);' data-id='" + response.items[a].id.videoId + "'>";
						html += response.items[a].snippet.title;
					html += "<button>";
				html += "</li>";
			}

			$("#videos").html(html);
		}
	});
</script>

Now a list will be displayed with 50 videos from your channel with their title inside a button. When you click the video title it will call the function videoSelected and pass the clicked button as a parameter. As we have set an attribute data-id with video ID so we can get the video ID easily and display it’s details by sending another API request.

Get video detail

Now we can get each video ID separately and by sending another API request we can get it’s detail. This time we will be calling videos API from googleapis.com and sending the video ID as a parameter whose details needs to be fetched. We will be creating a separate div to show video detail. We will be displaying title, description, thumbnail, views, likes and dislikes but you can show other details too as per your needs.

Regarding the thumbnail you will have 4 options in quality of thumbnail image (low, normal, high, maximum resolution). Although it depends on the actual video thumbnail quality, if the video does not have maximum resolution quality thumbnail then only 3 fields will be returned.

index.php

<div id="video-detail"></div>

<script>
function videoSelected(self) {
	// get video ID
	var videoId = self.getAttribute("data-id");

	// call ajax to get video detail
	var url = "https://www.googleapis.com/youtube/v3/videos?key=" + apiKey + "&id=" + videoId + "&part=statistics,snippet";

	$.ajax({
		url: url,
		method: "GET",
		success: function (response) {
			console.log(response);
			var html = "";

			// display title
			html += "<p>" + response.items[0].snippet.title + "</p>";

			// description
			html += "<p>" + response.items[0].snippet.description + "</p>";

			// display thumbnail
			html += "<img src='" + response.items[0].snippet.thumbnails.maxres.url + "'>";

			html += "<p>Views: " + response.items[0].statistics.viewCount + ", Likes: " + response.items[0].statistics.likeCount + ", Dislikes: " + response.items[0].statistics.dislikeCount + "</p>";

			$("#video-detail").html(html);

			showComments(videoId);
		}
	});
}
</script>

Get video comments

Displaying comments require only video ID and API key in the parameters. Please keep that in mind that all API calls to googleapis.com requires an API key to be provided. Without that, even if everything else was provided correctly, data will not be returned from API. Here we are displaying name of person who commented along with his profile image and the comment that he has posted.

<ul id="comments"></ul>

<script>
function showComments(videoId) {
	var url = "https://www.googleapis.com/youtube/v3/commentThreads?key=" + apiKey + "&videoId=" + videoId + "&part=snippet&maxResults=50";

	// call ajax to get comments
	$.ajax({
		url: url,
		method: "GET",
		success: function (response) {
			console.log(response);
			var html = "";

			for (var a = 0; a < response.items.length; a++) {
				html += "<li>";
					// show image
					html += "<img src='" + response.items[a].snippet.topLevelComment.snippet.authorProfileImageUrl + "'>";

					html += response.items[a].snippet.topLevelComment.snippet.authorDisplayName;

					// comment text
					html += "<p>" + response.items[a].snippet.topLevelComment.snippet.textDisplay + "</p>";

					html += "<br>";
				html += "</li>";
			}

			$("#comments").html(html);
		}
	});
}
</script>

Conclusion – YouTube channel statistics

Since this post is about using YouTube Data API using Javascript but you can also use it in PHP, Node JS or any other language of your choice. As most of the programming languages today supports Http requests. The URL of API will remain same except the API key and channel ID (of course). If you are using Node JS then you can Express JS, if you are using PHP then you can use Curl module and so goes for other languages too.

Instagram feed without API – PHP, MySQL

[wpdm_package id=’172′]

Private user to user chat in Node JS & MySQL

Private chat does not mean that there is not any server between sender and receiver. There will always be a server in the middle of you and the person you are chatting with. That does not mean that they are spying on your data. It means that they are providing you a medium where you can send and receive messages from others.

It is cost effective since you do not have to pay or worry about the server. A realtime server could take a lot of physical space. It also needs to be air-cooled 24 hours a day, 7 days a week. Also, you need to maintain those servers time-to-time from any failure. You also have to consider all the possible attacks from hackers.

Node JS

Node JS is a Javascript based server that provides realtime event notifications. It is the first thing that came in the mind of developers when they have to develop a private chat. Or even group chat. When you use Facebook, you do not need to refresh the page to see new likes or comments. When you receive a new notification, it will automatically be displayed at the corner left of screen.

Here’s how it works, when you send a message an event will be sent to the server to notify that user. Server will receive that event and send the same event to that specific user. Every user will be listening from server for incoming events. Now, whenever that event received from server a notification will be displayed. You can download and install Node JS from it’s official site.

Setup the project

Create a new folder anywhere in your computer (Node JS can run in any directory). Open that folder in terminal by running command:

cd "path_to_folder"

If you have downloaded and installed Node JS in your computer, you can run the following command to initialize the project:

npm init

You will be asked a series of questions like author, name, description, version etc. You can press enter for all these fields. Then you need to install Express, Http and Socket IO modules. Run the following commands one by one:

npm install express http socket.io
npm install -g nodemon

You do not need to run the last command if you have already installed the “nodemon” module, it helps to keep the server running and the server will restart itself if any change has been made in the server file. The above commands will install the necessary modules to start the server. Next, you are going to need is to download jQuery and Socket IO JS. You can download jQuery from here and Socket IO from here.

Create a new folder named “JS” and paste these files there. Then create a file at the root of your project folder and named it “server.js”, this will be served as your server. Open that file and paste the following code into it:

server.js

// creating express instance
var express = require("express");
var app = express();

// creating http instance
var http = require("http").createServer(app);

// creating socket io instance
var io = require("socket.io")(http);

// start the server
http.listen(3000, function () {
	console.log("Server started");
});

To start the server, open back the terminal and run the following command:

nodemon server.js

This will keep the server running and whenever you make any changes in “server.js” it will automatically restarts itself.

Display connected users

For private chat, the user must select the person he wants to chat with. To do that, create a new file, which will served as a client, named “index.php”. Paste the following code in it:

index.php

<!-- include jquery and socket IO -->
<script src="js/jquery.js"></script>
<script src="js/socket.io.js"></script>

<script>
  // creating io instance
  var io = io("http://localhost:3000");

  var receiver = "";
  var sender = "";

</script>

server.js

io.on("connection", function (socket) {
	console.log("User connected", socket.id);
});

The client will connect with the server and the server will keep listening from the client. As soon as one client connected IO “connection” event will be fired and his socket will be created with a unique ID. Now create a form to enter username and that name will be sent along with each user’s message.

index.php

<form onsubmit="return enterName();">
  <input id="name" placeholder="Enter name">
  <input type="submit">
</form>

<ul id="users"></ul>
	
<script>
	function enterName() {
	    // get username
	    var name = document.getElementById("name").value;

	    // send it to server
	    io.emit("user_connected", name);

	    // save my name in global variable
	    sender = name;

	    // prevent the form from submitting
	    return false;
	}

	// listen from server
	io.on("user_connected", function (username) {
		var html = "";
		html += "<li><button onclick='onUserSelected(this.innerHTML);'>" + username + "</button></li>";

		document.getElementById("users").innerHTML += html;
	});

	function onUserSelected(username) {
	    // save selected user in global variable
	    receiver = username;
	  }
</script>

server.js

var users = [];

io.on("connection", function (socket) {
	console.log("User connected", socket.id);

	// attach incoming listener for new user
	socket.on("user_connected", function (username) {
		// save in array
		users[username] = socket.id;

		// socket ID will be used to send message to individual person

		// notify all connected clients
		io.emit("user_connected", username);
	});
});

Now a form will be displayed where you can enter your name. When form submits, a function named “enterName()” will be called which stored your entered name in a global variable and send an event to the server with that name. The server will listen that event from the client, a new array will be created which holds socket ID of each user identified by his username and send the same event to all connected clients.

Same event is also attached on client side which when called will create a button with username and append it into a list. When that button is pressed, then a function will be called which stores that person’s name in another global variable. These global variables will be used when sending the message.

Send private chat message to selected user

Select a person from the list and now if you open your browser console, you will be able to enter variable “receiver” and it will print out the selected username. Similarly, you can enter “sender” and it will print your name. To send a message you have to follow almost same steps as for displaying connected users.

Create a form, on submit send an event to server. Server will get that person’s socket ID from his username and send an event to that person only. Every user will be listening for that event, whenever that event is received, display the incoming message in a list. After sending message you have to append in the list too so you can see your own messages too.

index.php

<form onsubmit="return sendMessage();">
  <input id="message" placeholder="Enter message">
  <input type="submit">
</form>

<ul id="messages"></ul>
	
<script>
	function sendMessage() {
		// get message
		var message = document.getElementById("message").value;

		// send message to server
		io.emit("send_message", {
		  sender: sender,
		  receiver: receiver,
		  message: message
		});

		// append your own message
		var html = "";
		html += "<li>You said: " + message + "</li>";

		document.getElementById("messages").innerHTML += html;

		// prevent form from submitting
		return false;
	}

	// listen from server
	io.on("new_message", function (data) {
		var html = "";
		html += "<li>" + data.sender + " says: " + data.message + "</li>";

		document.getElementById("messages").innerHTML += html;
	});
</script>

server.js

// listen from client inside IO "connection" event
socket.on("send_message", function (data) {
	// send event to receiver
	var socketId = users[data.receiver];

	io.to(socketId).emit("new_message", data);
});

Open 2 browsers and choose different names for both browsers. Send a message from 1 browser to another and you will see new message on both browsers. You can see that you can chat with each other but when you refresh the page, all previous messages will be removed. That’s because we are not storing any message anywhere, they are just sent and received from one client to another.

When it comes to saving data, you have multiple choices. You can save data in relational database like MySQL, you can save in no-relational database like Mongo DB or you can save in files too in XML or JSON format.

Save messages in MySQL

Saving data in relational database is most easy and reliable among all mentioned above. So create a new database in your phpMyAdmin, you can select any name but for simplicity we have created a database named “web_chat”. Create a table named “messages” and it will have just 4 fields:

  1. ID INT AUTO INCREMENT
  2. sender TEXT
  3. receiver TEXT
  4. message TEXT

Now you need to install a module named “mysql” that will be used by Node JS server. So run the following command in your terminal:

npm install mysql

Don’t forget to start the server again after installing this module: “nodemon server.js”

To use this module in Node JS, first you have to create an instance of this module and create a connection with database. Finally you can connect with your database using connection object. So paste the following lines in your “server.js”:

server.js

// Create instance of mysql
var mysql = require("mysql");

// make a connection
var connection = mysql.createConnection({
	"host": "localhost",
	"user": "root",
	"password": "",
	"database": "web_chat"
});

// connect
connection.connect(function (error) {
	// show error if any
});

To insert a new row in “messages” table, paste the following code in your “send_message” event in “server.js”:

// listen from client
socket.on("send_message", function (data) {
	// send event to receiver
	var socketId = users[data.receiver];

	io.to(socketId).emit("new_message", data);

	// save in database
	connection.query("INSERT INTO messages (sender, receiver, message) VALUES ('" + data.sender + "', '" + data.receiver + "', '" + data.message + "')", function (error, result) {
		//
	});
});

If you try to send a message now, you will see that message in “messages” too. So the INSERT operation works, now we need to show all messages from previous chat when user selected.

Show previous private chat from database

In “index.php” change the “onUserSelected” function to the following:

function onUserSelected(username) {
    // save selected user in global variable
    receiver = username;

    // call an ajax
    $.ajax({
      url: "http://localhost:3000/get_messages",
      method: "POST",
      data: {
        sender: sender,
        receiver: receiver
      },
      success: function (response) {
        console.log(response);

        var messages = JSON.parse(response);
        var html = "";
        
        for (var a = 0; a < messages.length; a++) {
          html += "<li>" + messages[a].sender + " says: " + messages[a].message + "</li>";
        }

        // append in list
        document.getElementById("messages").innerHTML += html;
      }
    });
}

It sends an AJAX request to the server sending the “sender” and “receiver” names as POST parameters, the response received in JSON so the response is parsed in Javascript objects. All messages will looped and appended in the list in the same way as appending in “sendMessage” function or in “send_message” event. In order to setup AJAX requests with POST method on Node JS server, we have to install a module named “body-parser” and we have to tell the Express instance and we will be encoding the URL. So install this module by running the following command in your terminal:

npm install body-parser

server.js

// create body parser instance
var bodyParser = require("body-parser");

// enable URL encoded for POST requests
app.use(bodyParser.urlencoded());

// enable headers required for POST request
app.use(function (request, result, next) {
	result.setHeader("Access-Control-Allow-Origin", "*");
	next();
});

// create api to return all messages
app.post("/get_messages", function (request, result) {
	// get all messages from database
	connection.query("SELECT * FROM messages WHERE (sender = '" + request.body.sender + "' AND receiver = '" + request.body.receiver + "') OR (sender = '" + request.body.receiver + "' AND receiver = '" + request.body.sender + "')", function (error, messages) {
		// response will be in JSON
		result.end(JSON.stringify(messages));
	});
});

Headers will be used to allow your client to send AJAX requests. An API will be created that will fetch all previous messages between you and your selected user and send it back to client in JSON format. And your client is already parsing the JSON and displaying in a list so no need to make further changes in “index.php”.

Using MySQL with async/await

If you are planning to use async in MySQL module, you need to install the module named “mysql2/promise”.

npm install mysql2/promise

After installation, you can include it in your Node JS file.

const mysql = require("mysql2/promise")

const pool = mysql.createPool({
	host: "localhost",
	port: 3306,
	user: "root",
	password: "",
	database: "db_name"
})

const connection = await pool.getConnection()

const [rows, fields] = await connection.query("SELECT * FROM users")

Note: Make sure to make the function async before using await command.

If you want to run the INSERT query and return the ID of the newly inserted row, you can do that by the:

const [result] = await connection.query(`INSERT INTO users (name) VALUES ('Adnan')`)

if (result) {
	const userId = result.insertId
}

Go ahead and give it a free try, the design will not look good obviously, because we haven’t done anything on the design. But the functionality will be good enough for you to understand how private chat system works and how you can send message to specific user even when you have hundreds of users connected at the same time.

Realtime Web-based Chat in Firebase

Realtime Web-based Chat in Node JS & MySQL

We will create a simple and real-time chat module in Node JS and MySQL. We will be using socket IO for real-time communication.

Why chat in Node JS ?

Node JS is a web server that runs under the most famous and widely used programming language, Javascript. As Javascript is asynchronous, so Node JS server can fulfil client requests without having to wait for previous instruction to execute. Node JS runs in non-blocking event, which means that if there is any statement that takes too much time then Node JS will not get stuck at that point rather it will move to the next statement. Node JS can generate dynamic content of a website so user does not have to refresh the page in order to see updated data. This is very useful in realtime applications such as chat apps and google maps etc.

That is why most of the chat apps are developed in Node JS.

Node JS server runs on a single executable file, that file can include other multiple files too. But the server will be executing just the main file. Typically, that file named as “server.js” or “main.js” and that depends if you wanted to have different servers in same folder. That file will be executed just once and then will keep listening to incoming events, as soon it receives a new event it will send it back to other clients. Every time you run the Node JS file, all previous variables, arrays, objects will be destroyed. That is why it is recommended to store that data in some database.

Database for Node JS

When it comes to the database, Node JS has multiple options. You can use MySQL which is famous relational database structure and it is widely used in web development all over the world. Tech giants like Facebook uses MySQL as backend database. Or you can use Mongo DB which is a relation-less data structure, here data is stored in collections and documents. Collection will be name of entity and document is a single record exist in some collection. For example, you will have a collection of user and whenever a new user registered, a new document will be created inside this collection. It is much faster than MySQL.

Or you can use a file system where everything will be saved in file, it is the least recommended method but you can use this for exporting data in external formats. You can have .CSV format which is Comma Separated Values and this type of file usually gets opened in Microsoft Excel (Windows) or Numbers (Macintosh). Similarly, you can use JSON format to store data in files and this type of files holds data in forms of arrays and objects, they are typically used for statistics, for example:

{
    users: [
        { january: 123 },
        { february: 100 },
        { march: 114 },
        { april: 138 }
    ]
}

Installation and setup

First you need to download and install Node JS server in your system. You can download it from it’s official site. After installation, you need to create a folder anywhere in your system and create a file named “server.js”. Make sure the extension of file must be “.js” because the code will be in Javascript. Write the following simple line inside this file, it will show “Hello world !” when the server runs:

server.js

console.log("Hello world !");

Open terminal (CMD) and change the directory to your project folder (cd /path/to/project/). Run the following command in the terminal:

> npm init
> npm install -g nodemon

The first command will start your project folder as Node JS project and it will ask several questions like author (your) name, version etc. Just keep hitting enter if you wanted to skip these. Second command will install nodemon module globally in your system. This is helpful because nodemon allows you to make changes in server file without having to worry to restart the server. Whenever you made any changes in server file, nodemon will automatically restart the server. Otherwise, you have to restart it manually every time you make any change in server file. Now go ahead and run the following command in your terminal, make sure your project’s directory is opened in terminal:

nodemon server.js

When you run the above command, you will see a message saying “Hello world !”. Now install the Express and Http modules in your project by running the following commands, you may need to stop the nodemon running command by hitting Ctrl + C:

> npm install express
> npm install http

After installation you need to create an instance of these modules in your “server.js” file:

// use express
var express = require("express");

// create instance of express
var app = express();

// use http with instance of express
var http = require("http").createServer(app);

To start the server, call the listen function from http object and pass the port number as a parameter. Second parameter is a function that will be called when the server starts running:

// start the server
var port = 3000;
http.listen(port, function () {
    console.log("Listening to port " + port);
});

After pasting these lines in “server.js” you need to run “nodemon server.js” again in the terminal so that the server will keep running on this port.

Socket for incoming connections

Install socket module in your project by running the following command:

> npm install socket.io

And in your “server.js” create an instance of it:

// create socket instance with http
var io = require("socket.io")(http);

To receive incoming connections, you need to attach “connection” event listener on IO object:

// add listener for new connection
io.on("connection", function (socket) {
	// this is socket for each user
	console.log("User connected", socket.id);
});

Whenever a new user connects, this function will be called and we will get it’s socket object in the function argument. We can use the socket ID to send event to specific users. Following is a list of useful functions that you can perform using these IO and socket objects:

EventPurpose
socket.to(socket.id).emit(“name”, “value”)Sends the value to specific user.
io.emit(“name”, “value”)Sends the value to all connected users.
socket.emit(“name”, “value”)Sends the value back to the user who called this event.
socket.broadcast.emit(“name”, “value”)Sends the value to all users except the one who called this event.

Sending chat message event in Node JS

Download and save the socket.io.js file in your project, create a folder named “js” where all JS files will be saved. You can download socket IO from here. Create a file named “index.html” at the root of your project’s folder and include this socket file as Javascript.

<script src="js/socket.io.js"></script>

Then you need to create an instance of socket IO with the same port number as specified in “server.js”. Paste the following code in “index.html”:

<script>
    var server = "http://localhost:3000";
    var io = io(server);
</script>

When you run the index.html in your browser, you will see in your terminal a message for new user connection with a unique socket ID. Paste the following line in your “index.html” inside script tag, it will send the event to server:

// sending message from client
io.emit("new_message", "New message");

And paste the following line in “server.js”, it will receive the event sent from server. This line must be inside IO connection event:

// server should listen from each client via it's socket
socket.on("new_message", function (data) {
	console.log("Client says", data);
});

Run the “nodemon server.js” command again to start the server and refresh the index.html page in your browser and you will see “Client says New message” in your terminal. So now you can create a form where user will enter his desired message and upon hitting submit button, that event will be fired to server. Paste the following code in “index.html” file:

<form onsubmit="return sendMessage();">
	<input id="message" placeholder="Enter message">
	<input type="submit" value="Send">
</form>

<script>
function sendMessage() {
	// get message
	var message = document.getElementById("message");

	// sending message from client
	io.emit("new_message", message.value);

	// this will prevent the form from submitting
	return false;
}
</script>

Emit event to all connected users

Now if you refresh the index.html file, you will see a form with an input field to enter message and a button. Write any message you want and click send button and you will see that message in your terminal window. Now server needs to respond back to all users that a new message has been received. First send the message from server to all connected clients:

// change in server.js inside IO "connection" event
// server should listen from each client via it's socket
socket.on("new_message", function (data) {
	// server will send message to all connected clients
	// send same message back to all users
	io.emit("new_message", data);
});

It will send the same message back to all connected clients. Now all clients must be listening from server for that event, once that event is triggered from server then all clients will show the new message. Paste the following code in “index.html” inside script tag:

// client will listen from server
io.on("new_message", function (data) {
	console.log("Server says", data);
});

Now refresh the page and open a new browser window or you can use different browsers if you have multiple browsers installed in your computer. Then open both browsers side by side. Send message from 1 browser and you will see the message in console of other browser. You can open console by right clicking in empty area and selecting “Inspect Element” option. Create a <ul> tag to display all incoming messages in a list in “index.html”:

<!--list where all messages will be displayed-->
<ul id="messages"></ul>

And paste the following code in the “new_message” event in the “index.html” file:

// client will listen from server
io.on("new_message", function (data) {

    // display message
    console.log("Server says", data);
    
    // creates a new DOM element for li tag
    var li = document.createElement("li");

    // show message in li item
    li.innerHTML = data;

    // append the message at the end of list
    var messages = document.getElementById("messages");
    messages.appendChild(li);
});

Refreshing the page and you will be able to send message from a form and it will be display on the other browser in a list. Send multiple messages and all will be displayed at the end of list. When you refresh the page you will see an empty page because the server only listens to incoming messages. In order to see old messages you can either create an array or store all messages in database. Creating an array will remove all messages when the server restarted. So we are going to save in database.

Connect chat app in Node JS, with MySQL

First you need to install a module named mysql, stop the server and run the following command in your terminal. You can stop the server by pressing Ctrl + C.

npm install mysql

Make sure to run “nodemon server.js” again to start the server.

Create a database in your phpMyAdmin named “web_chat” and inside this database create a table named “messages”. This table can have only 2 fields just for the sake of simplicity, auto increment integer “id” and TEXT “message”. ID will be used when deleting the message. Your table structure should be . Create mysql module instance in “server.js” file and start a new connection with database:

// use mysql
var mysql = require("mysql");

// create connection
var connection = mysql.createConnection({
	host: "localhost",
	user: "root",
	password: "",
	database: "web_chat"
});

connection.connect(function (error) {
	// show error, if any
});

Save messages in MySQL

In “server.js” change the “new_message” event to save the incoming message in database before notifying to all other clients:

// server should listen from each client via it's socket
socket.on("new_message", function (data) {
	console.log("Client says", data);

	// save message in database
	connection.query("INSERT INTO messages (message) VALUES ('" + data + "')", function (error, result) {
		// server will send message to all connected clients
		io.emit("new_message", {
			id: result.insertId,
			message: data
		});
	});
});

This will save the incoming message in database and return the new row inserted ID which can be used to delete the message. Similarly, change your “new_message” event in “index.html” to display the message as:

li.innerHTML = data.message;

If you try to send a message now, you will see that message will also get saved in database table. Now you need to display all previous messages to a client when connected.

Reading messages from MySQL

Download and save the jquery.js file in your project’s js folder. You can download jQuery from it’s official site and include it in your “index.html” file.

<script src="js/jquery.js"></script>

Paste the following code anywhere in the script tag in “index.html”. It sends an API request to Node JS server and display all messages returned from server. Since the data returned from server will be in JSON string, so we have to convert it back to Javascript object by parsing.

$.ajax({
	url: server + "/get_messages",
	method: "GET",
	success: function (response) {
		console.log(response);

		var messages = document.getElementById("messages");

		// parse JSON to javascript object
		var data = JSON.parse(response);
		for (var a = 0; a < data.length; a++) {
			// creates new DOM element
			var li = document.createElement("li");

			// add message content as HTML
			li.innerHTML = data[a].message;

			// append at the end of list
			messages.appendChild(li);
		}
	}
});

Now in “server.js” you need to set header to allow API requests from unknown sources. Since you are testing it from localhost and that is not known for Node JS so you can add a header for “Access-Control-Allow-Origin” and allow all origins by setting it’s value to “*”. Paste the following code outside of IO “connection” event:

// add headers
app.use(function (request, result, next) {
	result.setHeader("Access-Control-Allow-Origin", "*");
	next();
});

next() is a callback function that will attach these headers with incoming API requests. And you need to create an API for “get_messages” that will return all the saved messages in database. Paste the following code in “server.js” outside of IO “connection” event:

// create API for get_message
app.get("/get_messages", function (request, result) {
	connection.query("SELECT * FROM messages", function (error, messages) {
		// return data will be in JSON format
		result.end(JSON.stringify(messages));
	});
});

Since “result.end” can only send string data in response, so you can convert your objects into JSON string and can parse this JSON string back to Javascript objects at client side. Refresh the page and now you will see all previous messages sent in this chat using Node JS API. If you send or receive a new message it will be appended at the end of same list and upon refreshing it will not be removed, because it will already get saved in database.

Delete message

If you have used WhatsApp then you probably know about the delete message feature. Your friend sends you a message and you saw it, then he deletes it and suddenly a message appeared to you “This message has been deleted”. This can be done via Node JS where deleting message from sender will make that message removed from all other users all of a sudden. First you need to create a delete button in 2 functions, when all messages are fetched from database and when a new message has been received. Change the for loop inside “get_messages” AJAX call in “index.html” file:

// give it unique id
li.id = "message-" + data[a].id;

li.innerHTML = data[a].message;

// add delete button
li.innerHTML += "<button data-id='" + data[a].id + "' onclick='deleteMessage(this);'>Delete</button>";

Above code should be pasted inside for loop before appending the child. In your “new_message” event in “index.html”, paste the following code before appending the child:

// same here
li.id = "message-" + data.id;

li.innerHTML = data.message;

// display delete button here too
li.innerHTML += "<button data-id='" + data.id + "' onclick='deleteMessage(this);'>Delete</button>";

Now inside your <script> tag create a new function that will get the message ID and send the delete event to the server with selected message ID:

function deleteMessage(self) {
	// get message id
	var id = self.getAttribute("data-id");

	// send event to server
	io.emit("delete_message", id);
}

In your “server.js” that event will be listened and delete the message from database. After deleting, an event will be sent to all users to remove that message from list. Paste the following code in your IO “connection” event:

// attach listener to server
socket.on("delete_message", function (messageId) {
	// delete from database
	connection.query("DELETE FROM messages WHERE id = '" + messageId + "'", function (error, result) {
		// send event to all users
		io.emit("delete_message", messageId);
	});
});

Now all clients must be listening continuously for delete event and you can remove that list item as soon as user receives that event. We are making it to show “This message has been deleted” similar to WhatsApp when delete event is received from server. So paste the following code in your “index.html” script tag:

// attach listener on client
io.on("delete_message", function (id) {
	// get node by id
	var node = document.getElementById("message-" + id);
	node.innerHTML = "This message has been deleted";
});

Refresh both browsers and try to send message from one browser to anther. You will see a delete button along with message text. When you click that button from one browser, that message will gets deleted from both browsers and instead you will see a message “This message has been deleted”.

Display name with message

At this point, when you send or receive a message you only see the content of message but you also wanted to know WHO sends that message. So first create a form where user can enter his name and then that name will be sent along with his message. In your “index.html” file before send message form, create a simple form like below:

<form method="POST" onsubmit="return setUsername();">
	<input type="text" autocomplete="off" id="username" placeholder="Enter username">
	<input type="submit" value="Select">
</form>

In the same file inside the <script> tag create a function that will create a global variable named “username”:

var username = "";

function setUsername() {
    username = $("#username").val();
	
    // this will prevent the form from submitting	
    return false;
}

Now change the “sendMessage” function to the following so that it will send the username along with message to the server:

function sendMessage() {
	// get message
	var message = document.getElementById("message");

	// sending message from client
    io.emit("new_message", {
        message: message.value,
        username: username
    });

	// this will prevent the form from submitting
	return false;
}

Now in “new_message” event in same file, change the line which append the message content in <li> tag to the following:

li.innerHTML = "" + data.username + ": " + data.message;

Same goes in “get_messages” AJAX call in “index.html”, change the line which append the message content in <li> tag to the following:

li.innerHTML = "" + data[a].username + ": " + data[a].message;

The above line will display the name of user in bold and message in normal style. You can save the username in messages table in database too by first creating a column named “username” and it’s value must be TEXT. Then in “server.js” inside IO “connection” event change the socket’s “new_message” to the following:

// server should listen from each client via it's socket
socket.on("new_message", function (data) {

    // save message in database
	connection.query("INSERT INTO messages(username, message) VALUES('" + data.username + "', '" + data.message + "')", function (error, result) {
		data.id = result.insertId;
		io.emit("new_message", data);
	});
});

Conclusion

Node JS plays a very important role in web development especially in realtime environment. Apart from just creating a chat app in Node JS, you can create a notification system where someone’s activity is monitored realtime by others, or maps that share realtime live location between friends etc. If you wanted to have the chat app in Node JS with the design as above, you can download all source files from the button below. Make sure you download them and let us know if you face any issue.

Single page application in MEVN stack – Realtime chat

Cookie – PHP

Cookie is used to enhance browsing experience by storing less sensitive data on user’s browser. It is used for many purposes. You can use cookies to know the person who requested some resource from your server, so you can identify him later. Or you can use cookies to reduce the number of requests on server.

For example you can store most of the data in your user’s browser so that when the user try to access it, it will not be fetched from your server but it will be fetched from user’s browser cookies. Cookies also play an important role in serving the cache mechanism which means the static data which is served to user once will not be fetched again from the server again. This mostly used for static data which does not change frequently, for example images, css and js files etc.

We are going to create a script that will allow you to add, view, edit and delete your browser’s cookies. We will be getting 3 inputs from user, cookie name, value and expiry time.

Save cookie – PHP

For layout and design, we will be using bootstrap as the most popular web design tool at the time of writing this. You can download bootstrap from it’s official site or you can get it from the source files which are attached at the end of this tutorial. Create a new file named index.php and paste the following code in it:

<!-- Include bootstrap -->
<link rel="stylesheet" href="bootstrap.min.css">

<!-- Create container -->
<div class="container" style="margin-top: 100px;">

	<div class="row">
		<div class="col-md-3">
			<!-- Create form -->
			<form method="POST" action="create-cookie.php">
				<!-- Create fields -->
				<div class="form-group">
					<label>Cookie name</label>
					<input name="cookie_name" class="form-control">
				</div>

				<div class="form-group">
					<label>Cookie value</label>
					<input name="cookie_value" class="form-control">
				</div>

				<!-- Create field to select cookie expiry time -->
				<div class="form-group">
					<label>Expire</label>
					<select name="sec" class="form-control">
						<option value="0">Sec</option>
						<?php for ($a = 1; $a <= 60; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="min" class="form-control">
						<option value="0">Min</option>
						<?php for ($a = 1; $a <= 60; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="hrs" class="form-control">
						<option value="0">Hrs</option>
						<?php for ($a = 1; $a <= 24; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="days" class="form-control">
						<option value="0">Days</option>
						<?php for ($a = 1; $a <= 90; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<input type="submit" class="btn btn-primary" value="Add Cookie">
			</form>
		</div>
	</div>
</div>

This will create a form with a input fields for selecting cookie name and cookie value. The form will also have 4 dropdown menus for selecting seconds, minutes, hours and days for expiring the cookie. You can select the time that after how many seconds or minutes or hours will this cookie be expired. If you do not select this time then depends on browser it will expire after a long time, typically after 90 days.

But you can change the expiry time of each cookie as per your requirements. We are setting the default value of expiry seconds, minutes, hours and days to zero so that if the user does not select any of the field then the default value will be zero. Now we need to process the form to create a cookie in your browser. So create a new file named create-cookie.php and paste the following code in it:

Processing the form

<?php

$cookie_name = $_POST["cookie_name"];
$cookie_value = $_POST["cookie_value"];

// Get expiry time
$sec = $_POST["sec"];
$min = $_POST["min"] * 60; // Convert minutes to seconds
$hrs = $_POST["hrs"] * 60 * 60; // Convert hours to seconds
$days = $_POST["days"] * 60 * 60 * 24; // Convert days into seconds

// Add all seconds
$expiry_time = $sec + $min + $hrs + $days;

// Add in current timestamp
$expire = time() + $expiry_time;

// Create an object
$data = array(
	"value" => $cookie_value,
	"expire" => $expire
);

// Save data in cookie in JSON format
setcookie($cookie_name, json_encode($data), $expire);

// Redirect back to home page
header("Location: index.php");

Get cookie – PHP

To read the cookies we need to first check if the browser has any cookies. Then we will loop through all cookies and it will return cookie’s key and value in each iteration. We will be displaying cookies in bootstrap table so go ahead and paste the following code below col-md-3 div in index.php file:

<div class="col-md-9">
	<!-- Check browser has any cookie -->
	<?php

		if (isset($_COOKIE)) {
	?>
	<!-- Create table -->

	<table class="table table-responsive">
		<!-- Heading of table -->
		<tr>
			<th>Name</th>
			<th>Value</th>
			<th>Expire</th>
			<th>Actions</th>
		</tr>

		<!-- Loop through all cookies -->
		<?php foreach ($_COOKIE as $key => $value) { ?>
			<?php
				// Decode cookie from json back to object
				$cookie = json_decode($_COOKIE[$key]);
			?>

			<tr>
				<td><?php echo $key; ?></td>

				<!-- Set td width -->
				<td style="max-width: 300px; overflow-x: scroll;">
					<!-- Show cookie value -->
					<?php
						echo isset($cookie->value) ? $cookie->value : $value;
					?>
				</td>

				<!-- Show expiry -->
				<td>
					<?php
						// Show expiry date in readable format
						echo isset($cookie->expire) ? date("Y-m-d H:i:s", $cookie->expire) : "";
					?>
				</td>

				<!-- Creating edit and delete button -->

				<td>
					<a class="btn btn-warning" href="edit-cookie.php?name=<?php echo $key; ?>">Edit</a>

					<a class="btn btn-danger" href="delete-cookie.php?name=<?php echo $key; ?>">Delete</a>
				</td>
			</tr>

		<?php } ?>
	</table>

	<?php } ?>
</div>

This will display the expiry date in readable format date() function is used to display the 2nd parameter timestamp in the format specified in 1st parameter. There are many formats available to display the date, the one used in this function are explained below:

YDisplay the year in 2009 this format.
mDisplay the month number, for example January as 1 and December as 12.
dDisplay the day number in month.
HThis will show the hour in 24 hour format, for example 1 PM will be displayed as 13:00.
iThe minute in the hour.
sThe second of minute.

Update cookies – PHP

Updating the cookies will require a simple form to be created with auto-populated values of selected cookie. We will be using same create-cookie.php page to update the cookies. Because the key of cookie will remains same. Create a new page named edit-cookie.php and paste the following code in it:

<!-- Include bootstrap -->
<link rel="stylesheet" href="bootstrap.min.css">

<?php

// Get cookie data
$key = $_GET["name"];
$cookie = json_decode($_COOKIE[$key]);

// Show value and name in form

?>

<!-- Create container -->
<div class="container" style="margin-top: 100px;">
	<div class="row">
		<div class="col-md-6 offset-md-3">
			<!-- Create form -->

			<!-- Form will submit on same page -->

			<form method="POST" action="create-cookie.php">
				<!-- Create fields -->
				<div class="form-group">
					<label>Cookie name</label>
					<input name="cookie_name" class="form-control" value="<?php echo $key; ?>">
				</div>

				<div class="form-group">
					<label>Cookie value</label>
					<input name="cookie_value" class="form-control" value="<?php echo $cookie->value; ?>">
				</div>

				<!-- Create field to select cookie expiry time -->
				<div class="form-group">
					<label>Expire</label>
					<select name="sec" class="form-control">
						<option value="0">Sec</option>
						<?php for ($a = 1; $a <= 60; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="min" class="form-control">
						<option value="0">Min</option>
						<?php for ($a = 1; $a <= 60; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="hrs" class="form-control">
						<option value="0">Hrs</option>
						<?php for ($a = 1; $a <= 24; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>

					<select name="days" class="form-control">
						<option value="0">Days</option>
						<?php for ($a = 1; $a <= 90; $a++) { ?>
							<option value="<?php echo $a; ?>">
								<?php echo $a; ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<input type="submit" class="btn btn-warning" value="Edit Cookie">
			</form>
		</div>
	</div>
</div>

The code is mostly same as index.php page, only change is first we are getting the selected cookie from URL and populating it’s data in “cookie_value” field. The form will be redirected to create-cookie.php and it will execute the same code to update the cookie name, value and expiry date.

Remove cookie – PHP

Deleting the cookies is the most simplest part in this script. We need to get the cookie’s key from URL and will set the value to empty string. To delete the cookie, we need to set the expiry time in the past.

<?php

// Getting cookie name
$name = $_GET["name"];

// Setting cookie expire time in past will remove that cookie
setcookie($name, "", time() - 3600);

// Redirect back
header("Location: index.php");

We are setting the expiry time before 1 hour which will be enough. It will redirect you back to main page and now you will see that selected cookie will be removed. Removing it may logged you out from some sites which uses cookies. Cookies can also be accessed from Javascript so you must not save sensitive data like passwords in cookies. In javascript, cookies can be accessed by document.cookie you can write that in your browser’s console window and it will display all the cookies that has been stored in your browser.

That’s all for now. I have also attached all the source files below, make sure you download them and let us know if you face any issue.

Learn how to create a shopping cart using cookies in PHP.

[wpdm_package id=’164′]

Add overlay or watermark on video – PHP & FFmpeg

In this article, we will be using FFmpeg tool with PHP to add watermark on a video.

Watermark on video

Watermark (also known as overlay image) is an image that displays in a specific position throughout the video. It is important to display your brand logo along with your video. Also it serves as a material that this content has been provided by your brand. If you have ever used Microsoft Word, then you would probably be aware of what watermark is. In MS Word, you can display watermark in diagonal or horizontal format. That type of watermarks are used for documents only.

In terms of video, you cannot display this on whole video. So you need an image of lower resolution then your video so it can be placed in somewhere inside the video. Also, you need to position the overlay image in a proper location. The position of image should be so that user must not get distracted from your actual video. The recommended positions are either top left, right or bottom left or right.

FFmpeg

You need to download and install FFmpeg in your system. After installation, you can also add it in your environmental PATH variable. We are going to create a PHP script that will input 2 files from user, one video where watermark should be placed and second is the overlay image which will be placed throughout the video.

Creating layout

Create a file named index.php in your htdocs or www folder if you are using XAMPP or WAMP respectively. If you already have a live site with domain and hosting, you need to connect with your server using SSH and run all the commands at the root of your project. Also mare sure you have set the folder permission to read and write, otherwise FFmpeg will not be able to create a new video with overlay image. Paste the following code in index.php file:

<link rel="stylesheet" type="text/css" href="bootstrap.min.css">

<div class="container" style="margin-top: 100px;">
	<div class="row">
		<div class="offset-md-3">
			
			<!-- creating the form -->
			<!-- apply encoding type to process file -->
			<form method="POST" action="add-overlay.php" enctype="multipart/form-data">
				
				<!-- creating video input file -->
				<div class="form-group">
					<label>Select video</label>
					<input type="file" name="video" class="form-control">
				</div>

				<!-- creating image input file -->
				<div class="form-group">
					<label>Select image</label>
					<input type="file" name="image" class="form-control">
				</div>

				<!-- create submit button -->
				<input type="submit" class="btn btn-primary" value="Add overlay">

			</form>

		</div>
	</div>
</div>

Add overlay image to video

Now we need to process the form i.e. to add selected image as overlay to selected video file and save the output as new file with same video and audio quality. The process involves 2 steps, first, as the selected image could be a very high quality image with very high resolution. So we need to resize the image to resolution without decreasing the quality. Secondly we will apply that resized image as overlay to video. Create a new file named “add-overlay.php” or same as action attribute in <form> tag. Paste the following code in newly created add-overlay.php file:

<?php

// first you have to get both input files in separate variables
$video = $_FILES["video"]["name"];
$image = $_FILES["image"]["name"];

// then you have to resize the selected image to lower resolution
$command = "/usr/local/bin/ffmpeg -i " . $image . " -s 128x128 output.jpeg";

// execute that command
system($command);

echo "Overlay has been resized";

// both input files has been selected
$command = "/usr/local/bin/ffmpeg -i " . $video . " -i output.jpeg";

// now apply the filter to select both files
// it must enclose in double quotes
// [0:v] means first input which is video
// [1:v] means second input which is resized image
$command .= " -filter_complex \"[0:v][1:v]";

// now we need to tell the position of overlay in video
$command .= " overlay=80:50\""; // closing double quotes

// save in a separate output file
$command .= " -c:a copy output.mp4";

// execute the command
system($command);

echo "Overlay has been added";

?>

Explore what more you can do with FFmpeg.

Generate thumbnails of video – PHP & FFmpeg

In this tutorial, we will be creating a script in PHP and FFmpeg. We will provide a video to our script. And our script will generate thumbnails of that video after regular intervals.

Thumbnails of video

Thumbnail is just a preview of a video so user can see what’s inside the video before playing it. You can show single image as a thumbnail, or you can show a GIF image which is a series of multiple frames. The video which has a GIF thumbnail allows you to hover your mouse over the video to play the GIF. The first frame will be seen as a static image. You can generate a list of thumbnails from any video or you can create just one.

Get single thumbnail

If you wanted to get just 1 image from video (also known as screen capture) you need to tell the time duration from where to capture the screen. For example, you need to tell the time in this format (hh:mm:ss). But if you wanted to generate multiple images of video, like YouTube and Facebook does, you need to tell the frame interval. You can tell to capture image every 60 seconds, for example. When you upload any video on YouTube, by default it generates 3 images from the video. Similarly Facebook generates 10 images when you upload the video.

What we are going to do in this post ?

In this tutorial, we will be creating a similar script that will generate thumbnails from video and save them as separate files. In order to generate thumbnails from video, you must have FFmpeg installed in your system. You can download it from it’s official site. We are creating a form that will allow you to select video whose thumbnail needs to be generated.

Creating layout

<link rel="stylesheet" href="bootstrap-darkly.min.css">

<div class="container" style="margin-top: 200px;">
	<div class="offset-md-4 col-md-4">
		<form method="POST" enctype="multipart/form-data" action="generate-thumbnail.php">
			<div class="form-group">
				<label>Select video</label>
				<input type="file" name="video" accept="video/*" class="form-control" required>
			</div>

			<input type="submit" class="btn btn-primary" value="Generate">
		</form>
	</div>
</div>

Generating thumbnails of video

At this point if you run the script, you will see a form with 1 input field which allows you to select the video whose thumbnails needs to be generated and a submit button. Now you need to create a new file named “generate-thumbnail.php” and paste the following code in it:

<?php

$video = $_FILES["video"]["name"];

$command = "/usr/local/bin/ffmpeg -i " . $video . " -vf fps=1/60 thumbnail-%03d.png";
system($command);

echo "Thumbnail has been generated";

Now you can run the script and you will see a form with an input field from where you will be able to select the video from your computer. After selecting the video file when you hit the submit button, you will see several new image files will be created at the root of your project’s folder with a prefix thumbnail-“. The time required to process the video and generate thumbnails depends on the length and quality of video. The videos of larger length and of high quality will take longer to process than the one in shorter length.

php.ini

When uploading large files, php.ini plays an important role either you are working on localhost or on live server. Mostly it is located in your XAMPP “etc” folder if you are using Linux or Mac, or if your site is live on server. If you are using Windows OS, then it will be in your XAMPP “php” folder. You may need to change some of the settings to allow the user to upload larger files. Search “upload_max_filesize=128M” in your php.ini file and change it’s value to 512M or 1GB or any other size you want. In same php.ini file, you may need to search for “post_max_size=128M” and increase it’s value too.

That’s all for now. I have also attached all the source files below, make sure you download them and let us know if you face any issue.

There is more in PHP & FFmpeg

Add thumbnail to video – PHP & FFmpeg

[wpdm_package id=’160′]