Click a heading to expand or contract | Contract All | Expand All

phpscript - mysql timestamp to RFC822 format

Converts a mysql timestamp to RFC822 format. Useful for xml. The \G\M\T string is used instead of the 'T' php format spec, because some builds of php produce different time zones

?php
/*Convert mysql NOW()timestamp to RFC822 date GMT
  Useful for pubDate or lastBuildDate in RSS	*/ 
$mysqltimestamp = '2005-05-14 22:37:34';
$pubDate = gmdate('D, d M Y H:i:s \G\M\T', strtotime($mysqltimestamp));
echo $pubDate
?> 

javascript - insert text in textarea or input box

This bit of javascript inserts text into a textarea or input box in a form. The html page below includes a form demonstrating it's usage.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Javascript Insert text demo</title>

<script>
var hadFocus = null

function insert(text) 
{
if (hadFocus == null) return false;
hadFocus.value = hadFocus.value + text; 
//return true;
} 
</script>

</head>
<body>

<form>
<p>Click inside an input box, then click the 'bold' link</p>
<a href="javascript:insert('[b]Bold type here[eb]')">bold</a> 
<textarea cols="20" rows="2" name="name1" onfocus="hadFocus = this; return true;">Default text</textarea> 
<input type="text" name="name2" onfocus="hadFocus = this; return true;"> 
<input type="text" name="name3" onfocus="hadFocus = this; return true;"> 
</form>

</body>

javascript - force frames

This forces pages into a frameset. I looked at a lot of these type of scripts, this is one of the easiest as the exact same code can be placed in all your pages. I'm a recent convert to css layouts and now agree they are a better way to go than frames, but frames might be appropriate for some sites. TIP - take advantage of your 'noframescontent' to at least put links to the the individual pages. Most browsers won't see the noframes, but spiders will...

Step 1.This script goes into the head section of your pages,
substitute 'yourwebsite.com' and 'yourframeset.html' with 
your values, make sure to leave the ' ?" +url; ' portion intact. 
The exact same code can be copied and pasted into all the pages you 
want to force into your frameset:

<script language="JavaScript">
if (self == top)
{
var url = self.location;
self.location = "http://www.yourwebsite.com/yourframeset.html?" + url;
}
</script>

Step 2.This script goes into the head section of your frameset page. 
The only word to change here is 'contentFrame' - change it to 
the name of your content frame name (the frame you want the pages to appear in):

<script language="JavaScript">
function frame_saver()
{
if (self.location.search)
{
parent.contentFrame.location = location.search.substring(1,location.search.length);
}
}
window.onload = frame_saver;
</script>

javascript - self contained select onChange handler

I like this one. Change '_top' if you prefer a new window. Many variations on this at http://lab.artlung.com/scripting/dropdown/

<select onchange="window.open(this.options[this.selectedIndex].value,'_top')">
    <option value="">Choose a destination...</option>
    <option value="http://www.yahoo.com/">YAHOO</option>
    <option value="http://www.google.com/">GOOGLE</option>
    <option value="http://www.altavista.com/">ALTAVISTA</option>
    <option value="http://www.amazon.com/">AMAZON</option>
    <option value="http://artlung.com/">ARTLUNG</option>
</select>

applescript - Quark change black boxes to rich black

Printer often prefer areas of 100% black to instead be made up black and a 'support' colour, often 30-40% cyan. This help produce a more uniform black, especially when a black object is printed over dissimilar color areas. This script assumes a colour named 'Rich Black' has been defined and a document is open. Improvements to this this script would be tell you when it's done and how many objects it's converted. It might also apply the Rich Black to text objects over a certain point size...

tell application "QuarkXPress"
   tell document 1
      try
set the color of every text box whose color is "Black" and shade is "100%" to "Rich Black"
set the color of every picture box whose color is "Black" and shade is "100%" to "Rich Black"
      end try
end tell end tell 

applescript - Quark remove white overprints

This is an annoyance that gets most prepress people at some point. (overprinting white effectively makes it invisible)

tell application "QuarkXPress"
tell document 1
   try
      set trap text of every text style range of every story where its color is "White" to knockout
   end try
end tell end tell

phpfunction - sort multidimensional array

I found this on php.net. I built a function to read a directory and store the filenames, lastaccess times, and sizes in an array. Unfortunately, php's readdir seems to sort almost randomly. This function takes the name of the array ($unsorted) and sorts by the column name ($column), returning $sorted. To reverse the sort you can just do a krsort($sorted)

