PHP Get File Extension Quickly

Overview

If you are looking for the quickest way to check a file extension in PHP, then you have reached the best article to read. Perhaps you need to get file extension in PHP of a file that has been uploaded or use php to check a file extension of an existing file on your website. In any case, the below function will show you how to do it in the least amount of code.

PHP Get File Extension Quickly

<?php

$filename = "/home/darian/any.file.name.jpeg";

// get the php file type
$extension = pathinfo($filename, PATHINFO_EXTENSION);

// display the extension: This will echo out ".jpeg"
echo $extension;

?>

How Does The Above Code Work

We use the php function pathinfo() which will take a path (such as “/home/darian/any.file.name.jpeg” in our example) and will return the information about that full path. For example, if we had to run the following code:

$path_info = pathinfo($filename);

It would output an array with information similar to this below

Array
(
    [dirname] => /home/darian
    [basename] => any.file.name.jpeg
    [extension] => jpeg
    [filename] => any.file.name
)

As you can see, the element extension contains the file extension. Now we can speed this function up even further by adding the flag PATHINFO_EXTENSION which tells the function to only return the file extension as a string rather than an array with all the additional information.

Quickest Way To Remove Empty Array Elements PHP

Overview

Here I will show you the quickest way to remove empty values from an array.
The first way is slow but the most logical way of approaching this. Luckily the second example is the quickest and also pretty simple way. Use the second way, trust me, you will love it.

The slow but simple way – don’t use

Here is the most straight forward way of doing this. It works but I will show you a quicker way afterwards.

<?php

// our massive array with set values and empty values
$array = array(...);

foreach( $array as $key => $value )
	if( $value == "" ) unset($array[$key]);

?>

Quickest Way To Remove Empty Array Elements PHP

And here is the quickest way I have found to remove empty array elements php. Below we fetch a list of keys from the array that is empty (using the php function array_keys) and then unset each of those values.

<?php

// our massive array with set values and empty values
$array = array(...);

// get the empty array keys using array_keys
$keys = array_keys($array,"");

// foreach empty key, we unset that entry
foreach ($keys as $k)
	unset($array[$k]);

?>

Simple yet surprisingly quick.

MySQL Copy Table From One Database To Another

Overview

So you are looking at transferring the data of on MySQL Table into another MySQL Table. Migrating data from database to another database table can be surprisingly easier than you would think.

MySQL Copy Table From One Database To Another

The following query will copy all rows from table_one into table_two. In order for this to work correctly, the number of columns must match. It doesn’t matter if the names of the columns are different, so long as the column count is the same.

INSERT INTO `table_two` SELECT * FROM `table_one`;

MySQL Copy Table With Different Number Of Columns

You can also copy data where the column count is different between the two tables. In order to achieve this, your SELECT will have to return the right number of columns as INSERT statement is expecting.
The exciting part of this is that you can filter which results get transferred by using normal MySQL “SELECT WHERE” syntax as you can see in the below example. In the example, we only transfer the records from table one that are LIKE ‘some value’ and limit the transfer to 20 results.

INSERT INTO `table_two` (`column_A`, `column_B`) SELECT `column_C`, `column_D` FROM `table_one` WHERE `column_name` LIKE '%some value%' LIMIT 20;

Important Note

In the above query, you will notice I select column_C and column_D but I insert it into column_A and column_B. This will work fine even thought the column names don’t match. As long as the column count is the same you will be fine. Assuming that you don’t have foreign key conflict or are missing required columns.

Simple as that.

CSS Button Sprite Example

What IS A CSS Button Sprite?

Let me start off by explaining what an image sprite is. A sprite is basically one larger image that is made up of many smaller images. The idea of sprites is that you only need to load one image and then apply it to a smaller div or A tag so only a portion of the large image shows. Then depending on the background position of the image, you will only see one of the smaller images. This tutorial will be useful if you want to create button sprites, menu sprites, sprite animations or any other type of sprites.
If you would like to see an example on using these sprites to create a sprite animation, check out the sprite animation tutorial.

CSS Button Sprite Example

Below is showing you a css button sprite. This article will show you how to create this button sprite.
 

Above is the finished example of what this tutorial will show you. Mouse over this sprite button image and see how it works and bear in mind that we are only using one image to create the rollover effect. The button is actually an A (anchor) tag that has a height 32px which is half of the image sprite height. This way, only the top half of the image shows which is the up state part of the image.

Why should you use css sprites?

Before images and css items can be displayed on your webpage, your browser must request the item such as javascript files, images, css files, etc. Each request takes time and your browser must wait for a response and then download the file for it to be displayed. So in short, the less items means less time to request and download items, meaning less time to load a page. So using sprites will increase the speed at which your website loads.

