AlphalogicZ

  • Home
  • Services
  • Work
  • Blogs
  • Contact
  • Home
  • Posts tagged "PHP Programming"
May 16, 2025

Tag: PHP Programming

How To Set Up Password Authentication with Apache on Ubuntu 14.04

Thursday, 07 October 2021 by AlphalogicZ

When setting up a web server, there are often sections of the site that you wish to restrict access to. Web applications often provide their own authentication and authorization methods.

To get started, you will need access to an Ubuntu 14.04 server environment. You will need a non-root user with sudo privileges in order to perform administrative tasks.

Install the Apache Utilities Package

In order to create the file that will store the passwords needed to access our restricted content, we will use a utility called htpasswd. This is found in the apache2-utils package within the Ubuntu repositories.

Update the local package cache and install the package by typing this command.

$ sudo apt-get update

$ sudo apt-get install apache2 apache2-utils

Create the Password File

We now have access to the htpasswd command. We can use this to create a password file that Apache can use to authenticate users. We will create a hidden file for this purpose called .htpasswd within our /etc/apache2 configuration directory.

The first time we use this utility, we need to add the -c option to create the specified file. We specify a username (sammy in this example)

$ sudo htpasswd -c /etc/apache2/.htpasswd sammy

You will be asked to supply and confirm a password for the user.

Leave out the -c argument for any additional users you wish to add:

$ sudo htpasswd /etc/apache2/.htpasswd another_user

If we view the contents of the file, we can see the username and the encrypted password for each record:

$ cat /etc/apache2/.htpasswd
Output

sammy:$apr1$lzxsIfXG$tmCvCfb49vpPFwKGVsuYz.
another_user:$apr1$p1E9MeAf$kiAhneUwr.MhAE2kKGYHK.

Configure Apache Password Authentication

Now that we have a file with our users and passwords in a format that Apache can read, we need to configure Apache to check this file before serving our protected content.

Now we have to edit the Apache configuration and add our password protection to the virtual host file. This will generally give better performance