function columnSort($unsorted, $column) {
   $sorted = $unsorted;
   for ($i=0; $i < sizeof($sorted)-1; $i++) {
     for ($j=0; $j<sizeof($sorted)-1-$i; $j++)
       if ($sorted[$j][$column] > $sorted[$j+1][$column]) {
         $tmp = $sorted[$j];
         $sorted[$j] = $sorted[$j+1];
         $sorted[$j+1] = $tmp;
     }
   }
   return $sorted;
}

phpfunction - database connect

Everybody needs a database connection function. This assumes that the values $dbserver - your server name $dbuser - your db user name $dbpassword - your db password $dbname - name of your database have been predfined (usually in a config include file)

function dbconnect() {
	global $dbserver, $dbuser, $dbpassword, $dbname;
	$dbcnx = @mysql_connect($dbserver, $dbuser, $dbpassword);
	if (!$dbcnx) {
	die( '<p>Unable to connect to the database server at this time.</p>' );
	}
	else if (! @mysql_select_db($dbname) ) {
	die( '<p>Unable to locate the comments database at this time.</p>' );
	}
}

phpfunction - formatted, sorted directory listing

I wrote this for a little script that I use to monitor an FTP server. Given an absolute pathname, it produces a table of files and folders (does not go into folders) with file/folder name, date uploaded, and size, sorted by upload date. Requires that the 'sort multidimensional array' function (elsewhere in this code library) be present.

function files_on_server($dir) {
// initialize counter 
$count = 0; 
// to set directory name 
//$dir = "/home/yourftpdirectory/yourftpuserdirectory/"; absolute path with trailing slash

// open directory and parse file list 
if (is_dir($dir)) 
{ 
       if ($dh = opendir($dir)) 
       { 
               // iterate over file list 
               // print filenames
               while (($filename = readdir($dh)) !== false) 
               	{ 
                       if (($filename != ".") && ($filename != "..")) 
                       	{ 
                               $count ++;
							   $fullpath = $dir.$filename;
							   $rawsize = filesize($fullpath);
							   $myfilesize = number_format((filesize($fullpath) / (1024*1024)),0);
							   $atime = fileatime($fullpath);
							   $uploaded = date( "D M  d/y h:ia", $atime);
							   $fileinfo = array("filename" => $filename, "size" => $rawsize, "uploadtime" => $atime, "path" => $fullpath );
							   $sortlist[] = $fileinfo;
							   
	         			}
	         			
           		}
           		}
           		
           		closedir($dh); 
           		//echo "</table>";
}
				$finalsort =  (columnSort($sortlist, 'uploadtime'));
				krsort($finalsort);

					
				echo ('<em>Files on server, most recent uploads first...</em><br /><table width="600" border="0" cellpadding="1" cellspacing="1" bgcolor="#DDDDEE"><tr><td><strong>Filename</strong></td><td><strong>Date Uploaded</strong></td><td><strong>Size</strong></td></tr>'); 

				
				for ($item = count($finalsort)-1; $item > -1; $item-- ) {
				$finalname = $finalsort[$item]['filename'];
				$finaldate = $finalsort[$item]['uploadtime'];
				$finaldate = date( "D M  d/y h:ia", $finaldate);
				$finalsize = $finalsort[$item]['size'];
				
				$finalpath =$finalsort[$item]['path'];
				$finalsize = number_format((filesize($finalpath) / (1024*1024)),2);
				//print $finalname.$finaldate.$finalsize.$finalpath ."<br />";
				

				if (is_dir($finalpath)) {
						echo  ("<tr><td>".$finalname . "</td><td>" . $finaldate . "</td><td><em>FOLDER</em></td></tr>");
						} else {
                        echo  ("<tr><td>".$finalname . "</td><td>" . $finaldate . "</td><td>" .$finalsize ." MB</td></tr>");
		               	}
				 
				}
				echo "</table>";

}
// Usage example

$dir = "/home/ftpdir/keith/";
files_on_server($dir);
// produces this output, but in a nicely formatted table... 
Files on server, most recent uploads first...
Filename	        Date Uploaded	        Size
Stuffinafolder  	Sun Aug 28/05 04:03am	FOLDER
55327-ImposedLR.pdf	Tue Aug 23/05 06:30pm	23.32 MB
Jess pic 003.jpg	Wed May 11/05 07:23pm	1.82 MB
Jess pic.jpg	        Wed May 11/05 07:23pm	0.19 MB
Jess pic 002.jpg	Wed May 11/05 07:23pm	0.60 MB

javascript - clear input field onFocus

Clears input field when clicked

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>

<script>
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
</script>

</head>

<body>

<form>

<input type="text" value="Search this site" onFocus="clearText(this)">
</form>


</body>
</html>

phpfunction - find whole words in string without regex

