30 May 2011 @ 12:58 PM 

I have a software app that checks for updates and downloads them from http://www.some_random_website.com/updatefile.rar

However, I’ve noticed that ISPS tend to cache these files so the software app isnt always getting the latest file.

step 1 – create a php function to download a file

<?php
 
$filename = $_GET['filename'];
$path = $_SERVER['DOCUMENT_ROOT'] . "/$filename";
if ($fd = fopen($path, "r")) 
{
    $fsize = filesize($path);
    header("Cache-Control: no-cache, must-revalidate"); 
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); 
    header("Content-type: application/octet-stream");
    header("Content-Disposition: filename=\"" . $filename . "\"");
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while (!feof($fd)) 
    {
        $buffer = fread($fd, 2048);
        echo $buffer;
    }
}
fclose($fd);
?>

step 2 – rewrite urls so that when requesting /some_file.rar, it redirects to the php app as defined

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)\.rar$ ./getfile.php?filename=$1.rar [NC]
Posted By: Zayin
Last Edit: 30 May 2011 @ 12:58 PM

EmailPermalinkComments (0)
Tags
Categories: php
 21 Jun 2010 @ 5:29 PM 

This is a very basic example of using memcache + PHP

Use at your own peril

$memcache = new Memcache;
$memcache->connect("127.0.0.1");
$sql = "select * from some_huge_table where tx_date <= now()-365 limit 0, 5000";
$key = md5($sql);
$query = $memcache->get($key);
//the query isnt in the cache
if ($query == null)
{
    $query = $this->db->query($sql);
    $query = $query->result();
    //put it in the cache
    $memcache->set($key,$query,0,600);//10 minute expiry
}
if (count($query) > 0)
{
//do something with $query
}

This example loads memcached, looks for a key, and if its not there, stores it. SIMPLE

****UPDATE****

Today while going through CI framework, I realized that CI can do its own query caching, albeit to disk. For more info on CI query caching, look go here

To change this to memcached caching should be a cinch, and indeed, it is. Head over here to see how.

So without having to change a single line of code in your application, you can take full advantage of memcached for caching query results

Posted By: Zayin
Last Edit: 23 Jun 2010 @ 02:07 AM

EmailPermalinkComments (4)
Tags
Tags: ,
Categories: php
 21 Jun 2010 @ 8:19 AM 

Memcache is a very simple caching system that uses memory to store objects. As you may already know, memory is faster to read than hard drive. A site will take a lot less time to read a database result cached in memory. To make the best use of memcache, you should install the memcached module. For this post we used Ubuntu Server 10.04, but all commands should work on most Ubuntu editions.

I have chosen to use memcached, rather than memcache. Have a look here to view a comparison

First, install the memcached package, php-pear (required for pecl), php5-dev (required for phpize) and libmemcached-dev

sudo apt-get install memcached
sudo apt-get install php-pear
sudo apt-get install php5-dev
sudo apt-get install libmemcached-dev

next, install memcached using pecl

sudo pecl install Memcache

Also, we need to enable the memcache extension on php:

sudo echo "extension=memcache.so" > /etc/php5/apache2/conf.d/memcache.ini

Add the following line to your php.ini file.

memcache.hash_strategy="consistent"

You can add it anywhere in the file.

Next you need to start an instance of memcache, you can start a daemon with the following command:

memcached -d -m 2048 -l 10.0.0.40 -p 11211

If you are only using a single server, then you only need to include this line to your site’s settings.php file.

$conf['cache_inc'] = '/sites/all/modules/memcache/memcache.inc';

The final step is to restart apache and then switch your site back online if it was offline.

Posted By: Zayin
Last Edit: 21 Jun 2010 @ 08:34 AM

EmailPermalinkComments (2)
Tags
Tags: ,
Categories: linux, php
 06 Feb 2010 @ 4:57 PM 

Just a quick note on how to style columns in grids and fields in editors

$grid->column('last_cost','Last Unit Cost Price (of last import)');
$grid->columns[2]->attributes = array('style' => 'text-align: right');

It seems simple, but it took me ages to figure out

Posted By: Zayin
Last Edit: 06 Feb 2010 @ 04:57 PM

EmailPermalinkComments (1)
Tags
Tags: ,
Categories: php, rapyd
 04 Feb 2010 @ 5:28 AM 