If you do not have the ability to modify the virtual host file (or if you are already using .htaccess files for other purposes), you can restrict access using an.htaccessfile. Apache uses.htaccess` files in order to allow certain configuration items to be set within a file in a content directory. The disadvantage is that Apache has to re-read these files on every request that involves the directory

Configuring Access Control within the Virtual Host Definition

Begin by opening up the virtual host file that you wish to add a restriction to. For our example, we’ll be using the 000-default.conf file that holds the default virtual host installed through Ubuntu’s apache package:

$ sudo nano /etc/apache2/sites-enabled/000-default.conf

Inside, with the comments stripped, the file should look similar to this: “/etc/apache2/sites-enabled/000-default.conf”

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Authentication is done on a per-directory basis. To set up authentication, you will need to target the directory you wish to restrict with a <Directory ___> block.

we’ll restrict the entire document root, but you can modify this listing to only target a specific directory within the web space: “/etc/apache2/sites-enabled/000-default.conf”

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <Directory "/var/www/html">
    </Directory>
</VirtualHost>

Within this directory block, specify that we wish to set up Basic authentication. For the AuthName, choose a realm name that will be displayed to the user when prompting for credentials. Use the AuthUserFile directive to point Apache to the password file we created.

Finally, we will require a valid-user to access this resource, which means anyone who can verify their identity with a password will be allowed in: “/etc/apache2/sites-enabled/000-default.conf”

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <Directory "/var/www/html">
        AuthType Basic
        AuthName "Restricted Content"
        AuthUserFile /etc/apache2/.htpasswd
        Require valid-user
    </Directory>
</VirtualHost>

Save and close the file when you are finished. Restart Apache to implement your password policy:

$ sudo service apache2 restart

Configuring Access Control with .htaccess Files

If you wish to set up password protection using .htaccess files instead, you should begin by editing the main Apache configuration file to allow .htaccess files:

$ sudo nano /etc/apache2/apache2.conf

Find the <Directory> block for the /var/www directory that holds the document root. Turn on .htaccess processing by changing the AllowOverride directive within that block from “None” to “All”: “/etc/apache2/apache2.conf”

...
<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
...

Save and close the file when you are finished.

Next, we need to add an .htaccess file to the directory we wish to restrict. In our demonstration, we’ll restrict the entire document root (the entire website) which is based at /var/www/html, but you can place this file in any directory you wish to restrict access to:

$ sudo nano /var/www/html/.htaccess

Within this file, specify that we wish to set up Basic authentication. For the AuthName, choose a realm name that will be displayed to the user when prompting for credentials. Use the AuthUserFile directive to point Apache to the password file we created. Finally, we will require a valid-user to access this resource, which means anyone who can verify their identity with a password will be allowed in: “/var/www/html/.htaccess”

AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user

Save and close the file. Restart the web server to password protect all content in or below the directory with the .htaccess file:

$ sudo service apache2 restart

Confirm the Password Authentication

To confirm that your content is protected, try to access your restricted content in a web browser. You should be presented with a username and password prompt that looks like this:

If you enter the correct credentials, you will be allowed to access the content. If you enter the wrong credentials or hit “Cancel”, you will see the “Unauthorized” error page:

CodingPHPPHP ProgrammingServerUbuntu
Read more
  • Published in Apache, PHP Programming, Server, Ubuntu
No Comments

Apache, non-WWW to WWW (HTTPS/Secure)

Thursday, 30 September 2021 by AlphalogicZ

Here is my “normal” config file and just “gets the task done”.

Here’s my Updated File

<IfModule mod_ssl.c>
  <VirtualHost *:443>
    ServerAdmin admin@domain.co.uk

    ServerName www.domain.co.uk
    ServerAlias domain.co.uk

    DocumentRoot /var/www/html/domain

    <Directory /var/www/html/domain/>
      Options FollowSymLinks
      AllowOverride All
      Require all granted

      # Redirect non-www to www
      RewriteEngine On

      RewriteCond %{HTTP_HOST} !^www\. [NC]
      RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile /etc/letsencrypt/live/domain.co.uk/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/domain.co.uk/privkey.pem
  </VirtualHost>
</IfModule>

Where I have got the “Redirect non-www to www are the few lines where I have tried to make the changes done.

CodingPHPPHP ProgrammingServerUbuntu
Read more
  • Published in Apache, PHP Programming, Server, Ubuntu
No Comments

How to set Timezone in Laravel

Thursday, 19 August 2021 by AlphalogicZ

An easy way to set a timezone for a user in your application and then show date/times to them in their local timezone.

You can set your app time zone by configuring app.php file in config folder.

  1. Open the file app.php located in config directory in your project. Check for Application Timezone where default time zone will be set as,

Here you can add your time zone as below,

This is the time zone for paris

'timezone' => 'Europe/Paris',

This is the time zone for India

'timezone' => 'Asia/Kolkata',

After changing app.php, make sure you run below command,

php artisan config:clear

How to change time zone in .env file

Here you can add your timezone like.

'timezone' => env('APP_TIMEZONE', 'UTC'),
APP_TIMEZONE='Europe/Paris'
CodingLaravelPHPPHP ProgrammingProgramming Language
Read more
  • Published in PHP Programming
No Comments

Write Clean and Secure PHP Code

Tuesday, 15 September 2020 by AlphalogicZ

I’m reading Clean Code, a technical book which is trying to explain to us what is the difference between Good and Bad code. Any code when written in a clean, easy to understand and formatted way is readily accepted and acclaimed by one and all. It is essential that the codes we write should be able to be understood by all.

1. Avoid Unwanted Html Tags In The PHP Code:

For Example:

<?php
echo "<table>";
echo “<tr>”;
echo “<td>”;
echo “Hai welcome to php”;
echo “</td>”;
echo </tr>”;
echo “</table>”;
?>

Use this:

<html>
<body>
<table>
<tr>
<td><?php echo "Hai welcome to php"; ?></td>
</tr>
</body>
</html>

2. Avoid Unwanted if condition:

For Example :

if (condition) {
  code to be executed if this condition is true;
} elseif (condition) {
  code to be executed if first condition is false and this condition is true;
} elseif (condition) {
  code to be executed if first condition is false and this condition is true;
} elseif (condition) {
  code to be executed if first condition is false and this condition is true;
} else {
  code to be executed if all conditions are false;
}

Use Switch:

switch (n) {
  case label1:
    code to be executed if n=label1;
    break;
  case label2:
    code to be executed if n=label2;
    break;
  case label3:
    code to be executed if n=label3;
    break;
    ...
  default:
    code to be executed if n is different from all labels;
}

3. Clear Code With In Assigning Values To Mysql Arguments:

For Example :

$sql="select first_name,last_name,email_address from tbl_user where user_id=".$user_id." and member_type='".$member_type."'";

mysql_query($sql);

Use This :

$sql="select first_name,last_name,email_address from tbl_user where user_id="%d" and member_type='"%s"'";

mysql_query(sprintf($sql,$user_id,$member_type));

4. Avoid using many foreach loop:

For Example:

$users = Select * FROM 'users';

$id = [];
foreach($users as $user){
  $id[] = $user->id;
}

$data = [];
foreach($id as $s_id){
  $data[] = select * FROM 'bookings' where 'user_id' = $id;
}

Use This:


$users = Select * FROM 'users' pluck 'id';

$data[] = select * FROM 'bookings' wherein 'user_id' = $users;

5. Avoid using For loop use While loop:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

while (condition) {
  // code block to be executed
}
CodingPHPPHP ProgrammingProgramming LanguageWordpress
Read more
  • Published in PHP Programming
No Comments

Categories

  • Apache
  • PHP Programming
  • Server
  • Ubuntu

Recent Posts

  • How To Set Up Password Authentication with Apache on Ubuntu 14.04

    When setting up a web server, there are often s...
  • Apache, non-WWW to WWW (HTTPS/Secure)

    Here is my “normal” config file and just “gets ...
  • How to set Timezone in Laravel

    Open the file app.php file present in config di...
  • Write Clean and Secure PHP Code

    I’m reading Clean Code, a technical book which ...

Archives

  • October 2021
  • September 2021
  • August 2021
  • September 2020

Pages

  • Blogs
  • Contact
  • home
  • Services
  • test-blog
  • Work
TOP