PHP Index
Table of Contents
On this page... (hide)
- 1. Question mark colon control statement gotcha
- 2. Imagemagick examples
- 3. Syntax highlight source code with
.htaccess - 4. Prevent Flash caching
- 5. Apply a function to every entry of an array
- 6. Multidimensional array sorting
- 7. Evaluating a string that contains php functions ... etc
- 8. Reading headers sent
- 9.
exec()versus using backticks for system calls - 10. MP3Search.ru download script
- 11. Extend your
include_pathwith ini_set if you can edit yourphp.ini - 12. non-GUI status dialog for php command line interface scripting
- 13. PHP error handling function
- 13.1 Reference
- 14.
break - 15.
whileanddo...whileloops - 16. End of line character
- 17. Back tick operator for executing shell commands
- 18. Variable variables and how to use illegal variable names
- 19. Looping through a string character by character line by line
- 20. Example regular expression which was useful in creating a wiki engine
- 21. Using
$var++and++$varand the differences - 22. How to print every variable and it's value that is being used in a PHP script
- 23. SimpleXML with XPath
- 24. Place curl request response in variable
- 25. Make a REST request using curl
- 26. Hashing
- 27. Export contacts in Entourage
- 28. Ternary Operators - Handy way of getting a
$_GETvariable or$_POSTor$_COOKIEor anything else you want - 29. Storing cookies in an array
- 30. Find out what modules are compiled into your PHP from the command line interface (cli)
- 31. Message-Id and Date appearing in the body of an email when using the mail() function
- 32. How to make an interactive shell script in PHP
- 33. Figuring out when DST Starts
- 34. Page Comments (Click to edit)
1. Question mark colon control statement gotcha
If you have something like,
<?php $keywords_query = $a_keywords = $fp_search->get_keywords_array(); ? $fp_search->get_keywords_query($a_keywords) : FALSE; ?>
notice that $a_keywords is populated with an array in the if statement portion. Then $a_keywords is supposed to be used in the TRUE portion of the statement, but does not get passed in these Question mark colon control statements.
The following is a good way to do this, besides a normal if else statement.
<?php $a_keywords = $fp_search->get_keywords_array(); $keywords_query = $a_keywords ? $fp_search->get_keywords_query($a_keywords) : FALSE; ?>
2. Imagemagick examples
<?php
### Rotates left 90 degrees
header('content-type: image/jpeg');
$imagick = new Imagick();
$imagick->readImage("images/IMG_5250.JPG");
$imagick->rotateImage(new ImagickPixel(), -90);
print $imagick->getImage();
?>
http://us.php.net/manual/en/function.imagick-rotateimage.php »
3. Syntax highlight source code with .htaccess
If you would like to have your php files parsed as text, and with code highlighting(coloring), add the following to a .htaccess file in the directory containing your php files or above it.
AddType text/plain .php AddType application/x-httpd-php-source .php
4. Prevent Flash caching
Run your file through a php script.
<?php
$file = "video.flv";
set_time_limit(3600);
if (file_exists($file)) {
# header('Content-Description: File Transfer');
# header('Content-Type: application/octet-stream');
# header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
# header('Pragma: public');
header('Content-Length: ' . filesize($file));
# ob_clean();
# flush();
readfile($file);
exit;
}
?>
5. Apply a function to every entry of an array
<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);
?>
Found on http://docs.php.net/array_multisort ». See also http://docs.php.net/array_map ».
6. Multidimensional array sorting
Below is sample code and what is output.
In this sample, we are going to sort the second array with index abu. The basic sort maintains the keys mike, george, sarah but sorts by the phone numbers ascending.
You can throw optional parameters to control sorting with the following: SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING. See http://docs.php.net/array_multisort »
<?php
$a_test = array(
"test"=>array(
"bob"=>"855-0001",
"sue"=>"856-0002",
"joe"=>"852-0023"
),
"abu"=>array(
"mike"=>"319-0021",
"george"=>"392-2393",
"sarah"=>"233-2382",
)
);
print("--original array--\n");
print_r($a_test); print("\n");
print("--new sorted array--\n");
array_multisort($a_test['abu']);
print_r($a_test);
?>
$ php test.php
--original array--
Array
(
[test] => Array
(
[bob] => 855-0001
[sue] => 856-0002
[joe] => 852-0023
)
[abu] => Array
(
[mike] => 319-0021
[george] => 392-2393
[sarah] => 233-2382
)
)
--new sorted array--
Array
(
[test] => Array
(
[bob] => 855-0001
[sue] => 856-0002
[joe] => 852-0023
)
[abu] => Array
(
[sarah] => 233-2382
[mike] => 319-0021
[george] => 392-2393
)
)
7. Evaluating a string that contains php functions ... etc
The could below has a string called $function that contains print('hello world');. PHP can evaluate that string as if you had called print() directly with the eval() function. I believe there's something similar in JavaScript.
<?php
$function = "print('hello world');";
eval($function); # outputs: hello world
?>
8. Reading headers sent
The function apache_request_headers() or its alias getallheaders() spit out the request headers to an array.
<?php $headers_array = apache_request_headers(); ?>
9. exec() versus using backticks for system calls
If you use exec() to store output in a variable, it only returns the last line of output.
<?php
$output = exec("mycommand");
# or
$output = `mycommand`;
?>
The second example returns the entire output of the command and stores it in the $output variable.
10. MP3Search.ru download script
If you've ever used http://www.mp3search.ru », you'll know that you can download a text file that points to each mp3 file for direct download. Here is a script that will download each file you've purchased while making the artist and album directories and then placing the mp3 in it.
#!/usr/bin/php -Cq
<?php
$file = file($_SERVER['argv'][1]) or trigger_error("Can't open file",E_USER_ERROR);
$mp3searchdir = "/home/username/mp3search";
foreach($file as $mp3)
{
$a_mp3 = explode("_-_",preg_replace("/^.*\/(.*)$/","$1",$mp3));
$a_mp3[2] = preg_replace("/_\./","_",$a_mp3[2]);
if(!file_exists("{$mp3searchdir}/{$a_mp3[0]}")){ mkdir("{$mp3searchdir}/{$a_mp3[0]}"); }
if(!file_exists("{$mp3searchdir}/{$a_mp3[0]}/{$a_mp3[1]}")){ mkdir("{$mp3searchdir}/{$a_mp3[0]}/{$a_mp3[1]}"); }
`curl "{$mp3}" > {$mp3searchdir}/{$a_mp3[0]}/{$a_mp3[1]}/{$a_mp3[2]}`;
}
?>
11. Extend your include_path with ini_set if you can edit your php.ini
<?php
ini_set('include_path',ini_get('include_path') . ':/path/to/include/dir');
?>
12. non-GUI status dialog for php command line interface scripting
Just drop this in a folder that contains files of the extension JPG and it will display them all in your shell.
The following is an example if you wanted to resize every JPG you own to a max of 1600 pixels in either width or height - whichever comes first.
<?php
$rand = md5(date("U"));
exec("find . -name '*.JPG' > $rand.txt");
$a_jpgs = file("$rand.txt");
$num_jpgs = count($a_jpgs);
$cnt = 1;
foreach($a_jpgs as $jpg)
{
$jpg = preg_replace("/\n$/","",$jpg);
$percent_completed = floor(($cnt/$num_jpgs)*100);
$files_left = $num_jpgs - $cnt;
system("clear");
print <<<eof
[{$percent_completed}% completed - $cnt of $num_jpgs files - $files_left files left]
/usr/bin/mogrify -resize 1600x1600 -size 1600x1600 "$jpg"\n
eof;
$cnt++;
}
?>
13. PHP error handling function
Here's and example of using the built in error handling function of PHP I quoted from w3schools.com.
In this example an error occurs if the "test" variable is bigger than "1":
<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>
The output of the code above should be something like this:
Notice: Value must be 1 or below in C:\webfolder\test.php on line 6
An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.
Possible error types:
- E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
- E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted
- E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally
You can use the error types as a second argument of trigger_error() as so,
<?php
trigger_error("This is the error message",E_USER_WARNING);
?>
13.1 Reference
14. break
When using break in a loop, you can exit from more than one nested loop buy entering an integer after the break command as in the following example,
<?php
while($x > 0)
{
while($y < 10)
{
break 2;
}
}
In the previous example, break 2; will exit both of the while loops, whereas if I had only entered break;, only the while($y < 10) would be executed and the while($x > 0) would continue to loop.
Note: This also works for the continue statement. You can supply an integer to determine how many nested loops to continue through.
15. while and do...while loops
The main difference between these two loops is that if a while expression never evaluates to true, the code inside will never be executed whereas with a do...while loop, the code will be executed at least once. A while loop evaluates the condition before each loop is entered and a do...while loop executes code after the loop and code are executed.
<?php
$x = 7;
while($x < 5)
{
$x = $x + 1;
echo $x;
}
$x = 7;
do {
$x = $x + 1;
echo $x;
}
while($x < 5);
?>
Above in the first example, the loop will never be entered, and $x will never be printed, but in the second example, at least $x will be printed (7 is the output) and then the do...while loop will be over.
16. End of line character
When printing text, you may use the \n character to indicate a line break, but you can also use the php constant PHP_EOL which is the same thing as a \n.
This is useful because it uses the appropriate end of line character for your operating system.
17. Back tick operator for executing shell commands
Say you want to know what user is executing your scripts or what account you are running under. Here's a quick way to do it.
<?php $username = `whoami`; echo $username;
Just surround your shell commands with a back tick ` and it will store the output in a variable.
The back tick is on the key with the tilde ~ and to the left of the one (1) key.
18. Variable variables and how to use illegal variable names
In PHP, the variable $45 is illegal, but if you use variable variables, you can use it. Here is an example,
<?php
$var_name = "45";
$$var_name = "this value will be stored in the 45 variable";
echo ${'45'};
As you can see, you must use curly bracket syntax to use illegal variables.
19. Looping through a string character by character line by line
Okay, please ignore the relics like wild_colors ... etc. The main point is how to loop through a string, in this case a string that contains line endings \n and displays it's characters one by one.
The reason for the relics, is I was creating a script that would create a <span> with a random color for every non space character in a string. It was just for fun.
Here's the code,
<?php
$str = <<<eof
Hello World from the pretty colors.
eof;
### Use wild_colors($str,TRUE) for black and white grayscale or
### wild_colors($str) for colors.
function wild_colors($str,$black_and_white=FALSE)
{
$str = preg_replace("/\r/","",$str);
$a_str = explode("\n",$str);
$output = "";
foreach($a_str as $line)
{
for($i=0;$i<strlen($line);$i++)
{
if($black_and_white)
{
$rand = rand(0,255);
$random_color = "rgb({$rand},{$rand},{$rand})";
}
else
{
$random_color = "rgb(".rand(0,255).",".rand(0,255).",".rand(0,255).")";
}
$output .= "<span style=\"color:{$random_color}\">".substr($line,$i,1)."</span>";
}
$output .= "<br />\n";
}
unset($a_str);
return $output;
}
print(wild_colors($str,true));
?>
20. Example regular expression which was useful in creating a wiki engine
I have a string that looks like,
<?php $str = "This is a [[Link]] that should [[AnotherLink]] get found."; ?>
I want to run a regular expression on this one line that will find text inside the double brackets and will convert it to a link. The result should look like,
This is a <a href="Link">Link</a> that should <a href="AnotherLink">AnotherLink</a> get found.
First, I'll show you the wrong way,
<?php
$str = "This is a [[Link]] that should [[AnotherLink]] get found.";
$newstr = preg_replace("/\[\[(.*)\]\]/","<a href=\"\\1\">\\1</a>",$str);
echo($newstr);
?>
The above will spit out,
This is a <a href="Link]] that should [[AnotherLink">Link]] that should [[AnotherLink</a> get found.
The correct code is the following,
<?php
$str = "This is a [[Link]] that should [[AnotherLink]] get found.";
$newstr = preg_replace("/\[\[(.*?)\]\]/","<a href=\"\\1\">\\1</a>",$str);
echo($newstr);
?>
Notice that all I added was the question mark on the line that begins with $newstr. This searches for everything inbetween the double brackets, but stops when it finds the first set of ending double brackets (\]\]).
I think this is a non-greedy regular expression - I'm not sure on the terminology there, but that's essentially what it's doing.
The first example without the question mark, found everthing in between the first opening double brackets and the last ending double brackets.
Here's another example that will convert something like,
Go to [[Google Search | http://www.google.com]] to find stuff.
into the following HTML.
Go to <a href="http://www.google.com">Google Search</a> to find stuff.
Here's the code.
<?php
$str = "Go to [[Google Search | http://www.google.com]] to find stuff.";
$newstr = preg_replace("/\[\[ *(.*?) *\| *(.*?) *\]\]/","<a href=\"\\2\">\\1</a>",$str);
echo($newstr);
?>
21. Using $var++ and ++$var and the differences
Here is a couple examples of how they work.
Basically if -- or ++ is before a variable and it's in a conditional test, you will be testing for whatever the variables value is plus one.
If -- or ++ is after the variable and it's in a conditional test, you will be testing for whatever the variables value is at that time. The variable will be incremented by one, but in the test it will be what it's value was before the increment.
<?php
$x = 9;
if(++$x == 10)
{
echo("++x goes ahead and adds 1 to x so it does equal 10");
}
?>
<?php
$x = 9;
if($x++ == 10)
{
echo("x++ waits to actually add 1 to x so it doesn't equal 10
and this message will never be echoed");
}
?>
Using $x++ and ++$x is most useful if you want to increment a variable while testing it in a conditional statement before or after the condition is tested.
22. How to print every variable and it's value that is being used in a PHP script
I usually append the following code to any PHP script. Just put it at the very bottom of your script before the last ?>.
<?php
echo("<pre style='background-color:white;'>");
ob_start();
print_r($GLOBALS);
$GLOBALS_contents = htmlentities(ob_get_contents());
ob_end_clean();
echo($GLOBALS_contents);
echo("</pre>");
?>
23. SimpleXML with XPath
Say you have an xml that looks like the following,
<xml>
<book>
<title>Radical Things</title>
<author>Joe Foo</author>
<isbn>2345235</isbn>
</book>
<book>
<title>The Best Stuff</title>
<author>Foo Bar Jones</author>
<isbn>2342135</isbn>
</book>
<book>
<title>More Than You Know</title>
<author>Joe Foo</author>
<isbn>235236</isbn>
</book>
</xml>
Let's say it's called file.xml.
Normally you would do something like,
$xml = simplexml_load_file("file.xml");
and that would give you an xml object (array) that contains all of your books.
With XPath, we can get that same xml object, but this time let's get only the books by the author Joe Foo.
$xml = simplexml_load_file("file.xml");
$xml_xpath = $xml->xpath('/xml/book[author="Joe Foo"]');
24. Place curl request response in variable
The flag CURLOPT_RETURNTRANSFER when set to 1 causes curl_exec() to return the page content to a variable. Without that flag, the page contents are printed to the browser or stdout.
<?php $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,'http://www.example.com'); curl_setopt($ch,CURLOPT_HEADER,0); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); $xml = curl_exec($ch); curl_close($ch); ?>
25. Make a REST request using curl
<?php $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,'http://username:password@www.example.com/REST/request.xml'); curl_setopt($ch,CURLOPT_HEADER,0); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); $xml = curl_exec($ch); curl_close($ch); ?>
26. Hashing
In php, you can generate md5 or sha1 hashes by using the md5() and sha1() functions respectively.
You can also use the hash() function which I believe is much quicker. This function is available in PHP 5 >= 5.1.2.
Anyway, to get a list of the available hashing algorithms, just execute the following code.
<?php print_r(hash_algos()); ?>
Once you've decided on an algorithm, let's use md5 for this example, execute the following command,
<?php
echo(hash("md5","String to hash"));
?>
You can also use hash_file() to find a hash of a file with similar syntax.
<?php
echo(hash_file("md5","/path/to/file.txt"));
?>
27. Export contacts in Entourage
If you've exported your contacts in Entourage to a tab delimited file, you can use the following script to convert it into a readable form without all the mess.
First thing to do is to change the line endings. Note, I'm using a Mac to do this, but any Linux environment should work fine.
Open up Terminal from Applications > Utilities and run this command. The ^M character can only be entered by holding control and hitting v followed by the letter m. You must not literally type ^M.
Also note, I've exported my contacts to the file your_contacts.txt.
$ perl -p -i.bak -e "s?^M?\n?g" your_contacts.txt
Now put the following code into a file, say convert_phone_contacts.php, in the same directory as your_contacts.txt.
<?php
$a_contacts = file("your_contacts.txt");
$x = 1;
foreach($a_contacts as $contact)
{
$a_contact = explode("\t",$contact);
if($x == 1)
{
$a_headings = $a_contact;
}
for($i=0;$i<=83;$i++)
{
if($a_contact[$i] != "")
{
echo("{$a_headings[$i]}={$a_contact[$i]} | ");
}
}
echo("\n");
unset($a_contact);
$x += 1;
}
?>
Run this php file from the command line with,
$ php convert_phone_contacts.php > new_contacts.txt
This will store the new contacts in new_contacts.txt.
Note, I'm using Entourage from Office 2008. There were 84 different fields. That's why the loop goes from 0 to 83. You may need to change that if yours is different.
28. Ternary Operators - Handy way of getting a $_GET variable or $_POST or $_COOKIE or anything else you want
Say you have a variable $test that will be passed from a form or in a query string and you want to grab it with your php script. Here's a handy one-liner to do that.
<?php $test = isset($_GET['test']) ? $_GET['test'] : ""; ?>
This checks to see if $_GET['test'] has a value, and if it does, $test gets assigned that value. If not, $test gets assigned a blank string. You could also assign FALSE to $test if you want, or anything else for that matter. I just choose a blank string.
The basic format is,
$variable_to_store_value = (some conditional test) ? value_if_true : value_if_false;
Another basic example would be,
<?php $value = (5 > 3) ? "5 is greater than 3 - true" : "this is the false part and won't show up"; echo($value); ### outputs 5 is greater than 3 - true ?>
Note, you can also throw these into strings with concatenation.
<?php $string = "This is a " . (1 < 5) ? "string" : "not true" . " - what do you think?"; ?>
29. Storing cookies in an array
Cookies can be used to store multi-dimensional arrays.
Consider the following code;
<?php
setcookie ("name[first]", "Dennis", time() + (60*60*24));
setcookie ("name[last]", "Pallett", time() + (60*60*24));
?>
You can then display these two cookies using the following code:
<?php echo "First Name: " . $_COOKIE['name']['first']; echo "<br />Last Name: " . $_COOKIE['name']['last']; ?>
The cookie 'name' is an array, and has multiple values. You can even go deeper and have multi-dimensional arrays, e.g. $_COOKIE['name']['test']['something']['value']. You could store whole arrays of data in cookies. But beware that you don't store too much data, there are certain size limits to cookies.
30. Find out what modules are compiled into your PHP from the command line interface (cli)
Just run the following command from a terminal.
$ php -m reports
31. Message-Id and Date appearing in the body of an email when using the mail() function
Normally when I setup my from email address for the headers, I will append \r\n to the end of it. That works on many setups, but my Ubuntu Server 8.04 doesn't like this. So to fix the problem, I have changed from headers from,
$from = "From: me@example.com\r\n";
to
$from = "From: me@example.com";
That extra line ending was throwing things off.
32. How to make an interactive shell script in PHP
Basically, the function fgets with input STDIN will cause the script to pause and wait for the user to enter some text and hit enter.
<?php
echo "Please enter your name: ";
$name = fgets(STDIN);
echo "\nThanks, you entered: {$name}\n";
?>
http://www.sitepoint.com/article/php-command-line-1 »
33. Figuring out when DST Starts
### $reference_date format = m-Y
function get_day($describer,$weekday,$reference_date )
{
$d = explode('-',$reference_date);
switch($describer)
{
case 'first': $offset = get_day_offset($reference_date, $weekday); break;
case 'second': $offset = get_day_offset($reference_date, $weekday) + 7; break;
case 'third': $offset = get_day_offset($reference_date, $weekday) + 14; break;
case 'fourth': $offset = get_day_offset($reference_date, $weekday) + 21; break;
case 'last': $reference_date = ($d[0]+1).'-'.($d[1]); $d = explode('-',$reference_date);
$offset = get_day_offset($reference_date, $weekday) - 7; break;
}
$r = mktime( 0, 0, 0, $d[0], 1+$offset, $d[1] );
return $r; ### returns timestamp format
}
### $anchor format = m-Y
function get_day_offset($anchor,$target)
{
$ts = explode('-',$anchor);
$ts = mktime(0,0,0,$ts[0],'01',$ts[1]);
$anchor = date("w",$ts);
$target = strtolower($target);
$days = array( 'sunday'=>0, 'monday'=>1, 'tuesday'=>2, 'wednesday'=>3, 'thursday'=>4, 'friday'=>5, 'saturday'=>6 );
$offset = $days[$target] - $anchor;
if($offset<0) $offset+=7;
return $offset; ### returns 0-6 for use in get_day();
}
###
# Use the functions get_day() and get_day_offset() to find when dst begins and ends
# Note: This does not account for the fact the DST begins at 2am. This assumes midnight.
###
$dst_begins = get_day("second", "sunday", "03-".date("Y"));
$dst_ends = get_day("first", "sunday", "11-".date("Y"));
### Convert the date to UNIX time
$pubDate_unix = date("U",strtotime("now")); ### This is GMT time
### See if the pubDate is in-between the DST beginning and ending times
if($pubDate_unix >= $dst_begins && $pubDate_unix < $dst_ends)
{
### 4*60*60 adds 4 hours to the unix time in seconds (converts GMT to EST-DST)
$pubDate_unix = $pubDate_unix - (4 * 60 * 60);
}
else
{
### 5*60*60 adds 5 hours to the unix time in seconds (converts GMT to EST)
$pubDate_unix = $pubDate_unix - (5 * 60 * 60);
}
Borrowed from http:docs.php.net/strtotime » jay at jaymunda dot com.