I was looking for something like a 'bad word filter', but found that most such constructs match patterns, so that words like 'titmouse' might have a portion replaced, even though a valid word - I wanted a match on whole words only. Also, I did't want a replacement function - a submission would be rejected based on the presence of any one of the words defined (the concept is to ward off the casino and pharmaceutical guestbook spammers). Coming up with a regex was challenging me, until this little thing hit me (based on something I found in my searching). It explodes a string into an array, compares every word against a list of 'banned' words, and simply returns 0 if nothing objectionable is found, or 1 if any whole word matches (it's case insensitive). Until I get the hang of regex, this does what I wanted it to. Other measures would be needed for a complete spam solution.

/* this is childishly simple the more I look at it */
function bannedWords(&$text) {
$textArray = explode(" ", $text);
foreach($textArray as $testword) {
$detectWords = array("darn", "frig", "gamble", "poker", "hold-em", "viagra", "phentermine", "pharmacy", "casino");
foreach($detectWords as $wordCheck) {
			if (strtolower($wordCheck) == strtolower($testword)) return 1; //if we find any, return 1, else it's 0
		}
	}
}
/*USAGE
$toBanOrNotToBan = bannedWords($yourStringToCheck);
$toBanOrNotToBan will equal 1 if words found, 0 if 'clean'
add words as desired to the $detectWords array
*/

javascript - InDesignCS2 - Do arithmetic on Selection

Performs simple arithmetic on a number selected in a IDCS2 Document. Edit the calculation for 'myConvertedPrice' as desired. Was written to speed up simple discounts in a price list.

//Do arithmetic on Selection by Bryan H - Feb 08 2006
//Modify the value in line 7 as desired
//UnComment line 11 if you want an alert before committing the change
//Get current price - select a number only
myCurrentPrice = app.activeDocument.selection[0].contents;
//Convert to US Dollars
myConvertedPrice = myCurrentPrice * .84;
//No decimal value needed
myConvertedPrice = Math.round(myConvertedPrice);
//Confirm value
//alert(myConvertedPrice);
//Convert to string
myConvertedPrice = myConvertedPrice + "";
app.activeDocument.selection[0].contents = myConvertedPrice;

javascript - InDesignCS2 - Convert Table Values

Given a table of numbers, this script will apply a percentage change to all values. To select table place an insertion point anywhere. Enter rate change as a decimal value, eg, 1 is no change, .85 would be 85%, 1.15 would be 15% increase

//Do Math on Table - by Bryan H - Feb 08 2006
//Performs a simple rate change on all numbers in a selected table
//To select the table just put an insertion point anywhere in the table
//Works only on table containing only numbers - improvemnts needed
var myDialog = app.dialogs.add({name:"Bryans Value Converter", canCancel: true});
with(myDialog){
	with(dialogColumns.add()){
		var myConversionRateField = realEditboxes.add({editValue:1});
		}
	}
//Display the Dialog
var myResult = myDialog.show();
if(myResult == true){
	//Get the value
	var myConversionRate = myConversionRateField.editValue;
	//Remove Dialog from memory
	myDialog.destroy();
	}
	else {
	//User clicked cancel
	myDialog.destroy();
	}
	
tbl = app.selection[0].parent.parent
for( i = 0; i < tbl.cells.length; i++ ){ 
	myOriginalValue = tbl.cells[i].contents;
	myConvertedValue = myOriginalValue * myConversionRate;
	myRoundedValue = Math.round(myConvertedValue);
	myStringValue = myRoundedValue + "";
	tbl.cells[i].contents = myStringValue;
	}

javascript - page redirect

This is a page redirector. Use it if you want to prohibit from viewing a page directly, for example, a page that is intended to be viewed with in an iframe.

<script language="javascript">
if (self == top)
{
var url = self.location;
self.location = "http://www.osxsux.net/index.php"; //this is the url to redirect to
}
</script>

javascript - strip whitespace

This strips whitespace drom the beginning and end of a string. Javascript 1.2 version included if needed. Found this on my travels, suited a need...

<SCRIPT LANGUAGE="JavaScript"><!--
function stripSpaces() {
    x = document.myForm.myText.value;
    while (x.substring(0,1) == ' ') x = x.substring(1);
    while (x.substring(x.length-1,x.length) == ' ') x = x.substring(0,x.length-1);
    document.myForm.myText.value = x
}
//--></SCRIPT>

<SCRIPT LANGUAGE="JavaScript1.2"><!--
function stripSpaces() {
    var x = document.myForm.myText.value;
    document.myForm.myText.value = (x.replace(/^\W+/,'')).replace(/\W+$/,'');
}
//--></SCRIPT>

