Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
Showing 81-100 of 106 total

Selecting and checking items from HTML menus

This code allows you to pass in an HTML menu (select, radio, or checkbox) along with a single choice or an array of choices to be selected. The choice(s) should be contained literally in the value attribute.

This is handy for making persistent forms without polluting the HTML with PHP logic. For example, you could initialize all your menus to have nothing selected and then pass in GET or POST variables in case the form was not accepted, easily making form selections persistent.

/**
 * For select menus.
 */
function select_from_menu($menu,$choices,$deselect=true) {
  if ($deselect) $menu = preg_replace('/ selected(="selected")?/','',$menu);
  if(!is_array($choices)) {
    $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 selected=\"selected\"",$menu);
  } else foreach($choices as $value) {
    $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 selected=\"selected\"",$menu);
  }
  
  return $menu;
}

/**
 * For radio buttons and checkboxes.
 */
function check_from_menu($menu,$choices,$deselect=true) {
  if ($deselect) $menu = preg_replace('/ checked(="checked")?/','',$menu);
  if(!is_array($choices)) {
    $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 checked=\"checked\"",$menu);
  } else foreach($choices as $value) {
    $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 checked=\"checked\"",$menu);
  }

  return $menu;
}

Implement Error 447

There's a humorous pseudo-RFC which establishes HTTP Error 447 as "dropped in Pacific Ocean". Here's some PHP to implement it, if you'd like. Sends the right header, and even looks like a standard Apache 2 error page.

<?php

