• Home
  • Blog
  • Lifestream
  • Me
  • Twitter

Recent Posts

  • » Google Car - Damn I'm Observant
  • » Travelling - What's Next?
  • » Posh East Perth Apartment
  • » House in Perth
  • » House Sitting in Adelaide
  • » Sailing The Whitsundays
  • » Agnes Water / 1770
  • » Fraser Island
  • » Coomera Springs and Noosa
  • » Byron Bay

Tags

  • 365  australia  code  experiences  explore  flickr  france  function  holiday  house  javascript  misc  movie  perth  photo  photography  photos  php  random  rant  review  ski  skiing  thailand  traveling  travelling  trekking  video  work 

Search


Links

  • » 365 Gallery
  • » Twitter
  • » Lifestream
  • » My Flickr

Archives

  • » January 2010 (1)
  • » November 2009 (2)
  • » August 2009 (2)
  • » June 2009 (2)
  • » May 2009 (5)
  • » April 2009 (6)
  • » March 2009 (4)
  • » February 2009 (1)
  • » January 2009 (2)
  • » December 2008 (3)
  • » November 2008 (2)
  • » October 2008 (2)
  • » September 2008 (5)
  • » August 2008 (3)
  • » July 2008 (1)
  • » June 2008 (2)
  • » April 2008 (10)
  • » March 2008 (7)
  • » February 2008 (5)
  • » January 2008 (9)
  • » December 2007 (2)

 RSS Feed

Search results for 'function'

PHP Parser - Filtering Cross Site Scripting (XSS)

September 18th, 2008
So the last few days I've been seriously stressing about the implications of XSS (Cross site scripting) in a project that I've been working on. If you don't know what XSS is all about and you're a web developer, you're in trouble, google it.

There's also a great website over at http://ha.ckers.org/xss.html that gives you a huge list of many of the known XSS methods.

There are a plethora of PHP Classes out there that work on forums and such with a limited subset of XHTML but I need to cover as much as possible, and before people start shouting at me, an approach using BBCode or Textile just isn't possible here. (and it's ugly, don't get me started)

Whilst trying to find a decent PHP function to parse out these threats in the simplest manner possible I ended up combining a few to come up with what's below.

