Welcome to the Webmaster Blog and Portfolio of Darian Brown

Hello, my name is Darian Brown and this is my webmasters blog and portfolio.

It features tutorials, tips and code samples to help you create better websites and teach you techniques which can unlock your true potential to be a better web designer, webmaster and programmer.

I will be posting helpful tips, tutorials, techniques and code samples aimed at webmasters, designers and web developers. After being a webmaster for over 10 years, I am still lucky enough to be constantly challenged and learning every day. This has lead me to create this website which is a great way for me to share my experience with the world and give back to the community which has given me so much over the years read more…

Add Zone And Domain To DNS Bind Server – Also Includes A Sample DNS Domain Zone File

Overview

Welcome to the second of my DNS articles. It is more of a prequel to my first article in which I explained the steps in Creating A DNS Entry For A SubDomain.

This article assumes you have already installed bind and it is all running. If not, then you will need to setup bind first.

What is a DNS Zone?

My previously article explained what a zone is so I won’t go into to much detail here, but essentially a zone is the term used to describe a config file a specific domain/subdomain in your DNS server bearing in mind that a DNS server has multiple zones/domains associated to it. Each domain generally has its own zone file however in some situations, you can have multiple domains per zone file. For example, mydomain.com and mydomain.net and mydomain.org could all be in the same zone file as long as they all need to point to the same ip address.

Create the DNS zone file

The zone file we will create for this example will be for the domain example.com. The zone file will tell the DNS server which IP the domain should point to as well as configuring expiry and refresh times for the domain. Generally, the naming format for a zone file is db.example.com.conf where the domain in this case is example.com. Now to create the zone file and add the contents shown in the Sample DNS Domain Zone File

sudo vi /etc/bind/db.example.com.conf

Sample DNS Domain Zone File

In this sample DNS domain zone file, there are a couple changes you need to make to ensure it works in your situation. Firstly, change ns1.exampledns.com and ns2.exampledns.com with your own ns1 and ns2 dns servers. Secondly you can change example.com to the domain you are adding.

Optionally leave out $ORIGIN if you are adding multiple domains to a single zone file. The @ symbol simply means the current zone which is great for when you have multiple domains to a single zone file.

; Zone file for example.com
$TTL    3600
$ORIGIN example.com
@       IN      SOA     ns1.exampledns.com.    root.example.com. (
                     2012033101         ; Serial
                           3600         ; Refresh
                           1800         ; Retry
                         604800         ; Expire
                          43200 )       ; Negative Cache TTL

        IN      NS      ns1.exampledns.com.
        IN      NS      ns2.exampledns.com.

@       IN      A       192.168.0.2
www     IN      A       192.168.0.2

Now we add our new domain zone config file to our DNS server

Above we created the zone config file. Now we need to add the zone file to our dns config file which tells our DNS server that it should control and serve requests for this new domain zone.

Open your DNS config file and add a zone in for your domain. I will be using example.com in my example. Here the file is located under /etc/bind/named.conf.local however depending on the way your DNS server was configured, it may be under /etc/bind/named.conf.options or rarely even /etc/bind/named.conf

sudo vi /etc/bind/named.conf.local

Add a zone to your DNS config file

At the end of the file add an entry similar to the following

zone "example.com" {
	type master;
	file "/etc/bind/db.example.com.conf";
};

As you will see, the type of zone is a master zone. This means that it is the primary holder for dns information regarding this domain.

Creating A DNS Entry For A SubDomain – Add A DNS Entry Into Bind

Overview

Welcome to the first of a bunch of DNS articles I will write to help explain the different tasks needed to configure and manage your own DNS server using bind under Linux.

The article assumes you have already installed bind and it is all running. If not, then you will need to setup bind first.

What is a DNS Zone?

Essentially a zone in DNS terms is a collection of a domain with all its subdomains. Typically you will have one zone config file per domain (which including its subdomains) however you can also have multiple domains using a single zone file. If you have multiple domains to a zone file, each of those domains will be configured identically which includes the IP addresses and subdomains each of the entries point to. The zone file tells the DNS server what IP addresses are associated to each of the domains and subdomains. Each record in the zone file can also be configured to be any type of DNS record such as A record, MX record, TXT record, etc.

Editing a zone file

The zone files are located under /etc/bind/ and the zone files generally (but not always) are in the format of db.domain.com.conf. For example, my zone file for darian-brown.com is under:

/etc/bind/db.darian-brown.com.conf

So now we simply edit the zone file using vi or your preferred editor

sudo vi /etc/bind/db.darian-brown.com.conf

Adding a subdomain

In your zone file you will see a couple existing DNS records. You should see a section similar to this where 192.168.0.2 is the IP address on our internal network where these domains point to. The @ symbol simply means the current domain which in our case is darian-brown.com

@	IN	A	192.168.0.2
www	IN	A	192.168.0.2

Now we are going to add a subdomain called blog and point it to a different server. So we add the line after those two entries (or even at the bottom of the file) like so.