Button Sprite

Button Sprite

Above is the css button sprite image I made to create the above button sprite with it’s two states. Normal state when it is untouched and second state is the hover state for when we mouse over it. Notice that the one image contains both up and down states and then as we mouse over it, we use css to adjust the background position of the image sprite to make it appear that the button state is changing.

Now for the code to get this all working

CSS Code

<style>
/* css to style the button */
#rollover {
	background: #FFF url("images/sprite.png");
	width: 180px;
	height: 32px;
	display: block; /* can use inline-block instead of block */
}
/* hover is trigger when we mouse over the A (anchor) tag and adjust the
	background position of the sprite to make it appear the button is down */
#rollover:hover {
	background-position: 0 -32px;
}
</style>

HTML Code

Next the html A (anchor) tag we apply the rollover button style to.

<a href="#-" id="rollover"> </a>

Now when we mouse over, it will appear that the button is changing states. Image sprites aren’t only for buttons, but can be used for rollover menus, animations, or anything that has multiple display states.

Logrotate Set File Permissions

Overview

If you have ever wondered why your log files randomly change permissions each night. Logrotate could be up to its tricks. Similar to the other article I published on Why is apache randomly restarting which explains why logrotate could be causing apache to restart randomly.

Logrotate Set File Permissions

Each time logrotate runs its course, it will compress, rename and remove older files. Remember that a rename is essentially just a ‘move’ operation. This causes some of your log files to no longer exist (since then have been compressed and renamed). Luckily logrotate will attempt to recreate these files and will set some permissions for it.

Post Rotate

Once the logs are rotated, logrotate will execute any commands set in the post rotate part of the script. For example, my logrotate apache config tells it to restart apache.
It restarts apache so apache can recreates any missing log files. Then the permissions that the newly created log files get are determined by the config file for logrotate.

Example Logrotate Apache Config

/var/www/*/logs/*.log {
        weekly
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 root adm
        sharedscripts
        postrotate
                /etc/init.d/apache2 reload > /dev/null
        endscript
}

Choosing The Log Permissions

Edit the logrotate apache file which under Debian is usually found under:

vi /etc/logrotate.d/apache2

Inside this file and most logrotate config files, you will see an entry like this

create 640 root adm

This basically tells logrotate to create any missing files, with the permissions of 640 (640 being the standard unix permisson bits) and root as the user with adm as the group.

Simple as that!

Why is Apache Restarting Randomly

Overview

If your apache seems to restart randomly, it can be confusing and difficult to find the issue. I noticed apache on one of my servers was restarting at what seemed like random times.

Why is Apache Restarting Randomly

In my case, Logrotate was to blame and was the cause of the issue. Each time logrotate runs, it will compress, rename and recreate your log file. Furthermore, while rotating your logs it will also remove older logs. Similar to the follow up of this article explaining how to permissions for files that that logrotate creates.

Since the logs files are renamed, it will result in some of your log files to be ‘missing’ since a rename is essentially a ‘move’ operation.

Time To Recreate Apache Log Files

Now that the log files have been renamed, it will recreate the log files. Once the new log files have been created, apache needs to restart so apache can a file pointer to the newly created log files. Logrotate will achieve this by restarting apache, at which point apache will recreate the missing log files.

Example Apache Log Rotate

Here is an example of a logroate apache config. See the section on ‘postrotate’, this is the reason it is restarting apache after each log rotate.

/var/www/*/logs/*.log {
        weekly
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 root adm
        sharedscripts
        postrotate
                /etc/init.d/apache2 reload > /dev/null
        endscript
}

PHP Header Force Download Of Files

Overview

In apache, the file type will usually determine how the file is handled. It can opened and displayed in the browser or download, etc. For example, images, css, javascript, php, html (and other types) files are executed and displayed within the browser whereas PDF, ZIP, EXE and other unknown file types will be downloaded by the browser. Usually this behaviour is suitable however we may want to change how certain file types are handled and then force an Image or PHP script file to be downloaded.

PHP Header Force Download Of Files

The below PHP Header code will force any file to be downloaded rather than just being displayed in a browser. You can use this code to force PDF download or to force an Image to download or force download of a javascript file rather than having these file types displayed or executed by the browser.

PHP Header Code To Force File Download

<?php

/* The name of the file we want to force a download */
$filename = 'somefile.html';

/* set our content type to match the file we are downloading */
header("Content-Type: text/html");
/* Tell the browser how big the file is going to be */
header("Content-Length: ".filesize($filename)."\n\n");
/* force the file to be downloaded */
header("Content-Disposition: attachment; filename=$filename");

/* echo out the contents of the file */
echo file_get_contents($filename);

