PHP: Get Mime Type of a File (and Encoding)

by Yang Yang on December 25, 2011

While you can somewhat rely on the name extension of a file to determine the mime type, it may not always be accurate. For example, .jpg and .jpeg files are very probably image/jpeg files and .png files are very probably image/png files, but there’s always an exception because file extensions can be faked. To accurately find the mime type of a specific file in PHP, you should use the Fileinfo extension.

Find out if the extension is enabled with the code outlined in the beginning part of the resize image in PHP post.

With the php_fileinfo extension enabled in php.ini, this is the function I come up with:

$finfo = new finfo(FILEINFO_MIME); // return mime type
if ($finfo) {
	$file_name = "/absolute/path/to/some.jpg"; /* Must use absolute path */
	$file_info = $finfo->file($file_name);
	$mime_type = substr($file_info, 0, strpos($file_info, ';'));
	echo $mime_type;
}

Which will get you this:

image/jpeg

The reason it gets complicated in the echo line is that the standard output of FILEINFO_MIME information output by the file() function of the $finfo object is something like this:

image/jpeg; charset=binary

Therefore, you have to literally get everything before the semi-colon to get the mime type information.

If it was a CSS file, the output of the $finfo->file() method would be like this:

text/plain; charset=utf-8

Cool, huh! Winking smile

{ Comments on this entry are closed }

Redirect 404 Error to Home Page

by Yang Yang on December 25, 2011

Other than making your 404 error page user friendly, you can redirect it to your index pages such as the homepage, sitemap, or search page, to make it useful for the users. Instead of relying on them to correct the error themselves, you offer the new orientation.

How to redirect a 404 error page to the home page?

There are essentially 3 ways to do this depending on the technology your site is built on.

The .htaccess and HTML solution

This works across all sites that are served by the Apache web server with .htaccess enabled. Add this line in the .htaccess file in the root directory of your domain:

ErrorDocument 404 /404.html

And in 404.html, add a meta tag in the HTML head section:

<meta http-equiv="Refresh" content="1; URL=http://www.example.com/">

So when there’s an 404 Not Found error the user would be first redirected to /404.html and in turn, he or she would be redirected to the homepage http://www.example.com/ (or whatever you change it to) by the meta Refresh actions.

The PHP solution

If you are using PHP to code your site, chances are you know this solution. You can always use the previous solution (The .htaccess and HTML solution) to redirect 404 error page to your home page on a PHP site, but you can also try the pure PHP approach instead.

Whenever a user types in a URL request that you do not recognize, render this:

header("HTTP/1.1 404 Not Found");
header("Location: /");
exit();

Which would redirect the user who has hit a 404 error to the homepage / or any other page URL you specify there.

The WordPress solution

If you are using WordPress for your site, make a 404.php file in your theme directory with the following content:

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".get_bloginfo('url'));
exit();

WordPress would automatically use 404.php as the default 404 Not Found error page and when a user hits that page, he or she would then be taken to the home page your WordPress blog.

{ Comments on this entry are closed }

It’s not unusual to respond to the user actions by dynamically modifying some content of the page. For example, you can employ JavaScript to change and load another image based on the <select></select> option the user has just selected.

This is the snippet you need:

<select onChange="getElementById('front_image').src='/images/'+this.value+'.jpg';">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<img src="/images/1.jpg" id="front_image" />

Assuming you store all the images in the /images/ directory.

You get the idea.

{ Comments on this entry are closed }

Cheap PSD to WordPress Theme and Custom Plugins

by Yang Yang on December 23, 2011

My friend Xiaobo has been developing for WordPress for the last 4 years – a truly master he is about the themes, plugins, and any customizations you may need about WordPress. He has helped hundreds of professional bloggers.

If you ever run into any problems or are simply in need of a developer like him who can help you make your blog better, be sure to bug him at any time:

RoamFox: http://www.roamfox.com/
Gmail: roamfox@gmail.com

He does PSD to WordPress theme conversion and custom WordPress plugins development.

Make sure you mention you went over from Yang so that he would get you some nice discounts. Winking smile

{ Comments on this entry are closed }

You can save re-usable data in database such as MySQL so you can load them among different scripts / script sessions, though it may be a bit overwhelming for simple tasks because you have to set up a whole database and the connection credentials, etc.. File system is probably a better approach with regards to storing and retrieving simple tabular data, for not-so-important projects or test projects.

Then should we opt for XML or JSON? XML is bit too formal for teensy jobs. JSON, on the other hand, is the star of simplicity and capable or dealing with both tabular data and objects quite handily.

So we will store tabular data such as an PHP Array to JSON text which would then be stored as a ASCII text file. When we need to use the array again, be it in another PHP script or at a later time, we would just load the JSON string in the file and decode it into an array in PHP.

How can we do this? As simple as abc.

Store PHP Array in File

file_put_contents('array.txt', json_encode($your_array));

Read Array from File

$your_array = json_decode(file_get_contents('array.txt'), true);

Serialize()

Another approach is to use the serialize() and unserialize() functions of PHP. You may want to read this to choose between them: http://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize

{ Comments on this entry are closed }

CSS: Make <pre> Text to Wrap

