PHP raw POST data

To read the raw data being posted to a php page (for instance when $_POST is empty due to problems with encoding types or $HTTP_RAW_POST_DATA not being readable due to php.ini settings) reading file_get_contents is a nice solution.

$postData = file_get_contents('php://input');

PHP Send a mail as UTF-8

To send a mail from PHP encoded as UTF-8 is fairly easy to do by modifying the headers.

//Sender with special chars (UTF-8) encoded
mail('mail@example.com', '=?UTF-8?B?'.base64_encode($subjectString).'?=', $messageString, "MIME-Version: 1.0\r\nContent-type: text/plain; charset=UTF-8\r\n");
//Sender not UTF-8 encoded
mail('mail@example.com', 'sender@mail.com', $messageString, "MIME-Version: 1.0\r\nContent-type: text/plain; charset=UTF-8\r\n");

SimpleXml save formated output

When using the SimpleXml->asXML(‘file.xml’) the output is simply written onto one line.
like

<?xml version="1.0" encoding="UTF-8"?>
<product><companyId>1</companyId><productId>1:1</productId></product>

There is nothing wrong with this but if you add line breaks and indentations the xml file looks better and is easier to (manually) read.
Unfortunately there is no way to do this using SimpleXML, but there is a quick and dirty way to do this; and that is to import the SimpleXMLobject to a DOMElement and do it there so some example code

$xmlDom = dom_import_simplexml($simpleXmlObject);
$xmlDom->formatOutput = true;
$xmlDom->save("test.xml");

This would result in an xml file looking like this:

<?xml version="1.0" encoding="UTF-8"?>
<product>
	<companyId>1</companyId>
	<productId>1:1</productId>
</product>

Easier to read but takes some extra space on the disk (might not be much but it is good to remember).

PHP5: Quick on calling a parents constructor

Using OOP there comes a need to call the constructor of a parent class, this is not hard to do

class TestParent {
    public function __construct() {
        var_dump('blah');
    }
}
 
class TestChild extends TestParent {
    public function __construct() {
        parent::__construct();
    }
}
 
$a = new TestChild(); //Output will be: string 'blah' (length=4)

In PHP4 this would have looked like (this still works in PHP5)

class TestParent {
    public function TestParent() {
        var_dump('blah');
    }
}
 
class TestChild extends TestParent {
    public function TestChild() {
        parent::TestParent();
    }
}
$a = new TestChild(); //Output will be: string 'blah' (length=4)

Magento redirect

Sometimes there is a need to do a redirect from inside a Magento page where you might not know if headers are sent or not – Or maybe you wish to make a new redirect function where you don’t have to worry about writing different code if the headers are sent or not.

This is a way to do a redirect where a javascript redirect is used if headers have been sent (and thus it is no longer possible to use a header redirect)

if (!headers_sent()) {
 
	Mage::app()->getResponse()->setRedirect(Mage::getBaseUrl() . 'portal/');
 
}
 
else {
 
	$baseUrl = Mage::getBaseUrl() . 'portal/';
 
	print '<script type="text/javascript">';
 
	print "window.location.href = '{$baseUrl}';";
 
	print '</script>';
 
}

And the function headers_sent() is a php function so that can of course be used outside of Magento in any php scrip where a header location is nice but not always possible.

PHP: Converting a bool value to a string value

The first idea that comes into mind for doing this is to simply make a typecast of the boolean variable to a string and use that (which works)

$testVar = false;
echo (string)$testVar; //will output a empty string (as that evaluates to false)
$testVar = true;
echo (string)$testVar; //will output 1 (as that evaluates to true)

but what if the requirement is that the string should say true or false

$testVar = false;
echo $testVar ? 'true' : 'false'; //will output false
$testVar = true;
echo $testVar ? 'true' : 'false'; //will output true

(While the above example might seam useless I recently had to do this for a db insert)

PHP: Static functions in a Class

Static functions can be used without instantiating the object.

A quick example of a static function is shown below as well as a comparison with a non static function.

A quick example of this (in PHP5):

class TestClass{
	static function staticFunction(){
		echo "static function called";
	}
 
	function nonStaticFunction(){
		echo "nonstatic function was called";
	}
}
 
TestClass::staticFunction(); //will echo static function called
 
$testClass = new TestClass();
$testClass.nonStaticFunction(); //will echo nonstatic function was called
unset($testClass);

PHP: converting a uuid stored as BINARY(16) in mysql to RFC 4122 format

If you are storing uuid’s are BINARY(16) in the database, then the following will turn the stored id to the “original” format.

$uuidReadable = unpack("h*",$uuid);
$uuidReadable = preg_replace("/([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})/", "$1-$2-$3-$4-$5", $uuidReadable);
$uuidReadable = array_merge($uuidReadable);
echo "uuid is " . $uuidReadable[0];

PHP5: Quick on timing a script

Sometimes it is nice to know how long a scrip took to execute (or a part of a script).
This is a simple way to time a script in php.

$time_start = microtime(true);
 
usleep(500);
 
$time_end = microtime(true);
$time = $time_end - $time_start;
 
echo "run time was " . $time . " seconds";