www.pokeroconnor.com

htaccess Tips and Tricks

April29

Good information on htaccess (mod_rewrite and mod_alias) can be tough to come by – one web “guru” I know has a theory that mod_rewrite is one of the black arts of web design. So in order to try and shine a light on the darkness of htaccess, here’s some of the useful and very practical tidbits I’ve come across. 

To start with, here’s some of the better resources, with a brief description of what each link has to offer.

  • Stupid htaccess tricks is probably the most comprehensive guide to htaccess, and deserves to be first in the list. The examples aren’t very detailed, but if you work with mod_rewrite you will likely need to check something here
  • fun with htaccess is a more descriptive piece, nowhere near as comprehensive as Stupid Tricks, with just a few samples, but nicely written

Actually, the above two are the main ones worth reading, even if you aren’t looking for  anything specific. To be more specific, let’s look at some sample use cases.

Let’s jump right in – to use htaccess effectively you will be using regular expressions, for example say you want to match a certain string, and redirect that plus everything that follows. E.g. you have many many urls such as my.domain.com/book123 my.domain.com/book456 my.domain.com/book789 and you want to redirect them all to the uri /new-books, but keep the numbers, e.g. my.domain.com/book123 is to go to my.domain.com/new-books123 etc. So you would use a regexp, which is defined on the left hand side of the rule, and “used” on the right hand side. $1 represents the first match of a pattern (which has previously matched in that particular rule), $2 the second and so forth. So, that gives us:

RewriteRule ^book(.*)$ /new-books$1 [L,NC,R=301]

The ^ symbol signifies beginning of the match, $ the end. .* matches everything. Using parentheses around the .* identifies this as a matched pattern, for use on the right hand side with $1. [L,NC,R=301] is a sample of many possibilities, L meaning this is a terminating rule for that match, NC ignore case, 301 is a permanent redirect. Stupid htaccess tricks has a full list of all these options. The regexp’s you can use are endless of course!

Sometimes you need to build compound, conditional rules, such as if a certain domain, then redirect a certain uri. E.g. say you have 3 domains, www.domain.com www.domain.net and www.domain.org, and you want requests to domain.com/net/org to redirect to www.domain.com/net/org.

RewriteCond %{HTTP_HOST} ^domain\.(com|net|org) [NC]

RewriteRule ^(.*)$ http://www.domain.%1/$1 [R=301,L]

In this case the first pattern is com|net|org, which is represented by %1 in the rule. $1 again matches (.*) which means for example that domain.org/blah gets redirected to www.domain.org/blah. You can chain as many conditions as you need. 

htaccess ignores query strings, so if you needed to match www.domain.com/index?key=blahblah and redirect it to www.domain.com/index you would be out of luck! Unless of course you do this:

RewriteCond %{REQUEST_URI}  ^/index$

RewriteCond %{QUERY_STRING} ^key=blahblah$

RewriteRule ^index/?(.*)$ http://www. domain.com/index/? [R=301,L,NC]

Note the ‘?’ at the end of the rule, in http://www. domain.com/index/This is vital and signifies that you want to drop the query string

Say you want to block some bozo’s IP from accessing your site. Simply add this:

order allow,deny
deny from 123.45.6.7
deny from 012.34.5.
allow from all

Just make sure you use that order above to deny…

That’s it for now, there is so much to add, and so little time to add it!

Free SMS Gateways

April27

Will fill in more info later, but here’s the basics so far: got this amazing free sms Gateway, playSMS. Great install instructions, such as:

playSMS Web Interface:

1.  It is important to meet all minimum requiments above

2.  Setup a system user named ‘playsms’ to manage playSMS

    # adduser playsms

    # passwd playsms

    Note: on some Linux distributions adduser and passwd combined (Debian, Ubuntu and maybe others)

3.  On most Linux distributions actions (2) will create system user and group named ‘playsms’

    with home directory /home/playsms, but you will install playSMS in different directory

