# A collection of PHP code snippets

This is a collection of php code snippets that seem to come in handy rather often. They are assembled here more for my own organization than anything else.

## String: trim and convert to lowercase

A very straightforward but useful snippet. A string is first trimmed of any leading or trailing white space, and then converted to lowercase letters. Good for normalizing user input.

```<?php
\$string = "Orange";
\$string = strtolower(trim(\$string));
echo \$string;
?>
```

## String: truncate and break at word

This will attempt to shorten a string to `\$length` characters, but will then increase the string (if necessary) to break at the next whole word and then append an ellipses to the end of the string. Good for shortening readable text while keeping it looking pretty.

```<?php
function truncate(\$string, \$length) {
if (strlen(\$string) > \$length) {
\$pos = strpos(\$string, " ", \$length);
return substr(\$string, 0, \$pos) . "...";
}

return \$string;
}

echo truncate('the quick brown fox jumped over the lazy dog', 10);
?>
```

In the above example, the resultant output will be the quick brown…, because the 10th character is the space immediately before the ‘b’ in ‘brown’, which is counted as part of the word ‘brown’.

## What season is it?

Note that this is only a very rough approximation of when a season begins and ends. This snippet would be good for rotating a seasonal background or something, but it’s not astronomically correct, and I wouldn’t use it as a calendar. Reckoning a season is rather complex.

```<?php echo "It is day " . date('z') . " of the year. <br />"; ?>
<?php \$theday = date('z');
if(\$theday >= "79" && \$theday <= "171") {
\$season = "Spring";
} elseif(\$theday >= "172" && \$theday <= "264") {
\$season = "Summer";
} elseif(\$theday >= "265" && \$theday <= "355") {
\$season = "Autumn";
} else {
\$season = "Winter";
}
echo "It's " . \$season . "!";
?>
```

## Get the number of days since something happened

This function takes a date (formatted as a Unix timestamp) and calculates the number of days since that date. The `floor()` function shouldn’t really be necessary, but it’s a hold-over from a less accurate function that used only the hours elapsed. In that function, the results would vary depending on the time of day the function was called. In this method, the times are normalized to 12:00:00 AM.

```function calc_days_ago(\$date){
// The function accepts a date formatted as a Unix timestamp

// First, normalize the current date down to the Unix time at 12:00:00 AM (to the second)
\$now = time() - ( (date('G')*(60*60)) + date('i')*60 + date('s') );
// Second, normalize the given date down to the Unix time at 12:00:00 AM (to the second)
\$then = \$date - ( (date('G', \$date)*(60*60)) + date('i', \$date)*60 + date('s', \$date) );
\$diff = \$now - \$then;
\$days = floor(\$diff/(24*60*60));
switch (\$days) {
case 0:
\$days_ago = "today";
break;
case 1:
\$days_ago = \$days . " day ago";
break;
default:
\$days_ago = \$days . " days ago";
}
return \$days_ago;
}
```

## Get the hours and minutes remaining until something happens

This function takes a time (formatted as a Unix timestamp) and calculates the number of hours and minutes remaining until that time. If the time has already passed, the function returns “historical”. Example outputs would be “7 hours”, “6 hours and 34 minutes”, and “12 minutes”. It could probably be made even more accurate if you changed it to use 3 decimal places and then round to 2 decimal places, but this is good enough for my purposes.

```function calc_time_left(\$date){
// The function accepts a date formatted as a Unix timestamp

\$now = time();
\$event = \$date;
if (\$event >= \$now) {
\$diff = \$event - \$now;
\$unroundedhours = \$diff/(60*60);
// Find the hours, if any, and assemble a string
\$hours = floor(\$unroundedhours);
if (\$hours > "0") {
\$hourtext = (\$hours == "1")? " hour" : " hours";
\$thehours = \$hours . \$hourtext;
}else{
\$thehours = "";
}
// Find the minutes, if any, and assemble a string
if (strpos(\$unroundedhours, '.')) {
\$pos = strpos(\$unroundedhours, '.') + 1;
\$remainder = substr(\$unroundedhours, \$pos, 2);
\$minutes = floor(\$remainder * .6);
\$minutetext = (\$minutes == "1")? " minute" : " minutes";
\$theminutes = \$minutes . \$minutetext;
}elseif (\$minutes == "0") {
\$theminutes = "";
}else{
\$theminutes = "";
}
if (\$thehours && \$theminutes) {
\$sep = " and ";
}
\$timeleft = \$thehours . \$sep . \$theminutes;
}else{
\$timeleft = "historical";
}
return \$timeleft;
}
```

