Mar 29 2013

Multibyte php substring without the mbstring extension

In the rare case where the multibyte string (mbstring) extension is not enabled and cannot, for whatever reason, be enabled, it becomes difficult to create a substring using international characters without causing the string to be converted into gibberish.

There is a way around this using regular expressions and preg_match. If “(*UTF8)” or “/u” is used in the regular expression than the preg match will successfully return the desired substring. Two examples follow.


preg_match('/(*UTF8)^.{1,20}/',$multibyte_string,$result_array); 

preg_match('/^.{1,20}/u',$multibyte_string,$result_array); 

Ideally the mbstring functions should be used, but this serves when that is not possible

Share

Jul 2 2010

Django on Dreamhost: Virtual Python Install

After writing the backend for a new web app in python I went to start working on the Django portion. I was planning on hosting this application with a Dreamhost shared hosting plan which already has Python 2.5 installed. After trying unsuccessfully to install some new middleware with easy_install, I started looking for a solution that gives me more control over what I want to do with Python without having to purchase dreamhost vps hosting. It seems that you can set up a virtual python install in your home directory and it was surprisingly easy. I’ve only had the need to use this virtual python install on Dreamhost, which is using Debian, but I can’t see any reason why it wouldn’t work on other environments.

Note that this is completely unnecessary if you have root access.

Assuming you already have a shell account and you are ssh’d in, execute these commands to install your virtual python environment:

$ wget http://peak.telecommunity.com/dist/virtual-python.py 
$ python virtual-python.py

Those commands copy the Python binary to your /home/user/bin directory and sets up symbolic links to the system wide libraries. This means that the ~/bin/python executable will have access to the same libraries as the system Python but that any extra installed software will not affect the system wide Python install.

Next you should add the ~/bin directory to your PATH by adding this block to your .bash_profile:

 if [ -d ~/bin ] ; then     
    PATH=~/bin:"${PATH}" 
fi 

You’ll have to log out and back in for this to take effect.
After you’re logged back in, run these commands to install easy_setup:
$ wget http://peak.telecommunity.com/dist/ez_setup.py 
$ python ez_setup.py 

Now you should be able to install whatever you want using easy_install. The first thing I did was install django-db-log using this command:
$ easy_install django-db-log

Share

Nov 9 2009

This is How Credit Card Numbers Are Generated

I was reading an article today in one of my favorite publications about how to get free trials without actually using your credit card by generating valid credit card numbers using a simple algorithm called the Luhn check. So I wrote a little script that generates credit card numbers that will be deemed valid by most software checks. This will work because the service won’t know that the credit card is invalid until they actually try to charge it. Well, the card may be valid since my script uses random numbers. Obviously this if for informational purposes only and should never actually be used.

Most credit card numbers are validated using an algorithm called the “Luhn check”. This is a very simple algorithm that doubles the odd digits and does a sum to see if the number is divisible by 10. The credit card companies use a slightly different version that involves a check digit as the last digit. To generate a credit card number that will pass most validation software (as long as they don’t actually try to process the credit card) one only needs to follow these steps to make sure that the generated credit card is valid.

Choose 16 random numbers starting with a 3,4,5 or 6.
Starting with the first digit, double every other number.

If doubling a number results in a two digit number, add those digits together to produce a single digit number

Replace the odd digits with the new ones just created. You should now have 16 numbers consisting of all the new numbers and the original even numbers

Add up all sixteen numbers.

Manipulate the check digit so that the sum is divisible by 10.

Replace the last digit of the original random string with the new manipulated check digit.

Thats really all there is to it. Check out the source of my javascript credit card generator if you want to see how to generate and validate the credit card numbers.

The reason for starting with a 3,4,5, or 6 is that different card types start with different digit. The 3 is American Express, 4 is Visa, 5 is Master Card, 6 is a Discover Card.

Some companies use more digits to show that the card is from them. For example 5254 is a Master Card from the Bank of America and 4013 shows that it is a Visa card from Citibank. Also note that the expiry date has nothing at all to do with the card number.

Share

Oct 7 2009

Reset Mysql Root Password On Linux

If you have root access to a linux server and you don’t have the root mysql password, but need it, then you can easily reset the root mysql password in just a few commands. These commands probably differ depending on what linux distro you use. I was using Ubuntu 9.04 (Jaunty Jackalope) when I wrote this.

Firstly you will want to turn the mysql service off.


codytaylor@server:~$ sudo /etc/init.d/mysql stop
 * Stopping MySQL database server mysqld   

Now we restart the mysql server with the ‘skip-grant-tables’ option which basically allows anyone to do whatever they like. It’s usually preferable to include the ‘skip-networking’ option so that only localhost (you) have access to the naked database.

 codytaylor@server:~$ sudo mysqld_safe --skip-grant-tables --skip-networking &