4.  Create playSMS web root, spool and log and set ownership to user www-data or web server user

    # mkdir -p /var/www/playsms

    # mkdir -p /var/spool/playsms

    # mkdir -p /var/log/playsms

    # chown -R www-data /var/www/playsms

    # chown -R www-data /var/spool/playsms

    # chown -R www-data /var/log/playsms

5.  Extract playSMS package somewhere (Usually in /usr/local/src)

    # tar -zxvf playsms-x.x.x.tar.gz -C /usr/local/src

    Note: x.x.x may vary according to the package name you’ve download

6.  Copy files and directories inside ‘web’ directory to playSMS web root and set ownership again to 

    user www-data or apache web server user

    # cd /usr/local/src/playsms-x.x.x/web

    # cp -rR * /var/www/playsms

    # chown -R www-data /var/www/playsms

    Note: assumed your web server user is www-data

7.  Setup database (import database)

    # mysqladmin -u root -p create playsms

    # mysql -u root -p playsms < /usr/local/src/playsms-x.x.x/db/playsms.sql

    Note: you dont need to use MySQL root access nor this method to setup playSMS

    database, but this is beyond our scope, you should read MySQL manual’s for custom

    installation method or howto insert SQL statements into existing database

8.  Copy config-dist.php to config.php and edit config.php

    # cd /var/www/playsms

    # cp config-dist.php config.php

    # mcedit config.php

    or 

    # vi config.php

    Note: please read and fill all required fields with coutious

9.  Enter bin directory, copy playsms, playsmsd, playsmsd.php, playsmsd_start to directory default

    # cd /usr/local/src/playsms-x.x.x/bin

    # cp playsmsd playsmsd.php playsmsd_start /usr/local/bin/

    # cp playsms /etc/default/

    Note: please note the different between playsms and playsmsd

10. Look for rc.local on /etc and its subdirectories (usualy /etc, /etc/init.d or /etc/rc.d/init.d)

    Edit rc.local and put: 

    ”/usr/local/bin/playsmsd_start” (without quotes)

    on the bottom of the file (before exit if theres exit command). This way playsmsd_start 

    will start automatically on boot. 

    Note: you need ‘root’ access to do this

11  Browse http://localhost/playsms/ and login using default administrator user

    username: admin

    password: admin

12. At this point you should be able to login to playSMS web interface and manage playSMS

There are quite a few requirements though, notably you must have PEAR DB installed, and also Lynx browser. More to follow…
To install wget, get it here, read this. For the lynx install, I used /usr/share/libtool/config.guess instead of /usr/libexec/config.guess. 
posted under MySQL, php | No Comments »

Server Timezones

April19

You can override your server’s timezone setting using php’s date_default_timezone_set. It is a really good idea, in my opinion, to use this at the start of your scripts that work with timestamps. Reason being, you can transfer scripts between servers and they will always work, which wouldn’t necessarily be the case if they depend on a servers timezone e.g if you are calculating a unixtime value in your script.

For example, I had an Ajax Calendar app that used Unixtime values to calculate which data to retrieve from a MySQL db. This worked fine on my dev server, whose server timezone was GMT, but when I transferred the code to my production server, which runs on E.T, it was not retrieving the correct data! This was a major pain to debug, as the code itself was fine of course, and was solved with a single line of code:

date_default_timezone_set(”GMT”);

Place this at the start of any script that has a dependency on the server timezone, and you can port your code to any server regardless of its timezone. If you don’t know your server’s timezone, date_default_timezone_get() will give it to you.

posted under MySQL, php | No Comments »

XPath and php starters

April17

Quick starting point on XPath and php would be the W3C Xpath pages. All the syntax info you really need to build queries are there. One other example i found useful was this one.

Then to use XPath with your php scripts, I use xpath(). A basic example would be the following (explained underneath) – say you have an <item> node which has multiple <title> children nodes, and you want to get a list of all the first children <title> nodes from that xml doc, you could do this:

<?php