This data edit sample uses some of the nicer features of Rapyd editing, namely:
1) Field Editing
2) Drop down lists (static and dynamic from db)
3) validation
4) Hidden fields

        $edit = new dataedit_library();
        $edit->label = $this->title;
        $edit->back_url = site_url('users_list');
 
        $edit->source('user');
        $edit->field('dropdown','customer_id','Customer')
            ->options('SELECT customer_id, company_name FROM customer')
            ->rule('required');
        $edit->field('input','user_firstname','First Name')
            ->rule('min_length[3]|max_length[20]');
        $edit->field('input','user_surname','Last Name')
            ->rule('min_length[3]|max_length[20]');
        $edit->field('input','user_idnumber','ID Number')
            ->rule('exact_length[13]|unique[user]|numeric');
        $edit->field('input','email','Email Address')
                ->rule('valid_email');
        $edit->field('dropdown','province_id','Province')
            ->options('SELECT province_id, province_description FROM province where country_id = 1')
            ->rule('required');
        $edit->field('dropdown','country_id','Country')
            ->options('SELECT id, name FROM country')
            ->rule('required');
        $edit->field('dropdown', 'security_role_id', 'Security Role ID')
            ->options(array("1"=>"Administrator", "2"=>"User"));
        $edit->field('hidden','security_role_id','Security Role ID')->insert_value(2);
        $edit->field('hidden','activated','activated')->insert_value(1);
        $edit->buttons('modify','save','undo','back','delete');
        $edit->build();
        $data['head']    = $this->rapyd->head();
        $data['title']   = $this->title;
        $data['content'] = $edit->output.'<br />';
Posted By: Zayin
Last Edit: 04 Feb 2010 @ 05:28 AM

EmailPermalinkComments (1)
Tags
Tags: ,
Categories: php, rapyd
 04 Feb 2010 @ 5:21 AM 

Rapyd has some pretty useful validation rules. Pretty much all the ones that are in CodeIgniter + a few more

first create your edit grid

$edit = new dataedit_library();
$edit->label = $this->title;
$edit->back_url = site_url('users_list');
 
$edit->source('user');

Here are some of the lesser well known ones:

unique[table_name] – if you use this validation rule, rapyd will make sure that the field you are using the rule on is unique in table_name

$edit->field('input','user_idnumber','ID Number')
    ->rule('exact_length[13]|unique[user]')
    ->rule('numeric');

valid_email – this will make sure the field is a valid email address

$edit->field('input','email','Email Address')
        ->rule('valid_email');

in_range[low,high] – this will make sure that the value you enter is between (low) and (high)

$edit->field('input','selling_incl','Selling (Incl VAT)')
    ->rule('required|in_range[' . $avg_cost . ',' . $real_value . ']');
Posted By: Zayin
Last Edit: 04 Feb 2010 @ 05:21 AM

EmailPermalinkComments (1)
Tags
Tags: ,
Categories: php, rapyd
 28 Jan 2010 @ 3:55 PM 

This post deals with adding filters to a grid so that you can filter the result set. The reason for this is that you might have large grids (eg 100 000 items) and you dont necessarily want to search through all that info to get to the row you want to view/edit

$filter = new datafilter_library();
$filter->label = 'User Filter';
$filter->db->select('user.*, customer.company_name, customer.trading_entity_type_id');
$filter->db->from('user');
$filter->db->join('customer', 'user.customer_id = customer.customer_id');
$filter->field('dropdown', 'trading_entity_type_id', 'Trading Entity Type')
  ->options(array('1'=>'Associate',
                        '2'=>'Wholesaler',
                        '3'=>'Retailer'));
$filter->field('input','company_name','Company Name');//->attributes(array('style' => 'width:170px'));
$filter->field('input','user_name','User Name');
$filter->field('input','user_idnumber','ID Number');
$filter->field('input','email','email');
$filter->buttons('reset','search');
$filter->build();
 
$grid = new datagrid_library();
$grid->label = $this->title;
$grid->source($filter);
$grid->column('company_name','company');

Notice that the grid is no longer linked to a query, but is linked to the filter.

Filtered grid sample

Posted By: Zayin
Last Edit: 28 Jan 2010 @ 03:55 PM

EmailPermalinkComments (2)
Tags
Tags: ,
Categories: php, rapyd
 31 Dec 2009 @ 5:09 AM 

This post details some of the finer intricacies of working with Rapyd.

To set a title on the grid :

$provider_item_grid = new datagrid_library();
$provider_item_grid->label = 'My grid title';

To show more than 5 rows in a grid

$provider_item_grid->per_page = 100000;

To format the output text for a column in a grid

$provider_item_grid->column('real_value','Denomination Face Value')->callback('format');
.
.
.
.
function format($row)
{
    $avalue = $row['real_value'];
    $obj =& get_instance();
    return currency_format($avalue);
}

To make a a column that links elsewhere:

$provider_item_grid->column('item_description','Denomination')->url(site_url('service_provider_items/?show={service_provider_item_id}'),'');

To enable sorting on a column

$provider_item_grid->column('item_description','Denomination', true);
Posted By: Zayin
Last Edit: 31 Dec 2009 @ 05:09 AM

EmailPermalinkComments (1)
Tags
Tags: ,
Categories: php, rapyd
 03 Dec 2009 @ 1:08 PM 

encrypting and decrypting between different languages and character sets can be painful. It took me many hours of tweaking to get to a working robust solution.

