Manage website using Git – Shared, VPS, Dedicated

In this article, you will learn how you can manage your website, hosted on Shared, VPS, or dedicated server, using Git version control.

Video tutorial:

This tutorial works for all Shared, VPS, and dedicated hosting servers.

I have created a simple “Hello world” PHP file.

<?php

echo "Hello world";

I have created a sub-domain and Git repo on my shared hosting. You can check it from the video above.

Once a Git repo is created, it will give you an SSH path. I am going to open CMD in my folder and initialize Git in it.

cd "my-project-folder"
git init
git remote add origin ssh://adnantech@adnan-tech.com/home2/adnantech/git.adnan-tech.com
git status
git add .
git commit -m "Initial commit."
git push origin master

It will ask for your username and password. You can enter the credentials you use to log in to your hosting server.

If you receive the following error:

fatal: bad config value for ‘receive.denycurrentbranch’ in config

You can fix it by first accessing SSH from your terminal: (make sure to replace it with your username and IP address)

ssh -p 2222 adnantech@162.241.216.155

It will again ask for your password. Once the password is entered, you will be entered into the SSH terminal.

Once inside the SSH terminal, enter the following command:

which git-receive-pack

It will return the path of your Git receive pack. Copy it. Then push the code using the following command:

git push origin master -u --exec=your_git_receive_pack

Replace “your_git_receive_pack” with your Git receive-pack returned from the previous command.

I am going to make some changes in my code.

<?php

echo "Hello world of programming...";

Then I am going to push again.

git add -A
git commit -m "Changes made."
git push origin master -u --exec=your_git_receive_pack

You will now see updated code pushed to your website.

So that’s it. That’s how you can manage your shared, VPS, or dedicated server’s website code using Git.

You can watch the video if you are having problems following the article.

If you still face any issues with this, you can let me know.

More: Learn how to deploy Node JS app on VPS or dedicated hosting.

How to free up space in Mac

In this article, we will show you how you can free up some space in your Mac. If you are running low on space, this is for you.

My Mac was running on 5-6 GB and it keeps getting lower as I work more. So I did the following actions and now my Mac has 37 GB of free space.

1. Goto “home”.

2. Enable hidden files by pressing Command + shift + dot

3. If you do not do iOS development, then it is safe to remove the “.cocoapods” folder.

4. After that, you need to check each folder and see if there is any cache folder in it. You can safely remove all cache folders inside each folder.

4. Then you need to go to “Library”.

5. Remove the “Caches” folder.

6. When you uninstall an app, its files remain there in the “Library” folder. So check all the apps/software that you have uninstalled or no longer use, and delete their folders too.

If you follow the above steps, it will free up a lot of space in your Mac.

Force HTTP requests to HTTPS using .htaccess

This article will show you how you can force your website’s HTTP requests to HTTPS using htaccess.

Video tutorial

What is htaccess ?

.htaccess is a file used for server configuration. It is used primarily for URL redirection, preventing access to specific files, etc.

Force HTTP requests to HTTPS using .htaccess

If you have a website that is by default loads on HTTP, then this article is for you.

First, you need to open your .htaccess file from the root of your project.

If you do not have .htaccess file at the root, you need to manually create it in your main folder. Make sure to add the “.” dot at the beginning.

Then you need to write the following re-write condition and rule at the end of your .htaccess file.

# Redirect all http traffic to https
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://adnan-tech.com/$1 [R,L]

By default, the HTTP server loads on port 80. So, we have set the condition to port 80. Whatever comes to port 80, will be passed to the re-write rule.

Our re-write rule says that whatever comes in the URL of this website, will be redirected to the HTTPS address.

  • ^ means the start of the string.
  • $ means the end of the string.
  • () parenthesis is used for grouping in the regular expression.
  • . means 0 or more characters.
  • * means any character.
  • $1 means the URL will be passed as an argument.
  • [R,L] means to prevent further execution of rewrite rules. Make sure it does not have any space.

So that’s how you can force HTTP requests to HTTPS using .htaccess. If you face any problems in following this, kindly do let me know.

Prevent file access URL – htaccess