@	IN	A	192.168.0.2
www	IN	A	192.168.0.2
blog	IN	A	192.168.0.10

Now save the file and restart your bind service by running

sudo /etc/init.d/bind9 restart

Testing new subdomain

In order to test your new entry is working, you can dig the new address. See my article on What is Dig and When Should I use it for more information. Dig is a lot more informative and can be extremely useful as you can directly query your DNS server rather than waiting for the DNS to refresh.
An example of how to do would be

dig @ns1.mynameserver.com -t A blog.darian-brown.com

and if the DNS entry was added successfully, you should see a section in the response that is something like

;; ANSWER SECTION:
blog.darian-brown.com.	3600	IN	A	192.168.0.2

Alternately you can ping the subdomain using

ping blog.darian-brown.com

MySQL REPLACE Function – A MySQL Syntax Tip

Overview

MySQL replace is a function that allows you to replace a bit of text or numbers with another piece of text or numbers during a MySQL query. The best way to understand how a MySQL REPLACE Function works is to see it work as you will see in the example below.
The MySQL replace function works similar to how the PHP str_replace function works however the parameters are in different order.

 

Example 1 – SELECT and REPLACE

In this example, any results that have John as their first name will instead return Johnathon as their firstname and any other names will not be affected.

SELECT REPLACE(`firstname`,'John','Johnathon') AS firstname,lastname,age FROM userdatabase;

 

Example 2 – UPDATE and REPLACE

This will update and switch one bit of text with another. Here we are going to change some html and replace <i> tags with <em> tags.