Important Note

Remember that since we are sending headers, we need to make sure that there is no output sent to the browser before the headers are sent. Also, the file mime type should match the file type, such as a mime-type of image/png for PNG files and application/pdf to force a PDF file to download.

Note that you can force the download to have a different name by changing the filename for the Content-Disposition header to the filename of your choice.
For a more complete list of file mime-types, you should visit my article on list of file mime-types. If you would like to learn to to determine the mime-type based on the file extensions, check out this article.

Common List Of Mime Types

Below is a list of mime types I come across most often. Suggest others mime-types that should be a part of the list by leaving a comment below. You can also view my other article on finding the mime-type of a file to see how you can return the mime-type of a file determined by the file extension.

List Of Mime Types

Text

PHP – text/html
HTML – text/html
HTM – text/html
CSS – text/css

Multipart

– multipart/mixed

Application

PDF – application/pdf
ZIP – application/zip
JAVASCRIPT – application/javascript
JSON – application/json

Image

GIF – image/gif
JPEG – image/jpg
JPG – image/jpg
PNG – image/png

Video

MPEG-1 – video/mpeg
MP4 Video – video/mp4
Quicktime – video/quicktime
WMV – video/x-ms-wmv
3GP – video/3gpp

Audio

MP3 – audio/mpeg
MP4 – audio/mp4
Ogg Vorbis – audio/ogg

If you see anything missing from my list of mime types, please message me or leave a comment.

Conclusion

Browsers will detect the mime-type of files and display them accordingly. And because of this, it is important to have the correct Content-Type header set for your files. For example, if you read a jpeg from disk and echo the contents to the page, you must set the content type to image/jpeg or image/png in order for the browser to display it as an image and not just display the contents of the file.

Manually Override DNS -Window, Linux and Mac Examples

Overview

First off, let me explain what a DNS Entry is in order for us to understand why we would need to override it. Basically a DNS entry is a record or entry that tells us what ip address is of a domain will point to. Such as an example (not actual) IP of 66.12.23.124 could point to a domain such as www.example.com.

Say perhaps we are updating a DNS entry and as the nature of DNS would have it, sometimes it will take up to 48 hours for the DNS to propagate through the Internet. Or perhaps we don’t want to update a DNS record which could affect everyone but rather just change a record for ourselves, locally. In these case, we can manually override the DNS change which will only reflect on our local machine. Below I will show you how to achieve this on Windows, Linux and Mac.

Manually Override DNS on Windows

Open up the hosts file located under “C:\Windows\System32\etc\drivers\“. In there you will see the IP address in the left column and a space separated list of domains to the right. The below example will set the 3 domains of www.example.com, anotherdomain.example.com and lastdomain.com to the IP address of 10.0.0.1.

10.0.0.1 www.example.com anotherdomain.example.com lastdomain.com

Manually Override DNS on Linux

vi the hosts file which is located under /etc/hosts. Add in a line below the last entry in the same fashion as you would for windows. For example if you wanted to change the ip address for the domain www.example.com to point to 192.168.0.20 you would enter:

10.0.0.1 www.example.com anotherdomain.example.com lastdomain.com

Manually Override DNS DNS on Mac

Mac is the same as the above linux example. Simply edit the hosts file under /etc/hosts and add in the entries as needed. So again, you could enter something such as:

172.10.1.5 www.anydomain.com

Manually Override DNS Using IPV6

You don’t always have to use a standard IPV4 as the IP address. You can also use IPV6 and enter it into any of the hosts files like so:

fe80::1%lo0 localhost

And that is all there is in Manually Override DNS in windows, linux and mac.

Using Curl As A Wget For Mac Replacement

Overview

I was trying to download a file on my Mac and realised that there is no wget for Mac. Since I consistently use wget I decided to find a way to get wget for mac. I found a quick way to create an fake wget command by creating an alias of curl. By creating the alias, I am able to call ‘wget’ and it will invoke curl -O in the background and download the file just as wget would have. This is a quick way to get wget for Mac.

Using Curl As A Wget For Mac Replacement

In order to create an alias of `wget` that will simply run the command curl -O I ran the command below:

echo 'alias wget="curl -O"' >> ~/.bash_profile

Now when i type ‘wget http://www.example.com’ it will download the url as you would expect from wget. As mentioned before, in the background it will be invoking curl to download the file. So when I run `wget`, it is actually executing curl -O to download the file as we won’t even notice the difference. Well maybe a small difference. But the end result is the same and your file is downloaded.

Example Using The Replacement wget For Mac

wget http://www.example.com/helloworld.html

The -O option to curl tells curl to save the URL as a file rather than displaying the source.

And that is all there is to it.