## Get the path of the containing directory

This one really comes in handy. It will give you the URL of the folder where the executing script resides, so you can reference the full path to other files in that folder, no matter where the folder may be located. It works on both Linux and Windows servers, and it adds a trailing slash to the path if one doesn’t already exist, so that root looks the same as a subfolder.

```<?php
function get_path() {
// Get the path of the folder where the executing script resides, with the trailing slash

// Determine HTTPS or HTTP
\$url = (isset(\$_SERVER['HTTPS']) && \$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
\$url .= \$_SERVER['HTTP_HOST'] . dirname(\$_SERVER['PHP_SELF']);
// Convert the trailing backslash (on Windows root) to a forward slash
\$url = str_replace('\\', '/', \$url);
// Determine whether the current location is root by looking for a trailing slash (Windows or Linux)
if (strlen(\$url) != strrpos(\$url, '/') +1) {
\$url .= '/';
}
return \$url;
}
?>
```

### Centering unordered list items

I wrote this script because I wanted to center the thumbnails in the Plogger image gallery while still using an unordered list item to contain each thumbnail. The script figures out how many thumbnails exist on a page and how many will fit in the space provided, then adds sufficient left padding to each to give the appearance of them being centered. It can be easily adapted for other uses. The full explanation and code example is at //ardamis.com/2007/08/05/centering-the-thumbnails-in-plogger/.

### Parse .html as .php (Apache .htaccess)

This isn’t actually a PHP script, but it’s still handy. If you need to write pages with a .html or .htm extension but still want to use PHP in those pages, adding the following line to your .htaccess file will force an Apache server to parse .html files as .php files. I have confirmed this to work with GoDaddy’s hosting (GoDaddy runs PHP as CGI).

```AddHandler x-httpd-php .php .htm .html
```

If you are running an Apache server as part of an XAMPP installation on top of Windows, try using this instead:

```AddType application/x-httpd-php .html .htm
```

## 5 thoughts on “A collection of PHP code snippets”

1. fnfzone

Doesn’t work with my local apache server. i use xamp please tell me whts the reason ?
thanks

2. ardamis Post author

Try using

`AddType application/x-httpd-php .html .htm`

with XAMPP.

3. Swisher

Nice code thanks! You should submit some to programminghelp.com I am sure they would love it.

4. Nick

What a great collection of snippets 😛 I will definatly use a few of them somewhere!

I was reading over your season snippet, and was thinking could it be done like this? (modified for southern hemisphere seasons)

```< ?php \$m = date('m'); if(\$m == "12" || \$m == "01" || \$m == "02" ) { \$season = "Summer"; } elseif(\$m >= "03" && \$m < = "05") { \$season = "Autumn"; } elseif(\$m >= "06" && \$m < = "08") { \$season = "Winter"; } else { \$season = "Spring"; } echo "It's " . \$season . "!"; ?> ```
{"ft_lang_label":"__label__en","ft_lang_prob":0.8107342,"math_prob":0.8461834,"size":7284,"snap":"2020-45-2020-50","text_gpt3_token_len":1908,"char_repetition_ratio":0.10068681,"word_repetition_ratio":0.06752411,"special_character_ratio":0.30724877,"punctuation_ratio":0.15720524,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95345336,"pos_list":[0,1,2,3,4,5,6,7,8],"im_url_duplicate_count":[null,null,null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-11-28T13:40:20Z\",\"WARC-Record-ID\":\"<urn:uuid:d6a1fd1b-7fe1-404d-8576-f3a0cbaff2f4>\",\"Content-Length\":\"77204\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:461b9490-b07d-4402-985f-460526d47154>\",\"WARC-Concurrent-To\":\"<urn:uuid:291ea2e7-31bb-4923-87d0-0cd12c748207>\",\"WARC-IP-Address\":\"143.95.39.87\",\"WARC-Target-URI\":\"https://ardamis.com/2007/12/15/a-collection-of-php-code-snippets/\",\"WARC-Payload-Digest\":\"sha1:62TAAD4GZXTVJP5O5UPQZTDYGNGJNV7U\",\"WARC-Block-Digest\":\"sha1:TKXW2NJQU4YDRWKFCSPMHC7YEYAF5RJ2\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-50/CC-MAIN-2020-50_segments_1606141195656.78_warc_CC-MAIN-20201128125557-20201128155557-00693.warc.gz\"}"}