Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Monday, February 3, 2014

Default Parameter Values in PHP Functions

Here's a neat way to set some default parameter values in a PHP function. This only works if a function param is passed in as associative array.

function create_profile($values) {
  if (!is_array($values)) {
    $values = array();
  }
  
  // Default key/values
  $values += array(
      'uid' => NULL,
      'username' => '',
      'mobile' => '99999999',
      'location' => 'POINT(0 0)',
      'fb_id' => ''
  );
}

The most important line is at line 7; where both arrays are merged. If the key/value pair is in the $values array, it will be ignored; else the default values will be used.

Thursday, August 1, 2013

Two things to get Kohana up and running

Here are 2 things to do right after meeting all requirements dictated by Kohana's install script:


  1. Set Cookie::$salt value in application/bootstrap.php:

    Cookie::$salt = 'my*salt*value*';
    

  2. Change base_url value in application/bootstrap.php to match the server configuration:

    Kohana::init(array(
     'base_url'   => '/my_app/',
    ));
    

    In this example, you should be calling http://myserver.com/my_app/

Friday, July 26, 2013

Getting last run SQL from CodeIgniter's DB class

Here's a convenient way to obtain the last executed SQL query when using CodeIgniter's database class.

Code snippet for this example:

$this->db->select('status');
$this->db->from('tbl_user');
$this->db->where('user_id', $user_id);

$results = $this->db->get();

echo $this->db->last_query();

The last call to last_query() will output the actual SQL executed.

Tuesday, May 28, 2013

Parsing a Base64 encoded image string in PHP

Here's a quick way to parse a Base64 encoded image file to check if it's a proper image file. First, the PHP code:

$file_encoded = '[very LONG BASE64 STRING]';

$file_decoded = base64_decode($file_encoded);

$info = getimagesizefromstring($file_decoded);

print_r($size);

If the decoded data is a valid image, the getimagesizefromstring() function will return the following info if said string is a proper image:

Array
(
    [0] => 240
    [1] => 464
    [2] => 3
    [3] => width="240" height="464"
    [bits] => 8
    [mime] => image/png
)

Which makes it perfect for image validation. It returns FALSE if it's not able to parse the input as an image.

You'll need to have the GD image library installed to use this function.

Tuesday, February 5, 2013

APNS and PHP gotcha...

This got me good.  Wondering why your APNS messages aren't delivered?  And there's no error message from your client?  Well now, print out the APS payload after it has been JSON encoded.  A correct message should look like this:

{"aps":{"alert":"Oh really?","badge":1,"sound":"default"},"message_type":"message"}

Compare that to a message which supposedly looks fine but doesn't get sent:

{"aps":{"alert":"Ughieness:nfng","badge":"1","sound":"default"},"message_type":"message"}

See the difference? :)

Yup, the "badge" value.  PHP cast the "badge" value to a string :(  Blogging this so that I don't crack my head in the future.

Sunday, September 23, 2012

Formatting currency in Drupal Commerce

A project I've been involved in uses Drupal Commerce (DC) to manage currency and products.  Here's how to format "normal" values to be DC friendly.  Reason for doing so?  DC stores amount fields as INTEGER.  For instance, an amount of USD99 is stored as 9900 in the table.

There are several functions which you need to make this happen.

commerce_currency_decimal_to_amount(300, commerce_default_currency());

Friday, December 16, 2011

Logging request parameters in CodeIgniter

The application I'm currently working on provides services to mobile devices.  As such, I need to constantly check what values the mobile devices are POST-ing to the application.  Instead of adding a call to all functions in the controllers to perform this task, I decided to implement a hook in the application.

Hooks are supported in CodeIgniter (more info here).  Here's my hook class to perform the logging:

class Logger {
   
    private $CI;
   
    public function __construct() {
        $this->CI =& get_instance();
    }
   
    public function request_logger() {
        $uri = $this->CI->uri->uri_string();
       
            $params = trim(print_r($this->CI->input->post(), TRUE));
       
        log_message('info', '==============');
        log_message('info', 'URI: ' . $uri);
        log_message('info', '--------------');
        log_message('info', $params);
        log_message('info', '==============');
    }
}
To enable hooks, you'll need to edit the config/hooks.php file.  Here's the content of the file to enable the Logger class above:
$hook['post_controller_constructor'] = array(
                                'class'    => 'Logger',
                                'function' => 'request_logger',
                                'filename' => 'Logger.php',
                                'filepath' => 'hooks'
                            );

I chose to use "post_controller_constructor" as it is called before any methods in the controller class is executed.

Output below shows how the output looks like from the application logs:
INFO  - 2011-12-15 05:09:24 --> URI: services/promos/add_comment
INFO  - 2011-12-15 05:09:24 --> Array
(
    [param1] => value1
    [id] => dj3243hasdgasdg
    [msg] => Testing testing
)