Now all that is left is actually changing the root password. Log into the mysql monitor and change the root password.

codytaylor@server:~$ mysql -u root mysql
mysql> UPDATE user SET Password=PASSWORD('password') WHERE User='root';
mysql> FLUSH PRIVILEGES;

Those commands will reset the root mysql password to ‘password’. Now you’ll probably want to restart the mysql service and have it run normally.

codytaylor@server:~$ sudo /etc/init.d/mysql restart

If you are using windows and you want to reset the mysql root password then check the mysql documentation.

Share

Sep 30 2009

Vim Syntax Highlighting With .vimrc

I recently had to move all my sites over to a new host due to Lunarpages basically kicking me off. I chose DreamHost because they were having a promotion where I get a full year for $10. One of my coworkers uses them with no complaints and they give free shell access.

Vim is my editor of choice but I hate coding without syntax highlighting and DreamHost doesn’t have Vim Syntax highlighting on by default. It is possible to type “:syntax enable” when already in the editor to enable syntax highlighting on the current file that you’re editing but after closing it and opening another file you will be forced to do it again.

To enable syntax highlighting forever I had to edit the .vimrc file which lives in my home directory. It didn’t exist so I had to create one. After I created this file I added the lines :


syntax enable
set background=dark
set nocompatible
set autoindent
set smartindent
set tabstop=4
set shiftwidth=4
set showmatch
set ruler
set virtualedit=all

Alternatively you could put ‘background=light’ which will make the colors more readable if your console is black text on a white background. The rest of those lines are just personal preference and put there so I can copy and paste them elsewhere. More info and a great example can be found at this vim site.

Share

Sep 22 2009

Linux Bang Commands

If you spend a lot of time on the linux command line you quickly find that it requires a lot of typing and retyping commands. I used to find myself using the exact same lengthy command multiple times a day and to get there I would type “history | grep some_command” and then execute it from there. Since I knew enough to get the job done I hadn’t really tried to find more efficient ways of doing the same old thing. But when I found out about the Linux bang (!) commands I realized how wasteful what I was doing really was.

The exclamation mark, in this case, is referred to as a ‘bang’.

  • !!
    This bang command, when entered into the bash shell will run the previous command. It basically does the same thing as hitting the up arrow to take you to the previous command and then hitting enter.
     
  • !ls
    This will run the last command that started with ‘ls’. If you ran ‘ls -al /etc/init.d’ a few commands ago and then you type ‘!ls’ the full command will be run again, assuming that you haven’t used that command since then.
     
  • !ls:p
    This will display the command instead of running it.
     
  • !$
    This one will run the last word of the previous command. This one is mainly useful for substitutions.
     
  • !$:p
    Instead of running the last word of the previous command this will print it out.
     
  • !*
    This bang command will run the previous command without the first word. This one is also only really useful for substitutions as we see in the examples that follow.
     
  • !*:p
    This will print the previous command without the first word.
     

Here are a few examples of how to use these bash bang commands in everyday command line usage :

For the purposes of these examples, every example will assume these are the last three commands you ran:


    % which firefox
    % make
    % ./foo -f foo.conf
    % vi foo.c bar.c

Getting stuff from the last command:

    Full line:     % !!            becomes:   % vi foo.c bar.c
    Last arg :     % svn ci !$     becomes:   % svn ci bar.c
    All args :     % svn ci !*     becomes:   % svn ci foo.c bar.c
    First arg:     % svn ci !!:1   becomes:   % svn ci foo.c

Accessing commandlines by pattern:

    Full line:     % !./f          becomes:   % ./foo -f foo.conf
    Full line:     % vi `!whi`     becomes:   % vi `which firefox`
    Last arg :     % vi !./f:$     becomes:   % vi foo.conf
    All args :     % ./bar !./f:*  becomes:   % ./bar -f foo.conf
    First arg:     % svn ci !vi:1  becomes:   % svn ci foo.c

I found those examples here.

Share

Sep 21 2009

Vim Syntax Highlighting In Ubuntu

Spending a lot of time on the command line lately I noticed that Ubuntu does not come with Vim syntax highlighting by default. Apparently it installs a version of Vim called vim-tiny which doesn’t include any syntax highlighting.

There are two packages that you can install to get syntax highlighting to work in Vim: vim-full and vim-common. Because I didn’t have gnome installed vim-full was a very large download (like 50MB) and it errored out anyway. vim-common is definitely the way to go.


sudo apt-get install vim

The above line will replace vim-tiny with vim-common and will allow for syntax highlighting. A lot of the time you will have to enable syntax highlighting by editing the vimrc config file either in /etc/vim or in yur home directory. You will need to uncomment the line “syntax on”.

Share

Sep 20 2009

Bash Shell Script Error. “bad interpreter: No such file or directory error”