by Yang Yang on December 19, 2011

I deal with quite some code examples across some of my blogs and sometimes they contain too long lines to fit in nicely, which makes it hard to read the latter part of a long line. But you still need to maintain the pre-formatted text with the <pre> tag.

The solution is to use CSS to prescribe the <pre> tag to wrap the lines. Just add this in your stylesheet:

pre.wrap {
 white-space: pre-wrap;       /* css-3 */
 white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
 white-space: -pre-wrap;      /* Opera 4-6 */
 white-space: -o-pre-wrap;    /* Opera 7 */
 word-wrap: break-word;       /* Internet Explorer 5.5+ */
}

And add the “wrap” class to the <pre></pre> blocks that you want lines to wrap naturally:

<pre class="wrap">I will be wrapping at the end of the line width.</pre>

{ Comments on this entry are closed }

How Social Media is Ruining Our Minds [Infographic]

by Yang Yang on December 18, 2011

The power of social media now beginning to be felt, there may be some “powers” better left alone. Scientist now say Social Media participation may be causing users’ brains to be REWIRED! Now there is some startling news. Facebook, Twitter, and now g+ use being on the upswing, it’s no wonder all our time is taken up, but who said anything about losing the ability to multitask?

That’s just what the data plugged into the infographic from Assisted Living Today suggests. Accordingly, cognitive functioning may be altered, if not impaired from dogged pursuit of your network. If your focus seems shifted of later, maybe you should consider altering your SM patern of use? Well, at least practice multitasking in between social media usage, huh?

Seriously, if your attention spans (as indicated in below) get any shorter, we won’t be able to pay attention sure enough.

How Social Media is Ruining Our Minds Infographic

Infographic by Assisted Living Today – Assisted Living Facilities

{ Comments on this entry are closed }

verisignA quick notification for my readers. As VeriSign is increasing the registry fee of .com by about $0.5 by Jan. 15, 2012, you may want to renew all of your existing .com domains by then. The name registration fee is on a rise ever since the dawn, depending on your personal finance, renewing earlier is probably better that later.

dynadotIt’s about to be Christmas so do search for “*registrar* renewal promo code”, coupons, etc. for your registrar when you are renewing your names. Dynadot was kind enough to offer a renewal promo code “HOLIDAYRENEWAL” for $0.25 discount off one year renewal of any .com name. It’s the best chance to renew all your names before the prices increase at the beginning of next year (2012).

Currently the best promo code I can find for Godaddy is “cjc795dom” which is $7.95 for .com renewal. Do share in the comments if you have a better find.

Use this code for $7.49 / year .COM renewal: Zine10

{ Comments on this entry are closed }

<IfModule></IfModule> in .htaccess

by Yang Yang on December 2, 2011

I was debugging about some mod_rewrite errors caused by the .htaccess file on one of my sites and couldn’t solve the problem myself so I opted for a help thread on the SitePoint.com forum. Turned out it’s not the problem of my mod_rewrite rules in .htaccess but some incorrect file permissions that were causing the trouble.

Dklynn was very nice to help me in this regard and offered a gold advice that I thought I should share with you.

You Should NOT Use <IfModule></IfModule>. Why?

He pointed out that I should get rid of the <IfModule> conditional from the .htaccess file. It’s useless and a complete waste of server resources by all means. No excuses.

Considering the fact that all HTTP requests (including those to trivial assets such as .css, .js, .gif, .jpg, etc., thus each web page download would trigger about 10 or even more HTTP requests) to the Apache web server are handled by the rules in your .htaccess file, I think I should get rid of all such <IfModule> conditionals from all .htaccess files on all my sites, or the server would be doing useless check of “If Module xxx Is Enabled” every time a HTTP request is received…..

With a site receiving 1000 page visits per day, your server would have to do 10,000 such useless checks at the cost server resources and performance.

Many famous 3rd party scripts such as WordPress has <IfModule></IfModule> in the .htaccess file by default. This is to prevent potential errors should the module was not installed on the client’s production site / server. You should try and remove it. If the mod_rewrite and SEO friendly URLs are working, you can remove it without any problems.

This is pure gold advice offered by Dklynn. Check out his site about Apache mod_rewrite.

{ Comments on this entry are closed }

Turn Your Blog or Business Into A Marketing Machine

by Yang Yang on December 1, 2011

These days it seems everything is automated. Some marketers even try to automate the two way conversation of the so called social media revolution, but there’s always got to be a human sentiment and senetient being behind communications. Especially the closer our network interactions become.

However, despite the need for up-close-and-personal two way communication, there are ways in which business, your website, your SME, any brand can be funneled into the new age.

Leads are always the focus of the so called sales funnel, but your whole marketing plan needs to reflect the best combination of automated marketing tactics, along with tools that help humans interact with humans. The infographic below show some clues as to how any business might accomplish this.

Understanding Marketing Automation

HubSpot Marketing Automation Software

The graphic above courtesy HubSpot, shows a clear path for many large and small businesses to engage with better marketing balance. Putting any such plan into shoe leather, this is another story. Check back for more insight into how you can integrate all these tools and strategies, make your blog or outlet as powerful as it can be.

{ Comments on this entry are closed }