Archive for the ‘PHP’ Category

PHP function localizedString

Monday, February 28th, 2011

Last week I was looking for a string PHP function that does a very basic thing:
Take a string with some unknown number of variables in the string and replace them.

E.g.: “Your search for {1} has no results.”
or: “Page {1} of {2}

This is very handy for translations. In some languages you cannot just simply translate the word “page” and the word “of” because the case of the words might be different depending on the context of the word.
The solution is to translate the complete sentence and replace the variables.

Surprisingly, I could not find a quick solution for PHP although it is commonly used in .NET and JAVA.
So I had to build one myself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
     /**
     * Returns a string with some variables replaced
     * E.g.:
     * $str    = "Page {1}  ({1}/{2})";
     * $arg1   = "1";
     * $arg2   = "5";
     * echo localizedString($str,$arg1,$arg2);
     * would return: Page 1 (1/5)
     */

    function localizedString() {

      $patterns     = array();
      $replacements = array();
      $text         = func_get_arg(0);
      $numArgs      = func_num_args();

      for ($i = 1; $i < $numArgs; $i++) {
          $patterns[]     = '/\{'.$i.'\}/';
          $replacements[] = func_get_arg($i);
      }

      return preg_replace ($patterns, $replacements, $text);
    }

You can call the function like this:

1
2
3
4
$str    = "Sorry, the code you entered was invalid. {1}Go back {2} to try again.";
$arg1   = '<a href="history.go(-1)">';
$arg2   = "</a>";
echo localizedString($str,$arg1,$arg2);

FirePHP: debugging and tracing in 10 easy steps

Wednesday, July 21st, 2010

FirePHP enables you to log variables to your Firebug Console.

Data is sent via response headers, this means that the debugging data will not show on your page. FirePHP is ideally suited for AJAX development where clean JSON or XML responses are required.

I have made an example where you use you IP address to make sure that no other users can see the debugging data.
You can use alternative methods if you like.

In my example I have traced the execution of functions, methods and include files.
For this you will need run all code though a single php file. e.g. index.php

Assuming you already use Firefox and FireBug:
1: Download the FirePhp plugin for Firefox here: http://www.firephp.org/

2: Install the plugin

3: Download the FirePhp code here: http://www.firephp.org/HQ/Install.htm

4: Copy the code to your PHP project.

5: Add the following code to your configuration file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require_once 'FirePHP.class.php';
if($_SERVER['REMOTE_ADDR']  == "123.456.789.123"){
    $GLOBALS['firephp'] = FirePHP::getInstance(true);
    // make an array to trace the execution of methods, functions and included files
    $GLOBALS['firephptrace'] = array();
    global  $firephp;
    $firephp->setEnabled(true);
    $options = array('maxObjectDepth' => 10,
                 'maxArrayDepth' => 20,
                 'useNativeJsonEncode' => true,
                 'includeLineNumbers' => true);
    $firephp->getOptions();
    $firephp->setOptions($options);

    // Optionally log all errors, exceptions, and assertion errors to Firebug
    $firephp->registerErrorHandler($throwErrorExceptions=true);
    firephp->registerExceptionHandler();
    $firephp->registerAssertionHandler(
        $convertAssertionErrorsToExceptions=true,
        $throwAssertionExceptions=false
        );
} else {
    $GLOBALS['firephp']->setEnabled(false);
}

6: Now sprinkle some example code in your own code e.g.:

1
2
3
4
5
6
7
8
9
10
// add the name of the running method to your trace array
array_push($GLOBALS['firephptrace'],__METHOD__);
// add the name of this included file to your trace array
array_push($GLOBALS['firephptrace'],__FILE__);
// log the value of the variable 'language' as 'log'
$GLOBALS['firephp']->log('language: '.$language);
// log the value of an error as 'error'
$GLOBALS['firephp']->error($this->error);
// log the value of an array as 'info'
$GLOBALS['firephp']->info('my_arr: '.implode(",", $my_arr));

7: if you route all code in your index.php; log the trace array add this as the last line in your index.php:

$GLOBALS['firephp']->log($GLOBALS['firephptrace'],'backtrace');

8: run your code and look at the values in FireBug

9: checkout the excellent examples at: http://www.firephp.org/HQ/Learn.htm

10: have fun!

Generate variables from $_POST keys in PHP

Saturday, May 29th, 2010

Sometimes you will receive a lot of post values from a form and you need to assign a variable name for them.

This is a quick way to do this:
e.g. $_POST contains the following keys: “firstname” “lastname” “phone” “email” etc. etc.

1
2
3
foreach ($_POST as $key=>$value){
${$key} = $value;
}

You can now access the following variables:

echo $firstname . ' ' .$lastname. ' ' .$phone. ' '.$email;

Save an image from Flash in PHP

Tuesday, May 4th, 2010

How to save binary data from a flash application in PHP?

For example the flash application will send a .png file in a similar way like this:
Flash code…..

1
2
3
4
5
6
7
8
9
import org.bytearray.encodage.images.PNGEncoder  ;
var dataPngBitmap:BitmapData = new BitmapData ( 320, 240, false, 0x990000 );
var binaryFeedPNG:ByteArray = PNGEncoder.encode ( dataPngBitmap );
var HTTPheader:URLRequestHeader = new URLRequestHeader ("Content-type", "application/byte-stream");
var request:URLRequest = new URLRequest("http:www.mywebsite.com/saveimage.php?name=myimage.png");
request.requestHeaders.push(HTTPheader);
request.data = binaryFeedPNG;
request.method = URLRequestMethod.POST;
navigateToURL(request, "_blank");

To save the file in PHP you need the following code in your saveimage.php file:

1
2
3
4
5
6
7
if (isset ( $GLOBALS ["HTTP_RAW_POST_DATA"] )) {
$file = $GLOBALS ["HTTP_RAW_POST_DATA"];
$filename = $_GET['name'];
$fp = fopen ( $filename, 'wb' );
fwrite ( $fp, $file );
fclose ( $fp );
}

In this example we write the file based on the filename that is provided in the url: “myimage.png”.
Please be very careful with this:

  • You have no way to be sure that this is in fact a png file.
  • You could overwrite an existing file.
  • Someone could try to overwrite an existing php file: e.g. what happens when someone provide this name: “../../index.php”?

If you you need name information from the flash application, do some checks on the filename:

  • Is the extension allowed?
  • Does it contain prefixed dots, slashes etc.?

But it is always safer to provide the the image name yourself and always control the path and file extension of the file you will be writing.