header("HTTP/1.1 447 Dropped by Accident in the Pacific Ocean");
print("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Dropped in Ocean!</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rev="made" href="mailto:webmaster@example.com" />
<style type="text/css">
<!--
body { color: #000000; background-color: #FFFFFF; }
a:link { color: #0000CC; }
-->
</style>
</head>

<body>
<h1>Dropped in Ocean!</h1>
<dl>

<dd>


    The requested item was accidentally dropped in
    the Pacific Ocean while being transmitted to your
    computer, and cannot be displayed.

  

</dd></dl><dl><dd>
If you think this is a server error, please contact
the <a href="mailto:webmaster@example.com">webmaster</a>.

</dd></dl>

<h2>Error 447</h2>
<dl>
<dd>
<address>

  <a href="/">example.com</a>
  <br />
  
  <small><?php $date = date("D d M Y h:i:s A T");
print("$date"); ?></small>
  <br />
  <small>Apache/2.0.40 (Red Hat Linux)</small>
</address>
</dd>
</dl>
</body>

</html>

Extensible search highlighting in PHP

Based on Dean's original Google Hilite, but refactored a bit to make it easy to add support for more search engines (currently supports some 20-odd major searches).

<?php

function search_highlight($text)  {
  $referer = $_SERVER['HTTP_REFERER'];

  //Did they get here from a search?
  if((preg_match('/www\.google.*/i',$referer) && !preg_match('/^http:\/\/www\.google\.com\//i', $referer))
     || preg_match('/search\.atomz.*/i',$referer)
     || preg_match('/search\.msn.*/i',$referer)
     || preg_match('/search\.yahoo.*/i',$referer)
     || preg_match('/msxml\.excite\.com/i', $referer)
     || preg_match('/search\.lycos\.com/i', $referer)
     || preg_match('/www\.alltheweb\.com/i', $referer)
     || preg_match('/search\.aol\.com/i', $referer)
     || preg_match('/search\.iwon\.com/i', $referer)
     || preg_match('/ask\.com/i', $referer)
     || preg_match('/search\.cometsystems\.com/i', $referer)
     || preg_match('/www\.hotbot\.com/i', $referer)
     || preg_match('/www\.overture\.com/i', $referer)
     || preg_match('/www\.metacrawler\.com/i', $referer)
     || preg_match('/search\.netscape\.com/i', $referer)
     || preg_match('/www\.looksmart\.com/i', $referer)
     || preg_match('/go\.google\.com/i', $referer)
     || preg_match('/dpxml\.webcrawler\.com/i', $referer)
     || preg_match('/search\.earthlink\.net/i', $referer)
     || preg_match('/search\.viewpoint\.com/i', $referer)
     || preg_match('/www\.mamma\.com/i', $referer)
     || preg_match('/home\.bellsouth\.net\/s\/s\.dll/i', $referer)
     || preg_match('/www\.ask\.co\.uk/i', $referer)) {

    //Figure out which search and get the part of its URL which contains the search terms.
    if(preg_match('/(www\.google.*)|(search\.msn.*)|(www\.alltheweb\.com)|(ask\.com)|(go\.google\.com)|(search\.earthlink\.net)/i',$referer))
      $delimiter = "q";
    elseif(preg_match('/www\.ask\.co\.uk/i', $referer))
      $delimiter = "ask";
    elseif(preg_match('/search\.atomz.*/i',$referer))
      $delimiter = "sp-q";
    elseif(preg_match('/search\.yahoo.*/i',$referer))
      $delimiter = "p";
    elseif(preg_match('/(msxml\.excite\.com)|(www\.metacrawler\.com)|(dpxml\.webcrawler\.com)/i', $referer))
      $delimiter = "qkw";
    elseif(preg_match('/(search\.lycos\.com)|(search\.aol\.com)|(www\.hotbot\.com)|(search\.netscape\.com)|(search\.mamma\.com)/i', $referer))
      $delimiter = "query";
    elseif(preg_match('/search\.iwon\.com/i', $referer))
      $delimiter = "searchfor";
    elseif(preg_match('/search\.cometsystems\.com/i', $referer))
      $delimiter = "qry";
    elseif(preg_match('/www\.overture\.com/i', $referer))
      $delimiter = "Keywords";
    elseif(preg_match('/www\.looksmart\.com/i', $referer))
      $delimiter = "key";
    elseif(preg_match('/search\.viewpoint\.com/i', $referer))
      $delimiter = "k";
    elseif(preg_match('/home\.bellsouth\.net\/s\/s\.dll/i', $referer))
      $delimiter = "string";

    $pattern = "/^.*" . $delimiter . "=([^&]+)&?.*\$/i";
    $query = preg_replace($pattern, '$1', $referer);

    //Remove quotation marks.
    $query = preg_replace('/\'|"/','',$query);

    //List of words to exclude from matching.
    $excludes = array('a', 'an', 'the', 'is', 'in', 'are', 'was', 'and', 'by', 'for', 'from', 'of', 'on', 'with', 'this', 'that', 'shtuff', 'or', ' ', '');
    $query_array = preg_split ("/[\s,\+\.]+/",$query);
    //Iterate over search terms and do the highlighting.
    foreach($query_array as $term) {
      //Don't match the excluded terms.
      $term = strtolower($term);
      if(in_array($term, $excludes)) {
        continue;
      }
      if(preg_match('/(?<=>)([^<]+)?(\b'.$term.'\b)/i', $text)) {
        $matched = "Spoon!";
      } else {
        $mismatched = "Whoops";
      }
      if (!preg_match('/<.+>/',$text)) {
        $text = preg_replace('/(\b'.$term.'\b)/i','<span class="searchterm">$1</span>',$text);  
      } else {
        $text = preg_replace('/(?<=>)([^<]+)?(\b'.$term.'\b)/i','$1<span class="searchterm">$2</span>',$text);
      }
    }
    $query_terms = implode(" ", $query_array);
    $query_terms = htmlspecialchars(urldecode($query_terms));
    //If all terms matched, just tell them you did the highlighting.
    if($matched) {
      //Change this message if you like.
      $message = "<p><strong>It seems you arrived at this page from a search engine.  To help you find "
        . "what you were looking for, your search terms (\"$query_terms\") should "
        . "be highlighted with yellow backgrounds, like <span class=\"searchterm\">this</span>.</strong></p>";
      $text = $message . $text;
    } elseif($mismatched) {
      //If only some or no terms matched, offer to repeat the search locally.
      $query = implode("+", $query_array);                 
      //Also change this message if you like.                     
      $message = "<p><strong>It seems you arrived at this page from a search engine, but that some "
        . "or all of the terms you searched for (\"$query_terms\") aren&#8217;t in this page.  Would you like to "
        . "<a href=\"http://search.atomz.com/search/?sp-q=" //Insert a proper URL for your site's search function here, up to BUT NOT INCLUDING the part where the search terms go.
        . $query //Begin the next line with any parts of the search URL which have to go AFTER the search terms.
        . "&amp;sp-a=sp10028bf7&amp;sp-p=all&amp;sp-f=iso-8859-1"
        . "\">try your search again</a> using this site&#8217;s built-in search?  It might be more accurate.</strong></p>";
      if($matched) {
        $message .= "<p><strong>Any of your search terms which <em>do</em> appear in this page "
          . "should be highlighted with yellow backgrounds, like <span class=\"searchterm\">this</span>.</strong></p>";
      }
      $text = $message . $text;
    }
  }
  return $text;
}
?>

For Ray

In response to his question here, assuming your content is in a string called $content:

$num_paras = substr_count($content, '<p>'); 
switch ($num_paras) {
  case 1:
    $image = 'one.jpg';
    break;
  case 2:
    $image = 'two.jpg';
    break;
  case 3:
    $image = 'three.jpg';
    break;
  default:
    $image = '';
    break;
}

Not processing javascript in smarty templates

Use {literal}...{/literal} tags around the javascript within your smarty template:

{literal}
<script language="text/javascript">
...
</script>
{/literal}

Turn off (mostly) useless apache modules

When I first ported my old Php app to Textdrive, I got all manners of weird errors. Many of these were from weird Apache modules that are enabled by default here.

My solution was to turn off most of these things in my .htaccess file. Here it goes:

# let Apache recognize the ".php" extension
AddType application/x-httpd-php .php
DefaultType application/x-httpd-php

# make php use this very uncool default charset I had been using for years
php_value default_charset iso-8859-1

# make php define old style global variables
php_flag register_long_arrays On

# stop Apache from spewing "Charset: utf-8"
AddDefaultCharset Off

# stop Apache from silently mangling urls
CheckSpelling Off

# stop Apache from denying perfectly legitimate requests
SecFilterEngine Off

Display Current Year

Useful for example for automatic copyright notices:

&copy; Copyright 2004 - <?php echo date("Y") ?>

Date In The Future

<?php
 $nextmonth = mktime(0, 0, 0, date("m")+1, 1, date("Y"));
 echo date("F", $nextmonth);
 ?>

Compile PHP5 with Fast-cgi support for lighttpd

The following is my setup on OS X 10.4.2 using PHP 5.0.5

./configure --prefix=/usr/local/php5-fcgi --enable-fastcgi --enable-force-cgi-redirect --disable-cli --enable-memory-limit --with-layout=GNU --with-regex=php

make

sudo make install


The compile flags enable a fairly basic PHP setup, you may need to add more options for things like MySQL, etc. DO NOT ADD --with-apxs OR --with-apxs2 AS A COMPILE FLAG -- THESE ARE APACHE ONLY AND WILL PROBABLY BREAK UNDER LIGHTTPD!

Add the following to your lighttpd.conf file

fastcgi.server = ( ".php" =>
                   ( "localhost" =>
                     ( "socket" => "/tmp/php5-fcgi.socket",
                       "bin-path" => "/usr/local/php5-fcgi/bin/php"
                     )
                   )
                 )


Restart lighttpd, now with PHP support

extract email addresses

<?php

function extract_emails_from($string){
  preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
  return $matches[0];
}

$text = "blah blah blah [email protected] blah blah blah [email protected]";

$emails = extract_emails_from($text);

print(implode("\n", $emails));

?>


Context: http://forum.textdrive.com/viewtopic.php?pid=46783

Display In 2-Column Table

The below can be applied to MT, EE, etc, and will display the content in a 2 column table. The EE tags below are just an example, it will work equally well if you replace it with MT, Wordpress, etc, tags.

<? $set_table="0"; ?>

<table cellpadding="5" border="0">
{exp:gallery:categories gallery="{gallery_name}"}
<? 
$fs_table = $set_table +1;
if ($set_table == "1") {echo"<tr>";} ?>


Insert other tags here.


<? if ($set_table == "2") {echo"</tr>";  $set_table="0";} ?>
{/exp:gallery:categories}
</table>

Get Today's Date & Time

$today = date("F j, Y");


http://www.php.net/manual/en/function.date.php

Use PHP Inside EE Entries

You'll need the following plugins:
Allow EE Code: http://www.pmachine.com/plugins/allow-eecode/
Allow PHP: http://loweblog.com/archive/2005/06/03/ee-allow-php-plugin/

Set text formatting for the field you want to use this on to "None" (Admin > Weblog Administration > Custom Weblog Fields).

Change your template by adding the Allow EE tags around the field:

{exp:allow_eecode}{body}{/exp:allow_eecode}


Now you can use PHP inside your entries like this:

<p>Bla bla regular entry text</p>

{exp:allowphp}
echo "This will be processed as PHP.";
{/exp:allowphp}

Strip A String using explode

http://www.php.net/manual/en/function.explode.php

In this example, I need to strip the page's current URL to take off anything that follows a ? in that URL.

<? 
$fs_refer= $_SERVER ['REQUEST_URI'];

$fs_refer = explode("?", $fs_refer);
echo "$fs_refer[0] is now a URL without ?.<br />"; 
echo "$fs_refer[1] is the bit that used to follow the ?.";
 ?>

Trim a line of text to X characters

<? $varshort = substr($var,0,25); echo "$varshort"; ?>

Clean Up Form Input

<?
// trim spaces from the beginning and the end of the variable
$field_name = trim($field_name);

// strip all HTML from the variables
$field_name = strip_tags($field_name);

// change the case of the variable to capitalize (It Will Look Like This - handy for Name fields)
$field_name = ucwords(strtolower($field_name));

// change the case of the first character to uppercase, the rest to lowercase (It will look like this)
$field_name = ucfirst(strtolower($field_name));

//change the case of the variable to lowercase
$field_name = strtolower($field_name);

// change the case of the variable to uppercase
$field_name = strtoupper($field_name);
?>

Trim/Remove Spaces

To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:

<?
$text = preg_replace('/\s+/', ' ', $text);
?>


Strip whitespace (or other characters) from the beginning and end of a string

$variable = trim($variable);

Creating Excel files from php

We must use this header.
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=excel.xls");


An then, show the html table

Setting up a php-script to run as a cron-job

To run a php-script as a regular job, you need just point to the php-cli instance with the path to your script:

/usr/local/bin/php /home/username/public_html/scripts/your_script.php


Thanks to Jason for original tip @ http://forum.textdrive.com/viewtopic.php?id=863

Viewing php configuration settings

<?php
phpinfo();
?>
« Newer Snippets
Older Snippets »
Showing 81-100 of 106 total