UPDATE wp_posts SET post_content = REPLACE(post_content,'

Now all the italic html tags would have ben replace with emphasized tags.

Calculate Time Difference Between your Users And Your Server

People access your site aren’t always in the same timezone as you are. Now perhaps you would like to determine what the time is for a user in a different country. Then here is a quick way to find this information out.

This example is very useful if you simply want to fetch your clients date and time or timezone; but also good to see what time of day (their time, not server time) your clients access your website.

Now before I should you the code, remember that PHP is server side code – ie. it runs on the server and as such doesn’t have access to the clients local time. Javascript however is client side code which means it can see the localtime but the servers time. So a combination of the two will allow us to calculate the difference.

The way the below example works, is that the client will click a submit button which sets the value of the hidden input field to their local time stamp and that gets submitted to the same php script. Then the php script checks if that value has been sent and if it has, then it gets the local time (of the server) and takes the clients times and shows a message depicting the difference.

<!DOCTYPE html>
<html>
<head>
	<title>Server and Client Time Example</title>
</head>
<body>
	<script type='text/javascript'>

	// when we submit the form, get the client time and submit it as the
	// hidden field 'client_timestamp'
	function getClientTime() {
		var d = new Date();
		// we divide the timestamp by 1000 to go from milliseconds to seconds
		var timestamp = Math.floor(d.getTime()/1000);

		// put the timestamp into hidden field to be passed with the form
		document.getElementById('client_timestamp').value = timestamp;
	}

	</script>

	<form method='post' id='myform' onsubmit='getClientTime();'>
		<input type='hidden' id='client_timestamp' name='client_timestamp' />
		<button type='submit'>Send My Time</button>
	</form>

	<?php

	// if the form with the timestamp was submitted
	if( isset( $_REQUEST['client_timestamp'] ) ) {
		// the time posted to this script through the form
		$client_time = $_REQUEST['client_timestamp'];

		$server_time = time();

		$client_string = 'Your clients time is: ';
		$client_string .= date('d F Y h:i:s A',$client_time);

		$server_string = 'Your server time is: '
		$server_client .= date('d F Y h:i:s A',$server_time);

		// display the times
		echo $client_string.'<br />';
		echo $server_string.'<br />';
	}

	?>

</body>

</html>

GRANT’ing Privileges and Permissions To Users On A Database In MySQL

If you would like to add a user to MySQL and give them permissions to view on or multiple databases, then continue reading. It is a fairly simple process and can be very powerful in keeping your database secure as well as giving people the access to the database they need.

In order to run these sql commands (sql queries), login to your sql database First lets look at the structure.

mysql -u <user> -p

I recommend you don’t enter your password above as people viewing your .history would see your password. Once you hit enter you will be prompted to enter your password.

Now the structure of the grant appears as follows

GRANT <privilege-type> ON <database> TO <user>@`<ip-or-domain>` IDENTIFIED BY '<new-password>'

So, here is the breakdown of what each of the variables mean and could be

  • privilege-type: type of privileges to give such as INSERT, DELETE, ALTER, DROP, ALL PRIVILEGES, etc.
  • database: the database/table combination your are giving the user access to (see below for examples).
  • user: username of your choice that the user will use to login to view their databases.
  • ip-or-domain: the location where the user is access the database FROM.
  • new-password: password of your choice that the user will use to login to view their databases.

 

MySQL GRANT Examples – Helps to be understand

Example 1: Gives the user `poweruser` full access to all databases and tables. The *.* means all database and all tables.

GRANT ALL PRIVILEGES ON *.* TO poweruser@`1.2.3.4` IDENTIFIED BY 'some-pass';

 

Example 2: Create a user with INSERT, DELETE and UPDATE permissions to all tables under the exampledatabase database. They can also only login if they come from the location somedomain.example.com.

GRANT INSERT,DELETE,UPDATE ON exampledatabase.* TO `editoruser`@`somedomain.example.com` IDENTIFIED BY 'any-pass';

 

Example 3: Only give delete to a user and they can only access the reports database and the temptable table. The % for their location means they can access it from anywhere and not just a single ip or domain.

GRANT DELETE ON reports.temptable TO `cleanupuser`@`%` IDENTIFIED BY 'their-pass';

 

Example 4: Gives the root user full access but only from the same location as the database. So anyone outside of the server won’t be able to login. Useful if your website is running on the same server as the database and very secure.

GRANT ALL PRIVILEGES ON *.* TO `root`@`localhost` IDENTIFIED BY 'difficult-pass';

 

PHP stdin – Reading user input from command line in PHP

In C++ it is called cin, and in perl it is $variable = <STDIN> however what is the equivalent of cin and STDIN for PHP?

Well in PHP is is similar to perl in that we use php://stdin to read a user’s input from the command line. It is pretty straight forward and hopefully the example below will show how useful and easy it can be to capture a users input from the command line.

The below script will capture a user’s name and then display it to the user.

<?php

// show them a message to enter their name
echo "Tell us your name:\n";

// the script will wait here until the user has entered something and hit ENTER
$name = read_stdin();

echo "Thank you $name. Welcome to my site.\n";

// our function to read from the command line
function read_stdin()
{
	$fr=fopen("php://stdin","r");	// open our file pointer to read from stdin
	$input = fgets($fr,128);	// read a maximum of 128 characters
	$input = rtrim($input);		// trim any trailing spaces.
	fclose ($fr);			// close the file handle
	return $input;			// return the text entered
}

?>

Increase PHP Memory Limit in htaccess, apache or in a php script

Most of us have come across this error: “Fatal error: Allowed memory size of xxxxxx bytes exhausted (tried to allocate yyy bytes) in ….” in the php error logs.

In php, running out of memory in usually a sign that your php script is not too well written or has a bug or two in it; However sometimes even the best of our php scripts still require more memory than usual especially if it is handling large amounts of data.

Luckily in php, increasing the memory limit is an easy task to do and can be done in a number of ways.

Setting PHP Memory Limit inside PHP Script

Inside your php script that requires the increase in memory, you can add the following line which increases the memory limit just for that page. So putting this at the top of the script can help you handle larger amounts of data.

<?php

// note that memory_limit is case sensitive!
ini_set('memory_limit','64M');

// rest of your code follows

Setting PHP Memory Limit in .htaccess

Setting a memory limit in .htaccess is also straight forward. Add a line into your .htaccess file. Note that this will affect any php files within that folder and subfolders.

php_value memory_limit 64M

Setting PHP Memory Limit in php.ini config file

If you want to set the memory limit within PHP itself, then edit the php.ini file which is usually found under /etc/php/apache2/php.ini under Debian and find the line shown below and change it to whatever you need. This will affect all php scripts running under your server so be careful with this value.
Note: you will have to restart apache for this change to take effect

memory_limit = 64M

Setting PHP Memory Limit in Apache

Inside apache, find the virtual host that needs the increase in memory limit and add the line as shown below in italics.
Note: you will have to restart apache for this change to take effect

<VirtualHost *:80>

# apache settings for virtual host

php_value memory_limit 64M

# other settings etc. follow as usual.

</VirtualHost>

PHP Pear – Installing Pear and Pear Packages

What is PEAR?

PEAR is an acronym for PHP Extension and Application Repository. PEAR is a massive repository for PHP code. It provide easy access to hundreds of classes that can be implemented into your existing PHP project. It saves you time since you won’t have to write anything from scratch and you can simply reuse the code from the PEAR repository.

A few examples of the types PEAR packages available to you are packages such as encryption, mailing, image manipulation, benchmarking, caching, authenticating and so much more.

Installing PEAR for PHP

Now that you know what PEAR is, you may be asking “how do i install PEAR for PHP?”.

Under Debian this is quite simple. Enter the following command and it will download and install PEAR for you straight out the box.

$ apt-get install php-pear

It should really be that simple.

Installing a PEAR Package for PHP

Once you have installed PEAR, you can being installing all your much needed PEAR packages. To do this is a matter of entering the following:

$ pear install package-name

Where package-name is the name of the PEAR package you wish to install. So if I wanted to install the Auth_HTTP package, I would do this:

$ pear install Auth_HTTP

Upgrading a PEAR Package for PHP

Now to upgrade a PEAR package is pretty much the same as installing it.

$ pear upgrade package-name

Conclusion

Using PEAR packages will rapidly speed up your development since you will be using classes that are already complete with all the functionality you require instead of manually having to code from scratch. You can then focus on what is important, building amazing websites and programs that amaze everyone who comes to visit!