In this tutorial, we will teach you how you can prevent file access from URL using htaccess. Laravel is one of the most secured PHP frameworks, only if it’s used correctly. It can also be a huge security leak if not utilized properly. One problem I saw with many websites is that they move to production without securing their .env file.

You can always download the latest version of laravel from Github.

This file holds your site’s sensitive information like database passwords, email credentials, API keys, etc. By default, this sensitive information can easily be viewed by accessing the following URL:

https://your_domain/.env

If you see the content of your .env file, it clearly means that your website is open to hackers. To prevent this, open your .htaccess file and add the following highlighted code:

<IfModule mod_rewrite.c>

    <FilesMatch .env|.env.example>
        order allow,deny
        deny from all
    </FilesMatch>

    ...
</IfModule>

Now the .env file will be secured from the URL. You can refresh the page now and you will see a “403 Forbidden” error. So that’s how you can prevent direct file access from URL using htaccess.

Check out our social networking site project developed in Laravel.

Prevent form submit event from reloading the page

In this article, we are going to discuss 2 options that how you can prevent your HTML form submit event from reloading the page. Normally, when you submit the form, it redirects to the action attribute link. But you can stop that reload and call an AJAX or any other Javascript function.

1. preventDefault

You can call the preventDefault function on the event target and it will stop the form from redirecting to the page specified in the action attribute of the <form> tag.

<form method="POST" action="your-page.php" onsubmit="onFormSubmit();">
	<input type="submit" />
</form>

Then you can create the following Javascript function to prevent the page reload:

function onFormSubmit() {
	event.preventDefault();

	// your Javascript code here
}

In this method, the form is first prevented from submission and then your Javascript code will be run. So it prevents the form submit event first, then it will run our Javascript code which is a good approach.

You can learn more about preventDefault from here.

2. return false

The second approach is to use the return false statement in your Javascript code. For this, you also need to return the value from the onsubmit event function. Let’s check this out.

<form method="POST" action="your-page.php" onsubmit="return onFormSubmit();">
	<input type="submit" />
</form>

Then create your Javascript function as like that:

function onFormSubmit() {
	// your Javascript code here
	
	return false;
}

In this method, your Javascript code runs first before preventing the form submission.

Recommendation

We would recommend the 1st method i.e. preventDefault because it is the very first line of the Javascript function. So if there is an error in your Javascript code, your browser will not get reloaded and thus you will be able to view the error in the browser console.

Now that you have learned to prevent the form submit event. You can also display a pop-up for confirmation in case of the delete function. You can follow this tutorial to display a pop-up confirmation before submitting the form.

Password protect ZIP file in Mac OS X

In this article, we will show you how you can password protect your zip file in Mac OS X. To create a ZIP file and set the password to it using Mac, you simply need to follow the following steps:

  1. Open Terminal
  2. Open folder where target file is located by running the command:
    • cd “path of folder”
  3. Run the following command:
    • zip -er “my-file.zip” “target file or folder”
  4. It will ask password twice.

It may take longer for large files. You can then use the encrypted file on all iOS-based devices like Mac, iPhone, iPad, etc.

Learn how to password protect a ZIP file in PHP from this tutorial.

If you are a windows user, you can use the 7-zip software to password-protect the files.

Socket IO emit an event to specific users – Node JS

Introduction

Sockets are used for real-time communication. They are now being used in chat apps, team collaboration tools, and many more. Socket IO emit events to the receivers and the receivers are constantly listening to that event. When the event is received on the client-side, they can perform the necessary action. You can attach as many event listeners as you want and perform different actions for each event.

Users are connected with a Node JS server using a client-side library called Socket IO. Users can also join the room which will be helpful if you are creating a group chat app. There are 4 ways in which socket events are fired.

  1. Send event to all connected users, including the sender.
  2. Send event to all users, except the sender.
  3. Emit event to all users in a room.
  4. Send event to specific users.

In this tutorial, we will be covering the 4th part i.e. send socket events to specific users.

Video tutorial:

Problem

Suppose you have a chat app where you want 2 people to have a private chat. Now you want to have a real-time effect i.e. to show the new messages without having to refresh the page. This requires sockets that send the data in real-time. And we can show the data on the client-side in real-time too. Now when a sender sends a message to a specific user, we need to send the socket event to that specific user only.

Solution

