Thursday, May 6, 2010

Six Cool PHP Tricks You May Not Know

Over the years I've come across some useful tricks in PHP that are not obvious, but are worth mentioning. This is not meant to be a comprehensive list of all the useful tricks that you can do with PHP.

1. Count Characters in a String

To do this, I've usually just used the function strlen(). However, there is a faster method. Take a look at the following code example:
<?php
$string = 'testing';

if(isset($string[6]))
	echo "The string '$string' is at least 7 characters long.";
else
	echo "The string '$string' is less than 7 characters long.";
You treat the $string value like an array by passing an integer value to isset(). If that number plus one is greater than or equal to the number of characters in the string, it will return true. You need to add one because it is zero based.
2. Use PHP Echo like a Function
I've always thought that if you wanted to concatenate strings with echo, you needed to use periods. But you can actually treat echo like a function and use commas instead (it is also faster). Take a look at the following code:
<?php
$string1 = 'test-string1';
$string2 = 'test-string2';
$string3 = 'test-string3';

echo 'String #1: ', $string1, '<br />';
echo 'String #2: ', $string2, '<br />';
echo 'String #3: ', $string3, '<br />';

3. Use Single Quotes When Possible

By using single quotes instead of double quotes, you save PHP from having to parse your string for variables. It not only is faster, but I find it more programmer-friendly because it is easier to find variables in your code.
Also, when referencing an array that has a string index, always use single quotes. This prevents PHP from having to figure out exactly what you were trying to say.

4. PHP Variable Variables

There have been several cases when I needed to access a dynamic variable (where the variable name changed). You can do this easily in PHP by using what is called Variable Variables. Take a look at this example:
<?php
$var1 = 'nameOfVariable';
$nameOfVariable = 'This is the value I want!!!';

echo $$var1;

5. Use Arrays in Form Fields

Not only can you create a form field that creates an element in an array (like name['firstname'] ), but you can create dynamic arrays as well. This is especially useful in checkboxes, where the user could check multiple options. Take a look at this HTML:
<label><input type="checkbox" name="hobbies[]" value="Sports" /> Sports</label><br />
<label><input type="checkbox" name="hobbies[]" value="Hiking" /> Hiking</label><br />
<label><input type="checkbox" name="hobbies[]" value="Swimming" /> Swimming</label><br />
<label><input type="checkbox" name="hobbies[]" value="Swimming" /> Watching Movies</label><br />
When the above fields are posted to a PHP page, each hobby is added to the hobbies array. You can then loop through that array and access each value that was checked.

6. PHP Output Buffering

I have come across cases where something was being output to the screen that I didn't want (at least at that point, or maybe not at all).
A common example of this is if you have a function or a script that echoes out a string, but you are using the code in that instance where you don't want it to print to the screen at that point (when using a template system or framework system, for example). In this case you would still want to be able to reuse the code, but just prevent anything from being printed out at that exact point.
This will make more sense if you look at this simple example:
<?php
ob_start();

echo 'Print to the screen!!!';
$getContent = ob_get_contents();

ob_end_clean();

// Do whatever you want...

// Do something with the printed content (only if you want)...
echo 'Now: ' . $getContent;
You probably were familiar with at least some of these, but I hope that someone will find this list useful in some capacity. :)

Wednesday, March 31, 2010

Rename files with shell script

Rename a large list of files with names containing spaces and different characters

All the job is done using the tr command.


The following script i found on a Archlinux Forum Post changes spaces to underscores, remove characters like {}(),\! and convert the filenames to lowercase.

#!/bin/bash
ls | while read -r FILE
do
mv -v "$FILE" `echo $FILE | tr ' ' '_' | tr -d '[{}(),\!]' | tr -d "\'" | tr '[A-Z]' '[a-z]' | sed 's/_-_/_/g'`
done

The following script just changes spaces to underscores.

#!/bin/bash
ls | while read -r FILE
do
mv -v "$FILE" `echo $FILE | tr ' ' '_' `
done



Great everyday scripts. Thanks paramthegreat (Article post)

Thursday, October 22, 2009

OCI8

You need the following (once logged in) from Oracle Instant Client:

  • oracle-instantclient-basic
  • oracle-instantclient-devel

You also need to install two PHP related packages, namely:

  • php-pear
  • php-devel

You might need to update the channel data of pear and pecl by:

  • pear channel-update pear.php.net
  • pecl channel-update pecl.php.net

Now you should be able to install oci8 with the following command:

  • sudo pecl install oci8

Finally edit /etc/php.ini and add the line bellow in the extensions section:

  • extension=oci8.so

See also the php-oracle manual

Example

       # Here's how we connect:
$dbh = oci_connect ('USERNAME', 'PASSWD', '//172.31.5.337:1521/ORACL');
# Here's how we pass an sql statement:
$stmt = oci_parse ($dbh, 'SELECT USERNAME, PASSWORD FROM TABLE');
# Here we execute the statement:
oci_execute ($stmt);
$cnt = 1;
# Then we fetch rows in a loop until we're done
while ($result = oci_fetch_array($stmt)) {
echo "user: " . $cnt . " " . $result['USERNAME'] .
" " . $result['PASSWORD'] . "
";
$cnt = $cnt +1;
}
# last we close the database handle
oci_close($dbh);
# and note to the parser that this is the end of the php code section

Sunday, October 18, 2009

Friday, October 16, 2009

Gmail Tips

Wednesday, September 9, 2009

Friday, July 10, 2009

How to enable gzip compression with Php.



Enabling Gzip Compression


In many forums and on many webpages it has been widely proclaimed that to enable gzip compression using php is as easy as adding a single line of code at the beginning of each page. This is not false, however it is not the best way of doing it. Before continuing, here's the code. It takes advantage of Php's buffered output and buffers all output of the script until the Php engine has completed, and then runs all the output through a special function that gzip compresses it before sending it on to the browser.

Here is the code. Just place this at the very top of all your Php pages and it will send gzip-compressed output to the browsers.








Example Code


<?php
ob_start
("ob_gzhandler");
?>

This method is dependant on the Apache server and in addition, the mod_gzip module must be installed and loaded.

Other Methods to Enable Gzip Compression


The method mentioned above is quick and easy, but the downfalls are that it only works on Apache with mod_gzip. Not only that, but according to the Php manual, that is not the preferred method for gzipping.
(From the Php manual at www.php.net)
note that using zlib.output_compression is preferred over ob_gzhandler().

Another method of gzipping is as follows:








Example Code


<?php


// Include this function on your pages
function print_gzipped_page() {


global $HTTP_ACCEPT_ENCODING;
if(
headers_sent() ){
$encoding = false;
}elseif(
strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false ){
$encoding = 'x-gzip';
}elseif(
strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false ){
$encoding = 'gzip';
}else{
$encoding = false;
}


if( $encoding ){
$contents = ob_get_contents();
ob_end_clean();
header('Content-Encoding: '.$encoding);
print(
"\x1f\x8b\x08\x00\x00\x00\x00\x00");
$size = strlen($contents);
$contents = gzcompress($contents, 9);
$contents = substr($contents, 0, $size);
print(
$contents);
exit();
}else{
ob_end_flush();
exit();
}
}


// At the beginning of each page call these two functions
ob_start();
ob_implicit_flush(0);


// Then do everything you want to do on the page
echo 'Hello World';


// Call this function to output everything as gzipped content.
print_gzipped_page();


?>