Thursday, November 12, 2009

Force File Download with PHP

Here is the code taken from
function output_file($file, $name, $mime_type='')
{
/*
This function takes a path to a file to output ($file),
the filename that the browser will see ($name) and
the MIME type of the file ($mime_type, optional).

If you want to do something on download abort/finish,
register_shutdown_function('function_name');
*/

if(!is_readable($file)) die('File not found or inaccessible!');

$size = filesize($file);
$name = rawurldecode($name);

/* Figure out the MIME type (if not specified) */
$known_mime_types=array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain"
);

if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
};
};

@ob_end_clean(); //turn off output buffering to decrease cpu usage

// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');

header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');

/* The three lines below basically make the
download non-cacheable */

header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

// multipart-download and download resuming support
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}

$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}

/* output the file itself */
$chunksize = 1*(1024*1024); //you may want to change this
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);

while(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length)
)
{
$buffer = fread($file, $chunksize);
print($buffer); //echo($buffer); // is also possible
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else die('Error - can not open file.');

die();
}

/*********************************************
Example of use
**********************************************/


/*
Make sure script execution doesn't time out.
Set maximum execution time in seconds (0 means no limit).
*/

set_time_limit(0);
$file_path='that_one_file.txt';
output_file($file_path, 'some file.txt', 'text/plain');

Thursday, October 08, 2009

Touch Command for Windows

If you every need to change the last modified date on a windows file here is a command that does so

copy /b test.txt +,,

Source:

Thursday, July 30, 2009

Keeping your Geolocation up to date

If you host Open Ads or use Geographic targeting you will realise that from time to time you need to update you geo-location data file. This is an shell script to help

Script

#!/bin/sh
# retrieve and update Geolocation database

#get date...
today=`date +%d-%m-%y`
#today=`date +%d-%m-%y` #date in this format 04-08-09
#today=`date +%Y%m%%d` #date in this format 20090804

#go to folder
cd /home/adserver/

#grab data file
/usr/bin/wget -q --limit-rate=100k wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz

# Check if file exists

if [ -f /home/adserver/GeoIP.dat.gz ]
then
#backup current file
if [ -f /home/adserver/GeoIPCity.dat ]
then
/bin/mv /home/adserver/GeoIP.dat /home/adserver/GeoIP-$today.dat
fi

#uncompress new file
/bin/gzip -d /home/adserver/GeoIP.dat.gz
fi

Cron Job
Let us say the file above is called update.sh. Add this to your cron.

0 2 7 * * /bin/sh /home/adserver/update.sh > dev/null 2>&1

Notes:

1. Ensure the full paths for mv, cd, wget are correct
you can find that by doing a whereis command name e.g whereis mv

2. Change "/home/adserver/" to the your path to where you want to put the file

3. if " if [ -f filename ] ..." does not work try "if[ -e filename ].."

4. The service is free, from maxmind.com so I try not to abuse their servers.
a) limit the download rate to --limit-rate=100k
b) update once month usually about the 5,6,7th ( the say the 1st of the month but the updates are usually late
( paid services are available)

5. you an remove the old file using "/bin/rm -f /home/adserver/GeoIP.dat " but I am one for backups


Useful

Monday, June 29, 2009

MYSQL, Foreign Keys

Here is my example and some pointers that lead a solution to my problem.

'contact_id' in table 'note' referencing 'id' in table 'contact'

CREATE TABLE 'contact' (
'id' int(10) unsigned NOT NULL auto_increment COMMENT 'Unique Contact ID',
PRIMARY KEY ('id'),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=0 ;

CREATE TABLE 'note' (
'id' int(10) unsigned NOT NULL auto_increment COMMENT 'Note ID',
'entity_table' varchar(64) collate utf8_unicode_ci NOT NULL COMMENT 'Name of table where item being referenced is stored.',
'entity_id' int(10) unsigned NOT NULL COMMENT 'Foreign key to the referenced item.',
'contact_id' int(10) unsigned default NULL COMMENT 'FK to Contact ID creator',
PRIMARY KEY ('id'),
KEY 'index_entity' ('entity_table','entity_id'),
KEY 'FK_note_contact_id' ('contact_id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=0;

ALTER TABLE 'note'
ADD CONSTRAINT 'FK_note_contact_id' FOREIGN KEY ('contact_id') REFERENCES 'contact' ('id') ON DELETE SET NULL;

Things to note

1. Tables must be same type. [in this case InnoDB]
2. The columns must be the same type.[in this case int(10)]
3. The Attributes must be the same unsigned
4. The field that is referencing must be default set to null "default NULL"
i.e. contact_id , must be default NULL. (If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL.)
5. Indexes on foreign keys and referenced keys
6. Watch your case. the FK is case sensitive

If you need to alter a table do the following

set foreign_key_checks = 0;
...
Alter table etc..
..
set foreign_key_checks = 1;

Useful reference:
See also:

Thursday, June 04, 2009

LIME 3G speeds

Testing a lime 3g Modem... 

Received the following speeds in the New Kingston Area

The  installation on a Mac 10.5  failed but worked flawlessly on Windows XP.

During the so far I have received burst speeds of up to 5.3 Mbps per second.  The problem is this if you have to pay for the data you could run in trouble

Without downloading any programmes, just regular browsing in no time over 6 MB was consumed.

Friday, May 22, 2009

IE Tester for IE Version Testing

For many web developers cross browser testing has been a pain. One of the greatest pains has been test the different versions of IE, 5.5, 6, 7 and now 8. Users of browsers like Firefox, Safari and Opera tend to upgrade regular and even in some cases the updates are automated.

The reality however is that IE still controls the majority share in the browser market thanks to Microsoft dominance of the Operating System found on personal computers around the world.

Here is a good tool for testing different versions of IE.
Here are some reviews

Go ahead and give it a try. Solving those CSS and JavaScript errors should be alot easier now.

Tuesday, April 07, 2009

Javascript Frame works

Today I got a e-mail asking about Javascript frame works.  I am no expert but from my little fooling around I like JQuery..

Here you can read what a few other persons have to say.

  • Specky Boy lists their top 10 (not in order) and the his audience seems to give JQeury the edige.
  • Sixrevisions they also list their top 10 (not in order) but the comments are again worth reading.

This is one promotion I really endorse
“jQuery is a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way that you write JavaScript”.
As usual it boils doing to what you are doing, your style and what best suits you project

Friday, March 20, 2009

Windows Batch File

I needed  the get the date for batch file on Windows in this format yyyy-mm-dd e.g. 2009-03-20 so I did a little research on the internet.

The result is I found this snippet at tech-recipes.com

FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B

SET mydate=%yyyy%-%mm%-%dd%

There are some nuisances so for more discussion on the top visit  tech-recipes.



Audio Noise Removal

Many times in record clips we end up with unwanted background noise. Recently faced with the situation, I  needed to clean up some audio and...