Sunday, June 10, 2012

Forcing the files to download using htaccess

If we want to put a functionality in our website to download files, the best and easiest way to do it is to have it in htaccess.

By default, the files will open up to your current page or open up a tab when clicked via target="_blank" attribute. Well, that is for me not a good experience, most especially if your website is a downloading site.

You can also try to make a script to force the files to download either via php, asp, or any language, but that will be tedious.

Why do you need to be hard on yourself if you can do it fast and easy.

Please see below syntax that you can put in on your htaccess to force the file to download on your website.

AddType application/force-download .csv
AddType application/force-download .xls
AddType application/force-download .doc
AddType application/force-download .docx
AddType application/force-download .avi
AddType application/force-download .mpg
AddType application/force-download .mov
AddType application/force-download .wav
AddType application/force-download .zip
AddType application/force-download .mp3
AddType application/force-download .pdf


Hope this helps. Thank you for reading such a short post.

Thursday, May 17, 2012

Setting up a remember me functionality on your website

First we need to have a login page where to put the "remember me" check box to have an identifier whether the user wants to be remembered or not.

Second, we need to set the users table to store the remember me token which we will use to identify as to which user should be logged in.

Please take note that I used token which is another field rather than using the actual user id coz having a token that changes every time is much secure than having just a static id.

I will discuss below on how you can make it much secure.

Okay, once you have the above in placed, we are now ready to do the coding.

You need to capture those users that agrees to be remembered then call this function below. For the benefit of this post, I set the cookie to expire in 14 days.

<?php
 

if (!mysql_connect('localhost', 'mysql_user', 'mysql_password')) die("can't connect to db: ".mysql_error());

if (!mysql_select_db('database_name')) die("can't select db: ".mysql_error);

$user_id = '<your login user id>';

// call this function to set cookie and expiry time

set_remember($user_id);

// set cookie and expiry time
function set_remember($user_id=0) {
        $token = md5($user_id."-".date('YmdGis'));
        $expire = time() + (14 * 86400); // 14 days

        setcookie("remember_me_token", $token, $expire);

        $expire = date('Y-m-d', $expire);
        $return = update_user_token($user_id, $token, $expire);
}

// update users table for token and expiry time
function update_user_token($user_id=0, $token='', $expire='') {
        $sql = "UPDATE user_table SET token='$token)', expire='$expire' ".
               "WHERE user_id='$user_id'";

        $query = mysql_query($sql);
        return 1;
}

?>

$user_id is the id of the user who successfully logged in to your site. This will be used to generate a random token which we will set in our cookie and update the users table as well.

We will use the function of the PHP to set the cookie.

setcookie("your_cookie_variable", "your_cookie_value", "expiration_of_cookie");

Please take note that you have to make sure that the user be able to login with the right credential before you call the function "set_remember($user_id)".

After calling function, you can get the cookie value by calling $_COOKIE["your_cookie_variable"]; and in our example above, you can call it by this syntax $_COOKIE['remember_me_token'];

I just want to remind you that COOKIE is not like a SESSION that starts when the pages loaded, the COOKIE will store value in your computer, so you need to come up with a COMPLEX name to prevent hackers from hacking your site.

Okay, moving on, since we set our cookie to expire in 14 days, then we have to make the user to be remembered every time they login and extend the expiration accordingly.

To do that, we need to get the token value from the cookie, get the user_id from our database, then call again the function set_remember($user_id);. If there's no cookie available, then redirect the user to login page.

Please see below for the sample implementation.

<?php

if (!mysql_connect('localhost', 'mysql_user', 'mysql_password')) die("can't connect to db: ".mysql_error());

if (!mysql_select_db('database_name')) die("can't select db: ".mysql_error);

$cookie = get_cookie('remember_me_token');
if ($cookie) $user_id = get_user_id_by_cookie($cookie);

// go to login page if no value for user_id
if (!$user_id) header("http://mywebsite/user/login");

// function to get the user id from the cookie
function get_user_id_by_cookie($cookie='') {
        $sql = "SELECT user_id FROM user_table WHERE token='$cookie'";

        $query = mysql_query($sql);
        return mysql_result($query, 0, 0);
}

// call this function to renew token then set a new new expiry datetime
set_remember($user_id);

// set cookie and expiry time
function set_remember($user_id=0) {
        $token = md5($user_id."-".date('YmdGis'));
        $expire = time() + (14 * 86400); // 14 days

        setcookie("remember_me_token", $token, $expire);

        $expire = date('Y-m-d', $expire);
        $return = update_user_token($user_id, $token, $expire);
}

// update users table for token and expiry time
function update_user_token($user_id=0, $token='', $expire='') {
        $sql = "UPDATE user_table SET token='$token)', expire='$expire' ".
               "WHERE user_id='$user_id'";

        $query = mysql_query($sql);
        return 1;
}

?>


Hope this post helps a lot!! Thanks!!

Wednesday, May 16, 2012

How to get the main domain from the URL

This post is just a code snippet on how to get the main domain from the URL string. Enjoy and happy coding!!

<?php

$url = "http://subdomain.domain.com/sample/url"; 

$host = parse_url($url, PHP_URL_HOST);
$host = array_reverse(explode('.', $host));
$host = $host[1].'.'.$host[0];

echo "$host";

?>

Wednesday, April 25, 2012

How to setup cache pages in PHP

This post will teach you how to setup caching in your pages. This is recommended to setup if your pages is not that dynamic enough that changes frequently.

First, you need to create as to where you will put all your cache files, don't put it on the same directory where your files are in coz it might overwrite your pages. On this post, I created cache directory.

We can also set the cache expiry time by validating the time it was created. To check, we used time() and filemtime() functionality.

To make it work, we will put condition to check if the we have cache file and that it didn't expired yet. If okay, we will just include the file then display the contents. If not, it will capture the page then write to a file.

Please see below for the implementation. Happy coding!!

<?php
$cachefile = "cache/yourpage.html";
$cachetime = 30 * 60; // 30 minutes

// validate and check for existing cache file
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
        include($cachefile);
        exit;
}

// start the output stream
ob_start();
?>

<html>your page here to put into cache</html>

<?php
// save the contents to cache file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);


// end the output stream
ob_end_flush();

?>

Friday, March 9, 2012

Setting up dynamic sub domain via httpd.conf or htaccess

This post will teach you how to setup dynamic sub domain on your server.

We actually have 2 options on how to do it, maybe 3 which uses cpanel if allowed on your account.
Anyway, what I'll be discussing is the setup via httpd.conf or via .htaccess file.

To do this via httpd.conf, you only need to create a virtualhost with ServerAlias as below.
<VirtualHost>
    DocumentRoot /www/subdomain
    ServerName www.domain.tld
    ServerAlias *.domain.tld
</VirtualHost>


To do this via .htaccess, create the htaccess file on the www/ directory where your subdomains will be placed.

RewriteCond %{ENV:REDIRECT_SUBDOMAIN} =""
RewriteCond %{HTTP_HOST} ^([a-z0-9][-a-z0-9]+)\.domain\.com\.?(:80)?$ [NC]
RewriteCond %{DOCUMENT_ROOT}/%1 -d
RewriteRule ^(.*) %1/$1 [E=SUBDOMAIN:%1,L]
RewriteRule ^ - [E=SUBDOMAIN:%{ENV:REDIRECT_SUBDOMAIN},L]


Hope this helps. Thanks!

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.