The PHP code will encrypt and decrypt a string.

The java code will successfully decrypt a string encrypted by the PHP code.

Encrypt and decrypt in PHP:

function encryptString($pin)
{
    $cipher = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');
    // The block-size of the Blowfish algorithm is 64-bits, therefore our IV
    // is always 8 bytes:
    $iv =  '12345678';
    $key = encryptKey(); //32chars = 256bit encryption
    // The strengh of the encryption is determined by the length of the key
    // passed to mcrypt_generic_init
    if (mcrypt_generic_init($cipher, $key, $iv) != -1)
    {
        $cipherText = mcrypt_generic($cipher, $pin);
        mcrypt_generic_deinit($cipher);
        return $cipherText;
    } else
    {
        mcrypt_generic_deinit($cipher);
        return "";
    }
}
 
function decryptString($pin)
{
    $iv =  '12345678';
    $key = encryptKey();
    return mcrypt_cbc(MCRYPT_BLOWFISH, $pin, $ciphertext, MCRYPT_DECRYPT, $iv);
}
 
function hex2bin($h)
{
    //this function is the opposite of php's bin2hex
    if (!is_string($h)) return null;
    $r='';
    for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); }
    return $r;
}
 
//usage:
$encrypted_string = encryptString('Some text to encrypt');
$decrypted_string = decryptString($encrypted_string);

To decrypt in JAVA

private static String decryptBlowfish(String to_decrypt)
{
    try
    {
        String iv = "12345678";
        byte[] IVBytes = getBytes(iv);
        if (IVBytes == null)
        {
            return null;
        }
        IvParameterSpec IV = new IvParameterSpec(IVBytes);
        String strkey = "12345678901234567890123456789012"; //must be the same key we used to encrypt the data
        byte[] strkeyBytes = getBytes(strkey);
        if (strkeyBytes == null)
        {
            return null;
        }
        SecretKeySpec key = new SecretKeySpec(strkeyBytes, "Blowfish");
        try
        {
            Cipher cipher = Cipher.getInstance("Blowfish/CBC/NoPadding");
            try
            {
                cipher.init(Cipher.DECRYPT_MODE, key, IV);
                try
                {
                    byte[] encrypted = getBytes(to_decrypt);
                    if (encrypted == null)
                    {
                        return null;
                    }
                    byte[] decrypted = cipher.doFinal(encrypted);
                    return new String(decrypted);
                } catch(Exception e)
                {
                    errorMsg = "ERROR: decryptBlowfish(dofinal) : to_decrypt :" + to_decrypt + " : message : " + e;
                    return null;
                }
            }catch (Exception e)
            {
                errorMsg = "ERROR: decryptBlowfish(init) :" + e;
                return null;
            }
        }catch (Exception e)
        {
            errorMsg = "ERROR: decryptBlowfish(getInstance) :" + e;
            return null;
        }
    } catch (Exception e)
    {
        errorMsg = "ERROR: decryptBlowfish :" + e;
        return null;
    }
}
 
private static String hexToString(String input, int groupLength)
{
    try
    {
        StringBuilder sb = new StringBuilder(input.length() / groupLength);
        for (int i = 0; i < input.length() - groupLength + 1; i += groupLength)
        {
            String hex = input.substring(i, i + groupLength);
            sb.append((char) Integer.parseInt(hex, 16));
        }
 
        return sb.toString();
    } catch (Exception e)
    {
        errorMsg = "ERROR: hexToString :" + e;
        return null;
    }
}
 
private static byte[] getBytes(String toGet)
{
    try
    {
        byte[] retVal = new byte[toGet.length()];
        for (int i = 0; i < toGet.length(); i++)
        {
            char anychar = toGet.charAt(i);
            retVal[i] = (byte)anychar;
        }
        return retVal;
    }catch(Exception e)
    {
        errorMsg = "ERROR: getBytes :" + e;
        return null;
    }
}
 
 
//USAGE
String stringSignature = hexToString(signature, 2);
String decryptSignature = decryptBlowfish(stringSignature);
Posted By: Zayin
Last Edit: 03 Dec 2009 @ 01:08 PM

EmailPermalinkComments (11)
Tags
Tags: , ,
Categories: java, php
 21 Nov 2009 @ 9:42 AM 

When using activerecord in CodeIgniter to build your queries, it often happens that you want to see what SQL is being generated.

There are 2 ways to do this

1) The application profiler will show the sql used. Just add

$this->output->enable_profiler(TRUE);

2) OR

$str = $this->db->last_query(); 
echo $str;
Posted By: Zayin
Last Edit: 23 Nov 2009 @ 09:47 AM

EmailPermalinkComments (0)
Tags
Tags: ,
Categories: php

 Last 50 Posts
 Back
Change Theme...
  • Users » 1
  • Posts/Pages » 38
  • Comments » 57
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

Links



    No Child Pages.

Portfolio



    No Child Pages.