<FORM NAME="myForm">
<INPUT TYPE="TEXT" NAME="myText">
<INPUT TYPE="BUTTON" VALUE="Strip White Space" onClick="stripSpaces()">
</FORM>

javascript - give focus to first input field

Add this onLoad to the body tag to five focus to the first input field in your form (or change the value as necessary to put focus on the input element you want)

<body onload="document.getElementsByTagName('input')[0].focus();">

phpfunction - form functions

Some homegrown form functions that are intended to remember the $_POST values of certain elements if the form is rejected after validation, which is especailly tedious when dealing with radio groups and select boxes.

//PHP Function - radioGroup 
//Creates a radio group. Alignment default is centered
//Contained within <tr> tags. Needs a cooresponding header row, do that manually
//$valueList in the form "Yes,No,Male,Female"(will become an array exploded by comma)
//CSS class myRadio can be created for formatting
function radioGroup($label, $name, $valueList){
$values = explode(",", $valueList);
echo('<tr class="myRadio">');
echo('<th scope="row"><div align="center">'.$label.'</div></th>');
foreach($values as $val)
{
echo('<td><div align="center">');
echo('<input name="'.$name.'" type="radio" value="'.$val.'"');
if(isset($_REQUEST[$name]) && $_REQUEST[$name] == $val)
{
echo('checked');
}
echo('>');
echo('</div></td>');
}
echo('</tr>');
}

//PHP Function - txtInput
//Create CSS Class txtInput to format
//Is contained within a <td>
function txtInput($name, $cssClass){
echo('<td><input name="'.$name.'" type="text" class="'.$cssClass.'" ');
if (isset($_REQUEST[$name]))
{
echo('value="'.$_REQUEST[$name].'"></td>');
} else {
echo('></td>');
}
}

//PHP Function - selectBx
//Create CSS class selectBx to format
//Take care to have matching number of values and labels or 'undefined offset' error will ensue 
function selectBx($name, $valueList, $labelList){
$values = explode(",", $valueList);
$labels = explode(",", $labelList);
$y = count($values);
echo('<select name="'.$name.'" class="selectBx">');
for($x = 0; $x < $y; $x++){
echo('<option value="'.$values[$x].'" ');
if(isset($_REQUEST[$name]) && $_REQUEST[$name] == $values[$x]){
echo('selected');
}
echo('>'.$labels[$x].'</option>');
}
echo('</select>');

}

javascript - Restrict keypress in input field

This restricts the keys that that can pressed to input values, as is, it allows numbers only, but could be modified for other values. Use it in your form like this: <input name="whatever" type="text" onKeyPress="return numbersonly(this, event)">

<script language="javascript">
<!-- Begin
function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) ||
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}

// End -->
</script>

javascript - forms - alphanumeric input only

This restricts keypresses in an input to alphanumeric characters only. It uses the onkeypress attribute, which is unsupported by Netcrap 6, and I don't care. I have tested this and found it works in Windows IE6 and Firefox, and Mac Safari and Firefox

<script type="text/javascript">
//Usage - add this attribute to an input field - onkeypress="return alphanumericonly(event)"
function alphanumericonly(e){
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
if ((unicode<48||unicode>57) && (unicode<65||unicode>90) && (unicode<97||unicode>122)) //if not a number
return false //disable key press
}
}
</script>

javascript - forms - autogenerate username

I whipped this up for a recent project, it generates a username based on the input from another field, in my case, it takes a Company name, strips non-alphumerics and spaces, and inserts the result in the username field. For my purposes, the resulting username could be modified, or you could force the value by making the field readonly. Example: <form name="myform"> <input type="text" name="Company" onblur="generateUsername(this.value);"> <input type="text" name="username"> In the line of the script that reads "document.myform.username.value": Replace 'myform' with name of your form, Replace 'username' with the name of the field you want the generated value to appear in. So, a Company name like 'Joe's Print & Ink.' will produce a username of 'joesprintink'

<script language="javascript" type="text/javascript">
//place this script in the <head> of your html
//takes the value from a form field to auto-generate a user name with no spaces, punctuation
//grabs the seed value from the form field onblur eg.
//<input type="text" blahblah onblur="generateUsername(this.value);"
//eg 'Joe's Print & Ink.' beocmes 'joesprintink'
function generateUsername(name)
{
var username = name;
username = username.replace(/[^a-zA-Z0-9]/gi, ""); //remove non alphanumeric characters
username = username.toLowerCase();                 //all to lower case
 
//this is specific to the form it being used in and must be changed appropriatlely
//this is the destination field of the autogenerated username
document.myform.username.value = username;
}
</script>