We will create a simple script that allows us to send events to a specific user only. You can then integrate and customize that logic in your project. First, you need to download and install Node JS. You also need to download the Socket IO JS client-side library. We will have a simple database from where we can show all the users in a list, with a button to send an event to that user only. So we need to create a database with a simple users table, you can use your own database as well.

Database

In your phpMyAdmin, create a database named “send_socket_event_to_specific_users”. In that database, create a users table:

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` text NOT NULL
);

Add few rows in that table so we can show them in a list or a table.

INSERT INTO `users` (`id`, `name`) VALUES
(1, 'Adnan'),
(2, 'Afzal'),
(3, 'John'),
(4, 'Doe');

Then in your index.php, show all users.

<?php
	$conn = new PDO("mysql:host=localhost:3306;dbname=send_socket_event_to_specific_users", "root", "");
	$sql = "SELECT * FROM users";
	$result = $conn->prepare($sql);
	$result->execute([]);
	$users = $result->fetchAll();
?>

<table>
	<thead>
		<tr>
			<th>ID</th>
			<th>Name</th>
			<th>Action</th>
		</tr>
	</thead>

	<tbody>
		<?php foreach ($users as $user): ?>
			<tr>
				<td><?php echo $user['id']; ?></td>
				<td><?php echo $user['name']; ?></td>
				<td>
					<form method="POST" onsubmit="return sendEvent(this);">
						<input type="hidden" name="id" value="<?php echo $user['id']; ?>" required />
						<input type="submit" value="Send Message" />
					</form>
				</td>
			</tr>
		<?php endforeach; ?>
	</tbody>
</table>

It will show all users in a table with a button to send message. Now when the page loads, we need to get the ID of the user, you can also get it from PHP sessions.

Include Socket IO library

Before that, we need to include the Socket IO JS library. You can download it from here.

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

<script>
	var userId = prompt("Enter user ID");

	var socketIO = io("http://localhost:3000");
	socketIO.emit("connected", userId);
</script>

It will store your ID in userId variable. And it will connect with Node JS server and emit an event “connected” with your ID.

Now we need to create a simple Node server. Create an empty folder and create a file named “server.js” in it. Then open the CMD in that folder and run the following commands one-by-one:

npm init
npm install express http socket.io mysql
npm install -g nodemon
nodemon server.js

Write the following code in your server.js file:

var express = require("express");
var app = express();

var http = require("http").createServer(app);
var socketIO = require("socket.io")(http, {
	cors: {
		origin: "*"
	}
});

var users = [];

socketIO.on("connection", function (socket) {

	socket.on("connected", function (userId) {
		users[userId] = socket.id;
	});

    // socket.on("sendEvent") goes here
});

http.listen(process.env.PORT || 3000, function () {
	console.log("Server is started.");
});

This will start the server at port 3000, creates a users array and store all connected user’s socket ID in it.

Send event using socket IO emit function

Back in index.php, we need to create a JS function to send the event when the user click the “Send message” button:

function sendEvent(form) {
	event.preventDefault();

	var message = prompt("Enter message");
	socketIO.emit("sendEvent", {
		"myId": userId,
		"userId": form.id.value,
		"message": message
	});
}

Now in server.js, we need to listen to that event and send the message to that user only. But before that, we need to include mysql module because the user’s names are stored in mysql database. At the top of your server.js:

var mysql = require("mysql");
var connection = mysql.createConnection({
	host: "localhost",
	port: 3306,
	user: "root",
	password: "",
	database: "send_socket_event_to_specific_users"
});

connection.connect(function (error) {
	console.log("Database connected: " + error);
});

And after the socket connected event:

socket.on("sendEvent", async function (data) {
	connection.query("SELECT * FROM users WHERE id = " + data.userId, function (error, receiver) {
		if (receiver != null) {
			if (receiver.length > 0) {

				connection.query("SELECT * FROM users WHERE id = " + data.myId, function (error, sender) {
					if (sender.length > 0) {
						var message = "New message received from: " + sender[0].name + ". Message: " + data.message;
						socketIO.to(users[receiver[0].id]).emit("messageReceived", message);
					}
				});
			}
		}
	});
});

This will search the sender and receiver by ID, and emit the event to the receiver with the name of the sender.

Listen to socket IO events

Now we need to listen to that event in our index.php and show a message in a list when that event is received. First, create a ul where all messages will be displayed:

<ul id="messages"></ul>

Then attach that event in JS:

socketIO.on("messageReceived", function (data) {
	var html = "<li>" + data + "</li>";
	document.getElementById("messages").innerHTML = html + document.getElementById("messages").innerHTML;
});

So that’s how you can use the socket IO emit function to send the event to a specific user only.

Check out realtime chat app tutorial using socket IO.

[wpdm_package id=’1295′]

Prevent file access from URL – PHP htaccess

When developing a web application, it is very important for you to prevent file access from URL for the users. Because someone might try to download all your images and videos by directly accessing them from the URL. You must allow users to view the images and videos directly from your website instead of just letting the automated scripts download all uploaded data.

.htaccess

First, you need to create a file named “.htaccess” along with the dot “.” without the double quotes at the root folder of your project. Some operating systems hide the files that start with a dot extension.

  • In Windows, go to “view” from the top menu and check the “show hidden items” checkbox.
  • In Mac, press (command + shift + dot) (⌘ + ⇧ + .) at the same time.
  • In Ubuntu, press Ctrl + H.

Following should be the content of your .htaccess file:

# enable mod_rewrite
RewriteEngine On

# RewriteCond = define rule condition
# HTTP_REFERER = check from where the request originated
# ! = exclude
# ^ = start of string
# [NC] = case insensitive search
RewriteCond %{HTTP_REFERER} !^http://localhost:8888/tutorials/video-streaming-php [NC]

# \ = match any
# . = any character
# () = pattern, group
# $ = end of string

# [F] = forbidden, 403
# [L] = stop processing further rules
RewriteRule \.(gif|jpg|jpeg|png|mp4|mov|mkv|flv)$ - [F,L]

At line #9, you must place your website base URL without forwarding the slash “/” at the end. Using htaccess, you can also prevent “.env” files from accessing in your Laravel application. Follow this for more.

Access from code only

Now if you try to access the file directly from the URL, you will get a 403 Forbidden error. But you can easily access it from your code like this:

<video src="video.mp4" controls></video>

This prevent file access from the URL but you can still see it in the browser. However, the user can still manually download the video file. But it prevents the automated scripts to download all the files from your server directory.

Detect multiple tabs opened at the same time – Javascript

If you have used WhatsApp Web, you may encounter a situation where if you open the web.whatsapp.com in multiple tabs in the same browser, you will get the error that “it is already being opened in another tab”. So in this article, we are going to teach you how you can detect multiple tabs opened at the same time using vanilla Javascript.

This is done for various reasons, top of the most is security. So how you can add this feature to your website ? The following code will display an alert message if a 2nd tab is opened at the same time:

<script>
    // Broadcast that you're opening a page.
    localStorage.openpages = Date.now();
    window.addEventListener('storage', function (e) {
        if(e.key == "openpages") {
            // Listen if anybody else is opening the same page!
            localStorage.page_available = Date.now();
        }
        if(e.key == "page_available") {
            alert("One more page already open");
        }
    }, false);
</script>

window.addEventListener(‘storage’, function (e) {});” This listener will be called only when the local storage value is updated from an external source, which means the other tab has made any changes in the local storage.

[do_widget id=custom_html-4]

How it works:

You might need to read the following steps 2 or 3 times to grab the concept properly.

  1. When you open the 1st tab, line # 3 will create a local storage value named “openpages”.
  2. Storage listener will NOT be called because the local storage value is updated from this tab.
  3. When you open the second tab, line # 3 will also create a local storage value named “openpages”.
  4. Storage listener from the 1st tab will be called because the local storage is updated from the 2nd tab.
  5. 1st tab will receive the value of “e.key” as “openpages”.
  6. So it will create another local storage value “page_available” at line # 7.
  7. Now this will call the storage listener from the 2nd tab. Because for the 2nd tab, it is called from the 1st tab.
  8. 2nd tab will receive the value of “e.key” as “page_available”, so it will display an alert message.

That’s how you can detect multiple tabs opened by the user at the same time. Let me know if you have any problem understanding this.