Saturday, April 30, 2011

PHP To Loop Through Alphabet & Display Categories

The alphabet can be incremented in PHP like numbers can, so incrementing through an alphabetical list is possible.

$capital="A";
$capital++;
echo $capital;
(returns b)

To write all 26 letters of the alphabet
$capital=A;
for ($i=1; $i<=26; $i++)
{
echo $capital;
$capital++;
}
(returns whole alphabet)

I wanted to display categories, in divs, in alphabetical order, querying a database to get categories beginning with each letter, to display in the div corresponding to that letter.

It ends up looking like this...



I set css properties for the divs as follows..
.prop{
height:200px;
float:right;
width:1px;
display:inline;
padding:5px;
margin:5px;
float:left;
width:160px;
border-style:solid;
border-width:2px;
border-color:#2491EE;
}

The php I did as follows...


$capital=A;
for ($i=1; $i<=26; $i++)

{
/*echoes the current letter, images could be used if named A.jpg B.jpg etc*/

echo "<div class=\"prop\"> <strong>".$capital."</strong><br />";

/*The mysql quries a category table returning all categories beginning the current letter*/
$result=mysql_query("SELECT category FROM categories WHERE category REGEXP '^".$capital."' ORDER BY category") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$cat= $row['category'];

/*the following line echoes the category name and links to a category page, passing the name as a variable*/
echo "<a href='category.htm?category=$cat'>".$cat."</a><br />";
}
echo "</div>";
$capital++;
}

Monday, April 25, 2011

Comparing Dates In Epoch Seconds

I put together this script to check the date in a table, convert it to epoch seconds, and then check todays date minus seven days in epoch seconds, to make it possible to do a comparison (greater than) for the dates. So if a date is within the last week, it is returned.

Not so necessary for just seven dates as they could each be declared individually, but for any greater date range would be useful, as converting to epoch seconds means that the two dates can be compared as to which is greater, with later dates obviously being greater than....



#!/bin/sh

#GET CURRENT DATE IN EPOCH SECONDS#

export todaysdate=`date +%s`

#7DAYS AGO IS -604800 SECONDS#
sevendaysago="$(( $todaysdate - 604800 ))"

#QUERY DATABASE TO GET MERCHANT ID ANF LOOP THROUGH EACH#

merchant=`
mysql -u username --password=password << eof
use databasename;
SELECT merchantid FROM tablename;
eof`


for ARG1 in $merchant
do

#QUERY DATABASE TO GET DATE DATA WAS ALTERED FOR EACH MERCHANT#
date=`
mysql -u username --password=password << eof
use database;
SELECT lastUpdated FROM tablename WHERE merchantid='$ARG1';
eof`

for ARG2 in $date
do

#IGNORE COLUMN NAME IN RETURNED RESULT#
if [ "$ARG2" != "lastUpdated" ]; then
#CONVERT DATE TO EPOCH SECONDS#
export recordeddate=`date -d "$ARG2" +%s`


#COMPARE RECORDED DATE TO DATE SEVEN DAYS AGO#
if [ $recordeddate -gt $sevendaysago ]; then

#DO WHATEVER#
echo $ARG1 data changed in the last seven days on $ARG2

fi
fi
done
done


Linux Questions

Wednesday, April 20, 2011

Shell Script Useful Snippets

Returns todays date mysql style(2011-04-20)

#!/bin/sh

today=`eval date +%Y-%m-%d`
echo $today




Returns yesterdays date mysql style(2011-04-19)

#!/bin/sh

yesterday=`eval date --date=yesterday +%Y-%m-%d`
echo $yesterday