Download file (strip_xss.txt)
function strip_xss($str, $allowed=null){
	if (!$allowed){
		$allowed = array('<h1>','<h2>','<h3>','<h4>','<h5>','<h6>','<b>','<i>','<u>','<a>','<ul>','<ol>','<li>','<pre>','<hr>','<blockquote>','<img>','<font>','<span>','','
','<table>','<thead>','<th>','<tr>','<td>','<em>','<strong>','<applet>','<div>','<center>','<pre>','<ins>','<del>','<em>','<kbd>','<dd>','<tbody>','<tfooter>','<big>','<button>','<input>','<option>','<textarea>','<fieldset>','<form>','<legend>','code');
	}
	$disabled = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
	
	// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed // this prevents some character re-spacing such as <java\0script> // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
	$str = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $str);
	
	// straight replacements, the user should never need these since they're normal characters
	// this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
	$search = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()~`";:?+/={}[]-_|\'\\';
	for ($i = 0; $i < strlen($search); $i++) {
		// ;? matches the ;, which is optional // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars // &#x0040 @ search for the hex values
		$str = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $str); // with a ;
		// &#00064 @ 0{0,7} matches '0' zero to seven times
		$str = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $str); // with a ;
	}
	
	return preg_replace('/\s(' . implode('|', $disabled) . ').*?([\s\>])/', '\\2', preg_replace('/<(.*?)>/ie', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" . implode('|', $disabled) . ")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($str, implode('', $allowed))) );
}
Download file (strip_xss.txt)

What I'm yet to come up with is a way of stopping people putting in things such as..
<img src="http://yoursite.com/admin/users/deleteall" />
Then whenever an admin or someone went to this page, alredy logged in to the app, the page would be executed as them, perfectly legally. Obviously there isn't a page that does delete all users, but you can see the problem, right.

Anybody who finds an improvement / bug, please please please add it back here so everyone can benefit, i'll update the code as we go!
No Comments »

PHP Force Download

April 22nd, 2008
So today I needed to force a file to download in a web browser where the browser would normally just output the file. It will also work in IE6 over a secure (HTTPS) connection.. which was a bit like hard work.

function forceDownload($file,$name=false,$contenttype="application/octet-stream",$delete=false){
	if (!$name) $name = $file;
	
	header("Cache-Control: public, must-revalidate");
	header("Pragma: hack");
	header("Content-Type: " . $contenttype);
	header("Content-Length: " .(string)(filesize($file)) );
	header('Content-Disposition: attachment; filename="'.basename($name).'"');
	header("Content-Transfer-Encoding: binary\n");
					  
	$fp = fopen($file, 'rb');
	$buffer = fread($fp, filesize($file));
	fclose ($fp);
	echo $buffer;
	if ($delete){
		unlink($file);
	}
}

Example Usage:
So I wanted to create a temporary file, write some contents to it then force the file to be outputted via the browser and deleted on completion of download.
$data = 'what a load of content';    // data to write to a file

$filename = 'cache/tmpfile.txt';     // the file to write the data too, must be writable
file_put_contents($filename,$data);  // write the data to the file

// force the download and delete the file afterwards
forceDownload($filename,'whateverfilenameyoulike.txt','text/plain',true);

No Comments »

Worlds Best PHP Function

April 15th, 2008
pr($array)
Yes, I know wht you're thinking, how can Scrivna have written the ultimate time saving function? Well to be honest... I haven't... someone else did it and I've ripped it off :-)

Basically, what really annoys me is that when your writing code with big arrays of data and you need to view that data, print_r is your friend, it outputs an array to the page, only problem is it doesn't output it as html, the most common way to remedy this is to either...

A) View the source of the page so it appears formatted correctly
B) Wrap your print_r statement in <pre> tags
C) Do nothing and struggle like hell to read the output
D) Use my fabtabulous function below (trust me, this will save you hours)

And now for the big moment... here it comes.. are you ready for this?

Wait for it, drum roll please....
function pr($arrayness){
	echo '<pre>';
	print_r($arrayness);
	echo '</pre>';
}

Da na!! Yup, isn't it great!

Not only is it shorter than typing print_r all the bloody time, it also formats your output properly.
If you really are crazy you could do some kind of crazy merge with the function over HERE to buffer the output and put it into a variable... but that's for another day.

Thankyou and goodnight.
No Comments »

Youtube Embed Rewriting

April 6th, 2008
So the time may come when you have code for embedding a youtube video into a webpage but need that video to be automagically resized and looping and putting the kettle on for you. Well... here's a snippet of code that just might do that for you!
<?php
// function to adjust a youtube videos settings given the embed code

function youtube_adjust($string,$width=425,$height=355,$autoplay=false,$looping=false){
	// match the url in the embed string

	$pattern = '/name="movie" value[\\s=\'"]+([^"\'>\\s]+)/is';
	preg_match($pattern,$string,$url);
	// split the url to get the different parts
	$result = split('[/&]', $url[0]);
	$id = $result[4];

	// shall i adjust these things?
	$autoplay = $autoplay ? 1 : 0;
	$looping = $looping ? 1 : 0; 

	// insert the new settings into the new format string and return it
	return '<a href="http://www.youtube.com/v/%27.$id.%27&hl=en&autoplay=%27.$autoplay.%27&loop=%27.$looping.%27" style="left: 0px ! important; top: 22px ! important" title="Click here to block this object with Adblock Plus" class="abp-objtab-06839183377036349 visible ontop"></a><a href="http://www.youtube.com/v/%27.$id.%27&hl=en&autoplay=%27.$autoplay.%27&loop=%27.$looping.%27" style="left: 0px ! important; top: 22px ! important" title="Click here to block this object with Adblock Plus" class="abp-objtab-010214352500039581 visible ontop"></a><object height="'.$height.'" width="'.$width.'">
<param name="movie" value="http://www.youtube.com/v/'.$id.'&hl=en&autoplay=1"></param>
<param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'.$id.'&hl=en&autoplay='.$autoplay.'&loop='.$looping.'" type="application/x-shockwave-flash" wmode="transparent" height="'.$height.'" width="'.$width.'"></embed></object>';
}

// this is the string youtube give you
$string = '<a href="http://www.youtube.com/v/iy3T3sp4EW4&hl=en" style="left: 0px ! important; top: 22px ! important" title="Click here to block this object with Adblock Plus" class="abp-objtab-06839183377036349 visible ontop"></a><a href="http://www.youtube.com/v/iy3T3sp4EW4&hl=en" style="left: 0px ! important; top: 22px ! important" title="Click here to block this object with Adblock Plus" class="abp-objtab-010214352500039581 visible ontop"></a><object height="355" width="425">
<param name="movie" value="http://www.youtube.com/v/iy3T3sp4EW4&hl=en"></param>
<param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/iy3T3sp4EW4&hl=en" type="application/x-shockwave-flash" wmode="transparent" height="355" width="425"></embed></object>';

// call and output it yar
echo youtube_adjust($string,200,100,true,true);
?>


P.S Wordpress is gay and likes inserting random character places, sorry if this has screwed up the code above.
No Comments »
.
 
Twitter   |   Contact “everything should be made as simple as possible, but no simpler ” - Albert Einstein