Today I created a simple shell script and I was getting a few odd errors:


cody@taylor:/var/some_folder/server$ ./process_xml.sh
-bash: ./process_xml.sh: /bin/sh^M: bad interpreter: No such file or directory

I figured it was probably a permissions error or an issue with the shebang (#!/bin/sh) line. I tried removing the shebang line, changing it to use dash or bash explicitly, chmoding to 777 and still no luck and another odd error.


cody@taylor:/var/some_folder/server$ sh process_xml.sh
: not found.sh: 4:

I then checked the log file that the commands were supposed to be writing to and it was filled with ‘^M’ on every line break and the log name itself was followed by a ‘?’. Took a minute or two but I finally clued in that I wrote that script on a windows machine and then exported it to an ubuntu linux server via subversion. It was just a basic text format issue.

Under DOS (Windows/PC) the end of a line of text is signalled using the ASCII code sequence CarriageReturn,LineFeed. Alternately written as CR,LF or the bytes 0x0D,0x0A. On the Macintosh platform, only the CR character is used. Under UNIX, the opposite is true and only the LF character is used.

After a quick :


cody@taylor:/var/some_folder/server$ apt-get install tofrodos
cody@taylor:/var/some_folder/server$ dos2unix process_xml.sh

Everything worked fine.

Share

Sep 14 2009

Optimize WordPress

My webhost recently moved all my sites to a ‘stabilization’ server because my sites were using far to much CPU time and Memory. After reviewing the logs it looked like some bot from India decided to repeatedly scrape one of my sites in it’s entirety without any delays between requests. So the support team over there either requires me to correct the problem or upgrade to a dedicated server plan at ridiculous costs.

Since I didn’t really think that there was a problem I emailed back about the single IP address that was causing all the issues and took steps to prevent requests from that IP address from accessing the site. The support team replied saying that my usage was still high and that I still needed to correct the problem. A little frustrated, I did some research on how to improve my site’s load time and hopefully reduce CPU and memory usage.

Most of my sites use wordpress so I found a large number of articles geared specifically to optimizing wordpress blogs. Before I tried anything I backed up my entire public_html directory and did a dump of all my mySQL databases (took almost 20 minutes for the dump).

Dealing with Plugins
The first thing I did was upgrade all my plugins. Most wordpress plugins allow you to upgrade automatically so all you really have to do is click a button and all the work is done for you. I also deactivated and deleted a surprising number of plugins that I haven’t really had any use for recently. Apparently a lot of free plugins can cause large amounts of unneccesary load on your server due to the authors not really knowing or caring how well their software performs.

Dealing with spam bots
I have been using the Akismet plugin for awhile and it has been reporting large amounts of spam comments and pingbacks. It’s not really something that most people worry about because the spam is automatically deleted after a period of time. It does however increase server load, especially if it’s in the thousands of messages a day. I found this little mod_rewrite snippet to deny any blatent spammers that don’t have a proper referer :


RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*codytaylor.org.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule ^(.*)$ ^http://lemonparty.org//$ [R=301,L]

Cache and Compress
Since most of my pages rarely change it’s silly to generate every page for every request dynamically. After some reading I decided to use WP Super Cache to help optimize my WordPress sites. Of course just enabling Super Cache in the WP Super Cache plugin didn’t really improve load times for the end user but it should reduce server load immensely. What did improve load times drastically was the Super Cache Compression. This was a little more involved to get going but if you’re comfortable with copying and pasting code into a .htaccess file then it shouldn’t be difficult as long as your host supports mod_mime, mod_rewrite, and mod_deflate.

After going through all that, my sites now average at about half the load time they used to. Hopefully my web host feels that I’ve done enough to get off the ‘stabilization’ server so I don’t have to transfer all my stuff to another company.

Share

Aug 16 2009

Re-Enable Grub For Linux After Windows Install

Following the installation of Windows 7 on my desktop machine that was previously running Ubuntu 9.04, I realized that one of my partitions was missing. It was formatted as ext3 so of course it wouldn’t show up in windows. When I went to boot back into linux the grub boot manager was gone. The machine just booted straight into windows 7.

To re-enable grub was a lot simpler than I thought it would be. Since the Ubuntu 8.04 install disc that I had lying around also works as a live disc I booted my desktop off that. Once Ubuntu started up I opened up a terminal and typed these commands:


sudo grub
root(hd0,7)
setup(hd0)
quit

I then rebooted and grub was back to normal with both my Ubuntu operating system and windows 7 listed. Note that hd0,7 was the partition where I installed Ubuntu. If you installed linux before windows then you will probably want to use hd0,0. I installed windows 7 over a broken windows xp partition that I had installed before everything else.

If you installed ubuntu before you installed windows then you’re probably going to have to edit your ‘/boot/grub/menu.lst’ file. The grub documentation may be helpful.

Share