Returns last seven days dates mysql style(2011-04-20) (alternative method for greater number of dates in range http://www.linuxquestions.org/questions/programming-9/bash-script-date-range-876326/)

#!/bin/sh

export yesterday=`date --date="yesterday" +%Y-%m-%d`
export twodaysago=`date --date="2 days ago" +%Y-%m-%d`
export threedaysago=`date --date="3 days ago" +%Y-%m-%d`
export fourdaysago=`date --date="4 days ago" +%Y-%m-%d`
export fivedaysago=`date --date="5 days ago" +%Y-%m-%d`
export sixdaysago=`date --date="6 days ago" +%Y-%m-%d`
export sevendaysago=`date --date="7 days ago" +%Y-%m-%d`

echo yesterday was $yesterday
echo two days ago was $twodaysago
echo three days ago was $threedaysago
echo four days ago was $fourdaysago
echo five days ago was $fivedaysago
echo six days ago was $sixdaysago
echo seven days ago was $sevendaysago



bash script For Each Loop On mysql result -dont know why but the column name is returned in the results loop as the first result, so i put a condition to oly return if it was not the column name, that loops through all the values.

#!/bin/sh

##MYSQL QUERY##
variable=`
mysql -u username --password=password << eof
use databasename;
SELECT somecolumn FROM table WHERE anothercolumn='2011-04-19';
eof`

##for each##

for ARG in $variable
do
if [ "$ARG" != "somecolumn" ]; then
echo $ARG was updated yesterday
fi
done


Tuesday, April 19, 2011

Bash Script - MYSQL query (match files in directory with certain files in db table)

Get all files in a directory, compare it to filenames stored in database, where a condition is met and return only the filenames that match that condition.



#!/bin/bash

##GET & LOOP THROUGH FILES IN DIRECTORY##
cd /path/to/directory/
##FIND ALL TEXT FILES##
FILES=*.txt
for f in $FILES
do

##GET TXT FILENAME##
TXTFNAME="$f"

##ALTER IF NECESSARY##
export TXTFNAME1=`echo $TXTFNAME | sed -e 's/fromthis/tothis/g'`

##MYSQL QUERY##
variable=`
mysql -u username --password=password << eof
use databasename;
SELECT column FROM table WHERE column='keyword';
eof`

##IF FILENAME EQUALS FILENAME IN DB##
if [[ $variable =~ .*$TXTFNAME1.* ]]; then

echo $TXTFNAME1 is a match


fi

#end of loop#
done

Sunday, April 17, 2011

php change date format for inserting into MYSQL

This code is based on http://40shadows.wordpress.com/2008/09/30/change-date-format-in-php/

//input format: d/m/yy or yyyy
$date = '24/12/08';
$dtmp = explode("/",$date);
$dadate = mktime(0,0,0,$dtmp[1],$dtmp[0],$dtmp[2]);
echo date('d-m-Y',$dadate);
//outputs 24-12-2008


//input format: yyyy-m-d
$date2 = '2011-04-25';
$dtmp = explode("-",$date2);
$dadate2 = mktime(0,0,0,$dtmp[1],$dtmp[2],$dtmp[0]);
echo date('d/m/Y',$dadate2);
//outputs 25/04/2011

Full Text Search MySQL

Create a table called extypes, with 3 columns, ID , description and calpermin

CREATE TABLE IF NOT EXISTS `extypes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` text NOT NULL,
`calpermin` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

Insert some values into the table

INSERT INTO `extypes` (`id`, `description`, `calpermin`) VALUES
(1, 'Rowing Machine Moderate', 6),
(2, 'Walking Moderate', 4),
(3, 'Shopping With Trolley', 2),
(4, 'Dancing Moderate', 2),
(5, 'Dancing Vigorous', 4)

Make the description column searchable

ALTER TABLE `extypes` ADD FULLTEXT `search_index` (
`description`)

Search for the keyword "rowing" in the description

SELECT * from extypes WHERE MATCH (description) AGAINST('rowing')

Thursday, April 07, 2011

Mod_Pagespeed Update On Linux With cPanel & WHM

I started using a really good new mod, mod_pagespeed on my server that speeds up web page delivery alot. It can be put in Virtual Hosts for individual websites, or applied to all websites on a server.

If a server has cpanel/whm installed, manually updates are required when a new release comes out, so I wrote a bash script to put in cron.monthly to do this. It is based on the original installation guide at http://i-comers.com/showthread.php?t=1598691

It just checks to see if the file at code.google.com is newer than the file on the server and then goes through the various installation commands, if it is, then restarts httpd. The sed section could be further modified to include any specific config that is in pagespeed.conf, but my config is in virtual hosts so I can just rewrite the paths to the mods and switch it off there and leave the config as is in httpd.conf, virtual hosts. Although it would be worth checking whether any changes have been made in the new version of pagespeed.conf, that I have not written into the code, just an email to tell me if updated, so that can be checked manually against the bak version, because the config file, as far as I know, usually stays the same....

#!/bin/bash

##if date of remote file is newer than date of local file then update mod pagespeed##

if [[ https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-beta_current_x86_64.rpm -nt /usr/local/src/mod_pagespeed/mod-pagespeed-beta_current_x86_64.rpm ]]; then


echo Mod_Pagespeed Upgrade Required!

##remove previous version##
rm -r /usr/local/src/mod_pagespeed/

cd /usr/local/src
mkdir mod_pagespeed
cd mod_pagespeed
##this is the specific rpm url required for download from google##
wget https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-beta_current_x86_64.rpm

rpm2cpio mod-pagespeed-beta_current_x86_64.rpm | cpio -idmv
cp /usr/local/src/mod_pagespeed/usr/lib64/httpd/modules/mod_pagespeed.so /usr/local/apache/modules/

##bakup previous pagespeed config##
cp /usr/local/apache/conf/pagespeed.conf /usr/local/apache/conf/pagespeedbak.conf

##the following sed commands rewrite parts of pagespeed.conf as required for different paths to files on cpanel servers. Changes should be made as per each individuals pagespeed.conf requirements.##

sed -i 's/ModPagespeed on/ModPagespeed off/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf

sed -i 's/LoadModule pagespeed_module \/usr\/lib64\/httpd\/modules\/mod_pagespeed\.so/LoadModule pagespeed_module modules\/mod_pagespeed\.so/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf

sed -i 's/LoadModule deflate_module \/usr\/lib64\/httpd\/modules\/mod_deflate\.so/LoadModule deflate_module modules\/mod_deflate\.so/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf

sed -i 's/ModPagespeedFileCachePath \"\/var\/www\/mod_pagespeed\/cache\/\"/ModPagespeedFileCachePath \"\/var\/mod_pagespeed\/cache\/\"/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf

sed -i 's/ModPagespeedGeneratedFilePrefix \"\/var\/www\/mod_pagespeed\/files\/\"/ModPagespeedGeneratedFilePrefix \"\/var\/mod_pagespeed\/files\/\"/g' /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf


##copy the new pagespeed.conf to httpd##
cp /usr/local/src/mod_pagespeed/etc/httpd/conf.d/pagespeed.conf /usr/local/apache/conf/

##set directory permissions and create directories for files and cache##
chmod 755 /usr/local/apache/modules/mod_pagespeed.so
mkdir /var/mod_pagespeed/{cache,files} -p
chown nobody:nobody /var/mod_pagespeed/*

##restart httpd##
service httpd restart

##send mail to alert of update so that pagespeed.conf can be altered if necessary, can be checked against pagespeedbak.conf created during the update.##

SUBJECT="Mod Pagespeed has been updated"
EMAIL="someone@somewhere.com"
EMAILMESSAGE="/tmp/emailmessage.txt"
echo "Mod Pagespeed has been updated, check pagespeed.conf"> $EMAILMESSAGE
/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE
rm /tmp/emailmessage.txt

##else if the rpm on google has not been updated then just say so##
else
echo Mod_Pagespeed Upgrade not required at this time!
fi




Obviously the SED section of the code would need to be altered depending on what configs are set in pagespeed.conf, the above example is what I require in mine.