$xml = simplexml_load_file(’path/to/file/xml-file.xml’);

    $matches = $xml->xpath(”//item/title[1]“);

     foreach ($matches as $match){

echo $match[0] . “<br>”;

}

?>

So firstly we use simplexml_load_file to load our xml file. We then build the query, saying for every item element that appears anywhere in the xml file, select all title elements that are the first (the title elements that appear ‘top’ in the list) children of item elements.

posted under php | No Comments »

IE PNG Fix

April17

A very convenient way to deal with I.E 6 png transparency issues, is to use TwinHelix’s IE PNG Fix. Its convenient as in, once you apply it to your css file(s), you don’t necessarily need to do anything each time you use a png file. 

So the first thing is to download it. Once done , there are good instructions in the ‘iepngfix.html’ file. An extract is shown here, fyi…

How To Use

Follow these simple steps to add this to your page:

  1. Copy and paste iepngfix.htc and blank.gif into
    your website folder.
  2. Copy and paste this into your website’s CSS or HTML:


    <style type="text/css">
    img, div { behavior: url(iepngfix.htc) }
    </style>

    That CSS selector must include the tags/elements on which you want PNG
    support — basically, give it a comma-separated list of tags you use.
    It must also include the correct path to the .HTC relative to the HTML
    document location
    (not relative to the CSS document!). For instance,
    yours may look like this:


    <style type="text/css">
    img, div, a, input { behavior: url(/css/resources/iepngfix.htc) }
    </style>

  3. If your site uses subfolders, open the .HTC file in a text editor like
    Windows Notepad and change the blankImg variable to include
    a correct path to blank.gif like so:


    var blankImg = '/images/blank.gif';

    Again the path is relative to the HTML file.
    Otherwise, you will see a “broken image” graphic!

  4. Sit back and enjoy!
posted under css | No Comments »

MySQL datetime Formatting

April10

Say you are using MySQL datetime as the format for your dates, so when you output it you get 2009-03-21, which isn’t exactly user friendly nice to read. Say you want instead to have March 21st, 2009. There are of course two main ways to do this, convert the datetime field in php using mktime() to Unix Time, and then format with date() from there. Bit of a pain, and heavier processing then the second way, which is to use MySQL’s DATE_FORMAT. Check out that page, seriously – the list of date modifiers is very comprehensive, and listed here for your pleasure at the bottom of the page.

There’s a great forum post here, mentioning both methods – its well worth a look as the examples are simple and clear.

Quick example would be what we mentioned above, i.e. getting your date in the format of March 21st, 2009. Look how quick it is in MySQL compared to PHP:

SELECT DATE_format(olddate, ‘%M %D, %Y’) as newdate FROM table;

‘olddate’ is the name of your date field in datetime format, and ‘newdate’ is the new var representing the nicely and newly formatted date!

Specifier Description
%a Abbreviated weekday name (Sun..Sat)
%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th1st2nd3rd, …)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal “%” character
%x x, for any “x” not listed above
posted under MySQL, php | No Comments »

jQuery Pagination and Glow

April10

The main jQuery pagination plugin page, bit disappointing to be honest, a lot of vertical scrolling solutions which I think are pointless. But there is one little gem, which isn’t really what you would use for paginating large tables of mysql data for example, but which is ideal for paginating almost any kind of page element! That’s right, you can very, very easily paginate li’s, table rows, whatever you like with Quick Paginate. Definitely worth a look…

And one of the coolest effects I’ve seen, is the glow plugin. You’ve got to see the example. However, the full effects of the glow need to be seen in Safari (for the time being), in other browsers you just get a cool fading color effect – but the future looks bright (ahem)!

Http Authentication with curl_setopt

April10

If you want to access a web page that requires http authentication via a php script, a very handy way to do it is the following:

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, ‘http://my.url.com/password.asp’); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 

curl_setopt($ch, CURLOPT_USERPWD, ‘user_name:password’);

 

$data = curl_exec($ch); 

curl_close($ch);

 

echo “<pre>”; 

print_r($data); 

echo “</pre>”;

posted under php | No Comments »

chm Files on MAC

April8

For reading .chm files on MAC OS, get CHMOX! It’s free and dead cool.

Zend Framework Helpers

April8

If you want to have user defined helpers, here is a brilliant article on them. Well worth checking out, really useful stuff.

posted under php | No Comments »
« Older Entries