PHP and javascript snippets you can copy and paste.

Friday, June 8, 2007

js_move_elementToYPos(element, yPoint)

/**
* Move element to vertical point.
*
* @param object element
* @param int yPoint
*/
function js_move_elementToYPos(element, yPoint){
element.style.position = 'absolute';
element.style.top = yPoint;
}

js_move_elementToXPos(element, xPoint)

/**
* Move element to horizontal point.
*
* @param object element
* @param int xPoint
*/
function js_move_elementToXPos(element, xPoint){
element.style.position = 'absolute';
element.style.left = xPoint;
}

Thursday, June 7, 2007

js_move_elementHorizontal(element, shiftHoriz)

/**
* Move element horizontally.
*
* @param object element
* @param int shiftHorizontal
*/
function js_move_elementHorizontal(element, shiftHoriz){
element.style.position = 'relative';
element.style.left = shiftHoriz;
}

js_move_elementVertical(element, shiftVertical)

/**
* Move element vertically.
*
* @param object element
* @param int shiftVertical
*/
function js_move_elementVertical(element, shiftVertical){
element.style.position = 'relative';
element.style.top = shiftVertical;
}

js_get_rand(max)

/**
* Gets a random number
*
* @param int max
* @return int
*/
function js_get_rand(max){
return Math.random()*max;
}

js_get_isEven(n)

/**
* Gets whether a number is even
*
* @param int n
* @return int
*/
function js_get_is_even(n){
return n % 2 == 0?true:false;
}

js_is_odd(n)

/**
* Gets whether a number is odd.
*
* @param int n
* @return int
*/
function is_odd(n){
return n % 2 == 0?false:true;
}

js_get_screenCenterY()

/**
* Gets the middle vertical point of the page
*/
function js_get_screenCenterY(){
return ( window.outerHeight - getScrollTop())/2;
}

js_get_screenCenterX()

/**
* Gets the middle horizontal point of the page.
*/
function js_get_screenCenterX(){
return (window.outerWidth - js_get_scrollLeft())/2;
}

js_get_elementTop()

/**
* Gets the vertical position of an element.
*
* Credit: http://www.aspandjavascript.co.uk/javascript/javascript_api/get_element_top_left.asp
*/
function js_get_elementTop(elem) {

yPos = elem.offsetTop;
tempEl = elem.offsetParent;
while (tempEl != null) {
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return yPos;
}

js_get_elementLeft()

/**
* Gets the horizontal position of an element.
*
* Credit: http://www.aspandjavascript.co.uk/javascript/javascript_api/get_element_top_left.asp
*/
function js_get_elementLeft(elem) {

xPos = elem.offsetLeft;
tempEl = elem.offsetParent;
while (tempEl != null) {
xPos += tempEl.offsetLeft;
tempEl = tempEl.offsetParent;
}
return xPos;

}

js_get_elementHeight()

/**
* Gets the height of an element.
*
* Credit: http://www.aspandjavascript.co.uk/javascript/javascript_api/get_element_width_height.asp
*/
function js_get_elementHeight(elem) {

if (elem.style.pixelHeight) {
xPos = elem.style.pixelHeight;
}
else {
xPos = elem.offsetHeight;
}
return xPos;

}

js_get_elementWidth

/**
* Get the width of an element
*
* Credit: http://www.aspandjavascript.co.uk/javascript/javascript_api/get_element_width_height.asp
*/
function js_get_elementWidth(elem) {

if (elem.style.pixelWidth) {
xPos = elem.style.pixelWidth;
}
else {
xPos = elem.offsetWidth;
}

return xPos;

}

js_get_pageWidth()

/**
* Gets the width of a page
*
* Credit: http://www.quirksmode.org/viewport/compatibility.html
*/
function js_get_pageWidth(){

var x;
var test1 = document.body.scrollHeight;
var test2 = document.body.offsetHeight
if (test1 > test2) // all but Explorer Mac
{
x = document.body.scrollWidth;
}
else // Explorer Mac;
//would also work in Explorer 6 Strict, Mozilla and Safari
{
x = document.body.offsetWidth;
}

return x;

}

js_get_pageHeight()

/**
* Gets the page height.
*
* Credit: http://www.quirksmode.org/viewport/compatibility.html
*/
function js_get_pageHeight(){

var y;
var test1 = document.body.scrollHeight;
var test2 = document.body.offsetHeight
if (test1 > test2) // all but Explorer Mac
{
y = document.body.scrollHeight;
}
else // Explorer Mac;
//would also work in Explorer 6 Strict, Mozilla and Safari
{
y = document.body.offsetHeight;
}

return y;

}

js_get_scrollTop()

/**
* Gets the amount the page has been scrolled down.
*
* Credit: http://www.quirksmode.org/viewport/compatibility.html
*/
function js_get_scrollTop(){

if (self.pageYOffset) // all except Explorer
{
y = self.pageYOffset;
}
else if (document.documentElement && document.documentElement.scrollTop)
// Explorer 6 Strict
{
y = document.documentElement.scrollTop;
}
else if (document.body) // all other Explorers
{
y = document.body.scrollTop;
}

return y;

}

js_get_scrollLeft()

/**
* Gets how much the page has been scrolled left.
*
* Credit: http://www.quirksmode.org/viewport/compatibility.html
*
*/
function js_get_scrollLeft(){

if (self.pageYOffset) // all except Explorer
{
x = self.pageXOffset;
}
else if (document.documentElement && document.documentElement.scrollTop)
// Explorer 6 Strict
{
x = document.documentElement.scrollLeft;
}
else if (document.body) // all other Explorers
{
x = document.body.scrollLeft;
}

return x;

}

js_get_browserInnerHeight

/**
* Gets the inner height of the browser page.
*
* Credit: http://www.quirksmode.org/viewport/compatibility.html
*/
function js_get_browserInnerHeight(){

if (self.innerHeight) // all except Explorer
{
x = self.innerWidth;
}
else if (document.documentElement && document.documentElement.clientHeight)
// Explorer 6 Strict Mode
{
x = document.documentElement.clientWidth;
}
else if (document.body) // other Explorers
{
x = document.body.clientWidth;
}

return x;

}

js_get_browserInnerWidth

/**
* Gets the inner width of the browser page.
*
* Credit: http://www.quirksmode.org/viewport/compatibility.html
*
function js_get_browserInnerWidth(){

if (self.innerHeight) // all except Explorer
{
y = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
// Explorer 6 Strict Mode
{
y = document.documentElement.clientHeight;
}
else if (document.body) // other Explorers
{
y = document.body.clientHeight;
}

return y;

}

js_get_pageInnerWidth

function js_get_pageInnerWidth(){

// http://www.quirksmode.org/viewport/compatibility.html

if (self.innerHeight) // all except Explorer
{
y = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
// Explorer 6 Strict Mode
{
y = document.documentElement.clientHeight;
}
else if (document.body) // other Explorers
{
y = document.body.clientHeight;
}

return y;

}

Tuesday, May 15, 2007

bookmarklet

/**
* For an excellent article on what bookmarklets are and how to use them see:
* hunlock.com - Bookmarklets
*
* Usage example:
<html>
<head>
</head>
<body>
<body>
Simply drag the link below to your bookmarklet toolbar. If you're using IE7 you will need to right click on the link and select add to favorites then save it in their "links" folder.
<br/>>br/>

<!-- Replace 'http://www.example.com/script.js' with the path to your script -->
<A HREF='javascript:(function(){var%20s=document.createElement(%22script%22);s.charset=%22UTF-8%22;s.src=%22http://ma.gnolia.com/meta/magf\
rame%22;document.body.appendChild(s)})();'>Bookmarklet</A>

</html>

*/
function(){var%20s=document.createElement(%22script%22);s.charset=%22UTF-8%22;s.src=%22http://ma.gnolia.com/meta/magf\
rame%22;document.body.appendChild(s)})();

js_set_opacity(el, value)

/**
* Sets an element's opacity.
* @param obj el.
* @param int val - value from 0 to 10.
* Credit: quirksmode.org
*/
function js_set_opacity(el,value){
el.style.opacity = value/10;
el.style.filter = 'alpha(opacity=' + value*10 + ')'; // IE.
}

Tuesday, April 17, 2007

js_map_keyPress(actualKeyPress,keyPressToMatch,callback)

/**
* Maps a key press to a function.
*
* @param int actualKeyPress.
* @param int keyPressToMatch.
* @param object callback.
*/
function js_map_keyPress(actualKeyPress,keyPressToMatch,callback){
if(actualKeyPress==keyPressToMatch){
callback();
}
}

js_get_keyCode(e)

/**
* Returns the key code of a key press.
*
* @param object e.
* @return key code.
*/

function js_get_keyCode(e){

if(e.event){ // IE
keyCode = e.keyCode;
}
else if(e.which){
keyCode = e.which;
}
return keyCode;

}

Sunday, April 15, 2007

js_create_socialBookmarks(container,path_to_icons)

/**
* Creates links to social bookmarking sites.
*
* @param object container - div, span etc element to hold links.
* @param string path_to_icons - path to where the social bookmarking sites icons are.
*/

function js_create_socialBookmarks(container,path_to_icons){

var page = window.location;
var title = window.document.title;

links = new Array();

if(!path_to_icons || path_to_icons=='undefined'){
path_to_icons = './';
}

// Digg.
link = document.createElement('A');
link.href = "http://digg.com/submit?phase=2&url=" + escape(page) + "&title=" + escape(title);
link.setAttribute('title','Digg');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'digg.png');
img.setAttribute('border','0');

img.setAttribute('alt','digg');
link.appendChild(img);
links[links.length] = link;

// Delicious.
link = document.createElement('A');
link.href = "http://del.icio.us/post?url=" + escape(page) + "&title=" + escape(title);
link.setAttribute('title','del.icio.us');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'delicious.png');
img.setAttribute('border','0');
img.setAttribute('alt','del.icio.us');
link.appendChild(img);
links[links.length] = link;

// Stumbleupon.
link = document.createElement('A');
link.href = "http://www.stumbleupon.com/url/" + escape(page);

link.setAttribute('title','StumbleUpon');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'stumbleupon.png');
img.setAttribute('border','0');
img.setAttribute('alt','StumbleUpon');
link.appendChild(img);
links[links.length] = link;

// Reddit.
link = document.createElement('A');
link.href = "http://reddit.com/submit?url=" + escape(page) + "&title=" + escape(title);
link.setAttribute('title','Reddit');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'reddit.png');
img.setAttribute('border','0');
img.setAttribute('alt','Reddit');
link.appendChild(img);

links[links.length] = link;

// Technorati
link = document.createElement('A');
link.href = "http://technorati.com/faves?add=" + escape(page);
link.setAttribute('title','Technorati');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'technorati.png');
img.setAttribute('border','0');
img.setAttribute('alt','Technorati');
link.appendChild(img);
links[links.length] = link;

// Furl.
link = document.createElement('A');
link.href = "http://www.furl.net/storeIt.jsp?u=" + escape(page) + "&t=" + escape(title);
link.setAttribute('title','Furl');
img = document.createElement('IMG');

img.setAttribute('src', path_to_icons + 'furl.png');
img.setAttribute('border','0');
img.setAttribute('alt','Furl');
link.appendChild(img);
links[links.length] = link;

// Slashdot.
link = document.createElement('A');
link.href = "http://slashdot.org/bookmark.pl?title=" + escape(title) + "&url=" + escape(page);
link.setAttribute('title','Slashdot');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'slashdot.png');
img.setAttribute('border','0');
img.setAttribute('alt','Slashdot');
link.appendChild(img);

links[links.length] = link;

// Blinklist.
link = document.createElement('A');
link.href = "http://www.blinklist.com/index.php?Action=Blink/addblink.php&Url=" + escape(page) + "&Title=" + escape(page);
link.setAttribute('title','BlinkList');
img = document.createElement('IMG');
img.setAttribute('src', path_to_icons + 'blinklist.png');
img.setAttribute('border','0');
img.setAttribute('alt','BlinkList');
link.appendChild(img);
links[links.length] = link;

var max = links.length-1;

for(i=0;i<max;i++){

container.appendChild(links[i]);
}

}

Saturday, April 14, 2007

js_ajax.js

// Credit: http://www-128.ibm.com/developerworks/xml/library/x-ajaxxml3/index.html?ca=dnw-812
function ajx_process_reqChange() {

if (req.readyState == 4){
if(req.status!=200){
if(typeof(onfailure)=='function'){
onfailure();
}
}
else{
if(typeof(onsuccess)=='function'){
onsuccess();
}
}
}

}

function js_ajax_load_url( url, successCallback, failureCallback){

if(window.XMLHttpRequest) {
try {

req = new XMLHttpRequest();
}
catch(e) {
req = false;
}
}
else if(window.ActiveXObject) {
try {
req = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e) {
try {
req = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e) {
req = false;
}

}
}
if(req) {
onfailure = failureCallback;
onsuccess = successCallback;
req.onreadystatechange = ajx_process_reqChange;
req.open('GET', url, true);
req.send('');
}

}

var req = null;
var onfailure = null;
var onsuccess = null
req = null;

//-------------------------------------------------------------------------
// Example:

[html]
[head]
[script language="Javascript" src="js_ajax.js"][/script]

[script language="Javascript"]

function onsuccessCallback(){
alert(req.responseText);
}

function onfailureCallback(){
alert('failed');
}

window.onload = registerEvents;

function registerEvents(e){
js_ajax_load_url('test.php', onsuccessCallback, onfailureCallback)
}

[/script]
[/head]
[body]
[/body]
[/html]

Friday, April 13, 2007

net_upload_photosToFlickr($yourFlickrEmailAddress,$pathsToPhotos)

/**
* Uploads photos to Flickr.
*
* @param string $yourFlickrEmailAddress - email address used to upload photos to Flickr. Ref: http://flickr.com/account/uploadbyemail/
* @param array $pathsToPhotos - array of paths to photos eg array('/mypath/photo1.jpg',/mypath/photo2.jpg' ...)
* @return bool.
*/


// http://phpmailer.sourceforge.net/
require_once('phpmailer/class.phpmailer.php');

function net_upload_photosToFlickr($yourFlickrEmailAddress,$pathsToPhotos){

$mailer = new PHPMailer();
$mailer->AddAddress($yourFlickrEmailAddress);
if(!empty($pathsToPhotos)){
while(list($key,$pathToPhoto)=each($pathsToPhotos)){
$mailer->AddAttachment($pathToPhoto);
}
}

return ($mailer->send()){


}

Thursday, April 12, 2007

js_is_image(ext)

/**
* Returns true if ext is an image extension.
*
* @param string ext.
* return bool
*/
function js_is_image(ext){

var imgExtsArr = new Array();
imgExtsArr.png = true;
imgExtsArr.jpg = true;
imgExtsArr.gif = true;
imgExtsArr.jpeg = true;

return imgExtsArr[ext];

}

js_php_parse_url(url)

/**
* Javascript equivalent of PHP 'parse_url' function.
*/
function js_php_parse_url(url){

url = new String(url);

ret = new Array();

// Domain name and scheme
var regexp = new RegExp("([a-z0-9]+)\:\/\/([\.a-z0-9\-\_]+)", "i");
result = regexp.exec(url);
if(result){
ret.scheme = result[1];
ret.domain = result[2];
}

// Path
regexp.compile("[a-z]+\:\/\/[\.a-z0-9]+\/([a-z0-9\/\.\-\_]+)\/", "i");
result = regexp.exec(url);
if(result){
ret.path = result[1] + '/';
}

// file name

regexp.compile("[a-z]+\:\/\/[\.a-z0-9]+\/([a-z0-9\/\.\-\_]+)", "i");
result = regexp.exec(url);
if(result){
ret.filename = result[1];
}
else{
ret.filename = url;
}

// Ext.
temp = ret.filename.split('.');
ret.ext = temp[1];


// Port

regexp.compile("[a-z]+\:\/\/[\.a-z]+\:([0-9]+)", "i");
result = regexp.exec(url);
if(result){
ret.port = result[1];

}

// Query
temp = url.split('?');
if(temp[1]){
ret.query = temp[1];
}

return ret;

}

Wednesday, April 4, 2007

file_do_download($fileName)

/**
* Downloads a file.
*
* @param fileName.
*/

function file_do_download($fileName, $mimeType){

header("Content-type: $mimeType");
$baseName = basename($fileName);
header("Content-disposition: attachment; filename=$baseName");
echo $data;
die(); // required

}

xml_replace_nodeContent( &$node, &$new_content )

/**
* Replaces node contents.
*
* Needed as a workaround for bug/feature of set_content.
* This version puts the content
* as the first child of the new node.
* If you need it somewhere else, simply
* move $newnode->set_content() where
* you want it.
* Credit: http://www.php.net/manual/en/function.domnode-set-content.php
*/

function xml_replace_nodeContent( &$node, &$new_content )
{

$dom =& $node->owner_document();

$newnode =& $dom->create_element( $node->tagname );

$newnode->set_content( $new_content );

$atts =& $node->attributes();
foreach ( $atts as $att )
{
$newnode->set_attribute( $att->name, $att->value );
}


$kids =& $node->child_nodes();
foreach ( $kids as $kid )
{
if ( $kid->node_type() != XML_TEXT_NODE )
{
$newnode->append_child( $kid );
}
}

return $newnode;

}

arr_add_elementToStart($a,$el)

/**
* Adds an element to the start of an array.
* @param array $a
* @param mixed $el
*/

function arr_add_elementToStart($a,$el){
$aRev = array_reverse($a);
array_push($aRev, $el);
return array_reverse($aRev);
}

fnc_call($funcName)

/**
* Enables a function to be passed as a parameter
*
* @param string $funcName.
* @param string $fn.
* $param array $params - params to pass to $fn.
* @return array - return values of each call to $fn.
*/
function fnc_call($funcName){

$args = func_get_args();
array_shift($args);
$classNameMethod = explode('::',$funcName);
if(isset($classNameMethod[1])){
$funcName = $classNameMethod;
}
return call_user_func_array($funcName,$args);

}

// Example
/*

require_once('fnc_call.php');

function add($a,$b){
return $a + $b;
}

function test($addFn, $a, $b){
print_r(fnc_call('add',$a ,$b));
}

test('add', '4', '5');

?>
*/

Tuesday, April 3, 2007

sec_quote_SQLStr($sql)

/**
* Converts an array to url string.
*
* @param string $sql.
* @param object $path.
* @param int $index - defaults to 0.
* @return string.
*/
function sec_quote_SQLStr($sql){

if (get_magic_quotes_gpc()) $value = stripslashes($sql);

$value = "'" . mysql_real_escape_string($sql) . "'";

return $value;

}

net_convert_arrayToUrlStr($arr)

/**
* Converts an array to url string.
*
* @param object $xpathObj.
* @param object $path.
* @param int $index - defaults to 0.
* @return array.
*/

function net_convert_arrayToUrlStr($arr){

$s = '';

if(is_array($arr) && !empty($arr)){
while(list($key,$val)=each($arr)){
$s .= urlencode($key) . '=' . urlencode($val) . '&';
}

// remove trailing '&'
$s = substr($s, 0, -1);

}


return $s;

}

xml_get_nodeChildren($xpathObj,$path,$index=0)

/**
* Gets the children of a node.
*
* @param object $xpathObj.
* @param object $path.
* @param int $index - defaults to 0.
* @return array.
*/

function xml_get_nodeChildren($xpathObj,$path,$index=0){

$nodes = $xpathObj->xpath_eval($path);
$nodeSet = $nodes->nodeset;
return isset($nodeSet[$index])?$nodeSet[$index]->children():array();

}

xml_get_XMLStrFromXPath($xpathObj,$path,$index=0)

/**
* Gets xml string from xpath object.
*
* @param object $xpathObj.
* @param object $path.
* @param int $index - defaults to 0.
* @return object.
*/

function xml_get_XMLStrFromXPath($xpathObj,$path,$index=0){
$nodes = $xpathObj->xpath_eval($path); // php 4
$nodeSet = $nodes->nodeset;
return isset($nodeSet[$index])?$nodeSet[$index]->dump_node():null;
}

xml_remove_elementsByTagName($parentNode,$tagName)

/**
* Removes elements by tag name.
*
* @param object $parentNode.
* @param object $tagName.
* @return object.
*/

function xml_remove_elementsByTagName($parentNode,$tagName){

$nodes = $parentNode->get_elements_by_tagname($tagName);

if(count($nodes)>0){
while(list($key,$node)=each($nodes)){
$parentNode->remove_child($node);
}
}

return $parentNode;

}

xml_append_childNode($parentNode,$childNode)

/**
* Appends a child node to a node.
*
* @param object $parentNode.
* @param object $childNode.
* @return object.
*/

function xml_append_childNode($parentNode,$childNode){

$doc = domxml_new_doc("1.0");
$newNode = $doc->create_element("import");
$clonedNode=$parentNode->clone_node(true);
$clonedNode->append_child($childNode->clone_node(true));
return $parentNode->append_child($clonedNode);

}

xml_create_elementWithText($doc, $name, $value)

/**
* Creates an xml element with text.
*
* @param object $doc.
* @param string $name.
* @param string $value.
* @return object.
*/

function xml_create_elementWithText($doc, $name, $value){

$el = $doc->create_element($name);
$textNode = $doc->create_text_node($value);
$el->append_child($textNode);

return $el;

}

xml_clone_xpathToNewDOM($origXPath,$path)

/**
* Appends a node returned by an xpath object to a new DOM.
*
* @param object $origXPath.
* @param string $path
* @return object.
*/

function xml_clone_xpathToNewDOM($origXPath,$path){

$newDOM = domxml_new_doc("1.0");
$temp = $newDOM->create_element("import"); //otherwise get errors in PHP4
$origNode = getNode($origXPath,$path);

$newNode=$origNode->clone_node(true);
$newDOM->append_child($newNode);

return $newDOM;

}

Monday, April 2, 2007

xml_create_node($xml)

/**
* Creates an xml node.
*
* @param string $xml.
* @return object.
*/

function xml_create_node($xml){
$DOM = createDOM($xml);
return $DOM->root();
}

xml_create_xpath($DOM)

/**
* Creates an xpath object.
*
* @param object $DOM
* @return object.
*/
function xml_create_xpath($DOM){
return $DOM->xpath_new_context();
}

xml_create_DOM($xmlStr)

/**
* Creates a DOM from an xml string.
*
* @param string $xmlStr.
* @return object.
*/

function xml_create_DOM($xmlStr){
// Create DOM object of $xmlStr.
return domxml_open_mem($xmlStr);
}

xml_get_attribValue($node, $name, $default)

/**
* Gets the value of an attribute.
*
* @param object $node.
* @param string $name - the name of the attribute.
* @param string $default - the default value to return if attribute not found.
* @return string.
*/

function xml_get_attribValue($node, $name, $default){
if(is_object($node)){
$val = $node->get_attribute($name);
}
else{
$val = $default;
}
return $val;
}

xml_get_nodeSet($xpathObj,$path,$index=0)

/**
* Gets a nodeset.
*
* @param object $xpathObj.
* @param string $path.
* @param int $index - defaults to 0.
* @return string.
*/

function xml_get_nodeSet($xpathObj,$path,$index=0){
$nodes = $xpathObj->xpath_eval($path); // php 4
return $nodes->nodeset;
}

Saturday, March 31, 2007

net_get_HTMLDescriptionFromCode($HTMLCode)

/**
* Returns description of an HTML code.
* @param string $HTMLCode.
* @return string.
*/

function net_get_HTMLDescriptionFromCode($HTMLCode){
$HTMLCodeDescrs = array('100'=>'Continue','200'=>'OK','201'=>'Created','202'=>'Accepted',
'203'=>'Non-Authoritive Information','202'=>'No Content', '205'=>'Reset Content',
'206'=>'Partial Content','301'=>'Moved Permanently','302'=>'Found','303'=>'See Other',
'304'=>'Not Modified','305'=>'Use Proxy','307'=>'Temporary Redirect','401'=>'Unauthorized',
'402'=>'Payment Required', '403'=>'Forbidden', '404'=>'Not Found', '405'=>'Method Not Allowed',
'406'=>'Not Acceptable', '407'=>'Proxy Authentication Required', '408'=>'Request Timeout',
'409'=>'Conflict', '410'=>'Gone', '411'=>'Length Required', '412'=>'Precondition Failed',
'413'=>'Request Entity Too Large','414'=>'Request-URI Too Long', '415'=>'Unsupported Media Type',
'416'=>'Requested Range Not Satisfiable', '417'=>'Expectation Failed',
'500'=>'Internal Server Error', '501'=>'Not Implemented', '502'=>'Bad Gateway',
'503'=>'Service Unavailable', '504'=>'Gateway Timeout', '505'=>'HTTP Version Not Supported');
return isset($HTMLCodeDescrs[$HTMLCode])?$HTMLCodeDescrs[$HTMLCode]:'Unknown network error';
}

net_increment_ipAddress($iPAddress)

/**
* Increments an IP address.
* @param ip $ipAddress.
* @return ip address.
*/

function net_increment_ipAddress($iPAddress){
$ipLong = ip2long($iPAddress);
$ipLong = $ipLong+1;
return long2ip($ipLong);
}

sec_remove_emailInjectionChars($str)

/**
* Removes email injection characters from a string.
* Credit: http://www.securephpwiki.com/index.php/Email_Injection
* @param string $str - string to remove email injection characters from.
* @return string.
*/

function sec_remove_emailInjectionChars($str){
return str_replace("\n",'',str_replace("\r",'',str_replace("%0A",'',$str)));
}

str_get_textBetween($start,$end,$str)

/**
* Gets the text between two points in a string.
* @param int $start.
* @param int $end.
* @param string $str - string to remove quotes from.
* @return string.
*/

function str_get_textBetween($start,$end,$str){
$toMatch = "/" . $start . "(.*?)" . $end . "/";
preg_match($toMatch,$str,$matches);
return isset($matches[1])?$matches[1]:'';
}

str_remove_doubleQuotes($str)

/**
* Removes double quotes from a string.
* @param string $str - string to remove double quotes from.
* @return string.
*/

function str_remove_doubleQuotes($str){
preg_match("/\"(.*?)\"/i", $str,$matches);
return isset($matches[1])?$matches[1]:$str;
}

str_remove_Quotes($str)

/**
* Removes quotes from a string.
* @param string $str - string to remove quotes from.
* @return string.
*/

function str_remove_Quotes($str){
return str_remove_doubleQuotes(str_remove_singleQuotes($str));
}

Thursday, March 29, 2007

ajax request

/**
* Credit: http://www-128.ibm.com/developerworks/xml/library/x-ajaxxml3/index.html?ca=dnw-812
*/
var req = null;
function processReqChange() {
if (req.readyState == 4 && req.status == 200 ) {
var dobj = document.getElementById( 'htmlDiv' );
dobj.innerHTML = req.responseText;
}
}

function loadUrl( url ) {
if(window.XMLHttpRequest) {
try { req = new XMLHttpRequest();
} catch(e) { req = false; }
} else if(window.ActiveXObject) {
try { req = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
try { req = new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { req = false; }
} }
if(req) {
req.onreadystatechange = processReqChange;
req.open('GET', url, true);
req.send('');
}
}

var seachTimer = null;
function runSearch()
{
if ( seachTimer != null )
window.clearTimeout( seachTimer );
seachTimer = window.setTimeout( function watchSearch() {
var url = window.location.toString();
var searchUrl = 'antipat1_content.html?s='+searchText.value;
url = url.replace( /antipat1b_fixed.html/, searchUrl );
loadUrl( url );
seachTimer = null;
}, 1000 );
}

Wednesday, March 28, 2007

str_remove_singleQuotes($str)

/**
* Removes single quotes from a string.
*
* @param string $str.
* @return string.
*/

function str_remove_singleQuotes($str){
preg_match("/'(.*?)'/i", $str,$matches);
return isset($matches[1])?$matches[1]:$str;
}

str_explode_strAssoc($separator,$assignSeparator,$str)

/**
* Works like 'expode()' but parses the string into an associative array where the keys are the
* values on the left of $assignSeparator and the values are the values on the right of $assignSeparator.
* eg if given explodeAssoc(',','=','Content-Type=text/plain,...')
* then this method would return:
* array('Content-Type'=>'text/plain', ...)
* @param string $separator
* @param string $asssignSeparator
* @param string $str
*/

function str_explode_strAssoc($separator,$assignSeparator,$str){

$assocArr = array();

$arr = explode($separator,$str); //eg array('Content-Type=text/plain',...)
while(list($key,$val)=each($arr)){
$temp = explode($assignSeparator,$val);
$assocArr[$temp[0]] = isset($temp[1])?$temp[1]:'';
}
return $assocArr;

}

str_get_strlenmb($s)

/**
* Returns length of a string.
*
* @param string $s - the string.
* @return string.
*/

function str_get_strlenmb($s){
if(function_exists('mb_strlen')){
$len = mb_strlen($s);
}
else{
$len = strlen($s);
}
return $len;
}

str_get_substrmb($s,$start,$len)

/**
* Returns portion of a string.
*
* @param string $s - the string.
* @param string $start - start point.
* @param string $len - length of sub string.
*/
function str_get_substrmb($s,$start,$len){
if(function_exists('mb_substr')){
$sub = mb_substr($s,$start,$len);
}
else{
$sub = substr($s,$start,$len);
}
return $sub;
}

ajx_print_r

/**
* Credit: http://lists.firepipe.net/pipermail/cwe-lug/2004-September/001934.html
function ajx_print_r(obj, cont, tab){

var propertyList = '';
var val = '';
for (prop in obj){
eval("val = 'obj.' + prop")
propertyList += tab + prop + '=>' + eval(val);
propertyList += "\n";
}

return propertyList;

}

Tuesday, March 27, 2007

str_remove_strFromStart($needle,$haystack)

/**
* Removes $needle from the start of $haystack.
*
* @param string $needle - needle.
* @param string $haystack - haystack.
*/

function str_removeStrFromStart($needle,$haystack){
return strpos($haystack,$needle)==0?(substr(($haystack),strlen($needle))):$haystack;
}

Wednesday, March 21, 2007

file_write($fileName, $data, $mode)

/**
* file_write()
*
* Writes data to a file.
* @param string $fileName -file to write to.
* @param string $data -the data to write.
* @param string $mode -mode eg 'w','a' etc.
*/

function file_write($fileName, $data, $mode){

if ($handle = fopen($fileName, $mode)) {
if (flock($handle, LOCK_EX)) { // do an exclusive lock
fwrite($handle, $data);
flock($handle, LOCK_UN); // release the lock
}
fclose($handle);
}

}

net_get_remoteFile($path,$method='GET',$timeout=30)

/**
* net-get-RemoteFile()
*
* Returns a remote fle.
* @param string $path - path to the remote file.
* @param string $method -method to use," get="" or="" post="">
* @param int $timeout - seconds before timeout, defaults to 30.
* @return string.
*/

function net_get_remoteFile($path,$method='GET',$timeout=30){

$parts = parse_url($path);
$params = isset($parts['query'])?$parts['query']:'';

$fp = fsockopen(isset($parts['host'])?$parts['host']:$parts['path'], 80, $errno, $errstr,$timeout);
if (!$fp) {
echo "$errstr ($errno)\n";
}
else {
$out = strtoupper($method). " " . $parts['path'] . " HTTP/1.1\r\n";
$out .= "Accept: */*\n";
$out .= "Host: " . $parts['host'] . "\r\n";
if(strtoupper($method) == "POST" ) {
$strlength = strlen($params);
$out .= "Content-type: application/x-www-form-urlencoded\n";
$out .= "Content-length: ".$strlength."\n\n";
$out .= $params."\n";
}

$out .= "Connection: Close\r\n\r\n";

fwrite($fp, $out);
$contents = '';

while (!feof($fp)) {
$contents .= fgets($fp, 1024);
}
fclose($fp);
}

return $contents;

}

Saturday, March 17, 2007

str_get_pointsBetween($start,$end,$s,$n=0)

/** str_get_pointsBetween()
*
* Given start and end characters returns the start and end positions
* of the substring that includes the character at $n.
* @param string $start - the starting character.
* @param string $end - the end character.
* @param int $n - the position of the character that must be between $start and $end.
* @return array.
*/

function str_get_pointsBetween($start,$end,$s,$n=0){

$textUpToN = strrev(substr($s,0,$n+1));
$startCoord = strlen(substr($textUpToN,0,((strlen($textUpToN) - strpos($textUpToN,$start)) - strlen($textUpToN)==0?0:(strlen($textUpToN) - strpos($textUpToN,$start)))));
$endCoord = $n + (strpos((substr($s,$n)),$end));

return array($startCoord,$endCoord);

}

Friday, March 16, 2007

dir_do_dirIteratorCallback($dir,$fn,$params)

/**
* dir_do_dirIteratorCallback
*
* Iterates over an array.
* @param string $dir - the directory to iterate over.
* @return arguments as an array.
*/

function dir_do_dirIteratorCallback($dir,$fn,$params){

$res = array();

if(class_exists('DirectoryIterator')){
$dirIterator = new DirectoryIterator($dir);
while($dirIterator->valid()) {
if(!$dirIterator->isDot()) {
if(isset($params['file'])) $params['file'] = $dirIterator->getFileName();
$res[] = call_user_func_array($fn,$params);
}
$dirIterator->next();
}
}
else{
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {

if($file!='.' && $file!='..'){
if(isset($params['file'])) $params['file'] = $file;
$res[] = call_user_func_array($fn,$params);
}
}
closedir($dh);
}
}

return $res;

}

fnc_conv_argsToArray()

/**
* fnc_conv_argsToArray
*
* Returns its arguments as an array.
* @param varies.
* @return arguments as an array.
*/

function fnc_conv_argsToArray(){
return get_defined_vars();
}

net_conv_urlStringToArray($urlStr)

/**
* net_conv_urlStringToArray
*
* Converts url string to an array.
* @param string $urlStr - url string to convert to an array.
* @return array.
*/

function net_conv_urlStringToArray($urlStr){
parse_str($urlStr,$urlParamArray);
return($urlParamArray);
}

net_conv_arrayToURLStr($arr,$prefix,$arg_separator)

/**
* net_conv_arrayToURLStr
*
* Converts an array to a url string.
* @param $arr - array to convert to url string.
* @param $prefix - string. If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only.
* @param $arg_separator - arg_separator.output is used to separate arguments, unless this parameter is specified, and is then used.
* Credit: mqchen at gmail dot com
* @return string.
*/

function net_conv_arrayToURLStr($arr,$prefix=null,$arg_separator=null){

if(!function_exists('http_build_query')){
$s = http_build_query($arr, $prefix, $arg_separator);
}
else{
$ret = array();
foreach((array)$arr as $k => $v) {
$k= urlencode($k);
if(is_int($k) && $prefix != null) {
$k = $prefix.$k;
};
if(!empty($key)) {
$k = $key."[".$k."]";
};

if(is_array($v) || is_object($v)) {
array_push($ret,arrayToURLStr($v,"",$arg_separator,$k));
}
else {
array_push($ret,$k."=".urlencode($v));
};
};

if(empty($sep)) {
$sep = ini_get("arg_separator.output");
};

$s = implode($sep, $ret);

}

return $s;

}

xml_get_isXML($xml)

/**
* xml_get_isXML($xml)
*
* Returns true if a string is valid xml.
* @param $separator - char to separate the string with.
* @param $xml - string.
* Credit: Luis Argerich (lrargerich at yahoo.com)
* @return bool.
*/
function xml_get_isXML($xml){
$parser = xml_parser_create_ns("",'^');
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
if (!xml_parse($parser, $xml, true)) {
return false;
}
xml_parser_free($parser);
return true;
}

Thursday, March 15, 2007

str_get_strMatchesEnd($needle,$haystack)

/**
* str_get_strMatchesEnd
*
* Returns true if $needle matches the end of $haystack.
* @param $needle.
* @param $haystack
* @return bool.
*/

function str_get_strMatchesEnd($needle,$haystack){
return strrev(substr(strrev($haystack),0,strlen($needle)))==$needle;
}

str_conv_strToLowerCaseArray($separator,$s)

/**
* strToLowerCaseArray
*
* Converts a string to an array where each element is lowercase.
* @param $separator - char to separate the string with.
* @param $s - string.
* @return array.
*/
function str_conv_strToLowerCaseArray($separator,$s){
$arr = explode($separator,$s);
while(list($key,$val) = each($arr)){
$arr[$key] = strtolower(trim($val));
}
return $arr;
}

fnc_wrap($fnc)

/**
* wrap
*
* Creates a wrapper around a function and returns the wrapper as a function.
* @param $fnc.
* @return function.
* Credit:
* http://www.andyhsoftware.co.uk/space
* http://www.thescripts.com/forum/thread9037.html
* Example usage:
* function times($a,$b){
*$a * $b;
* }
* $dbl = wrap('times',2);
* echo '450 doubled is ' . $dbl(456);
*/
function fnc_wrap($fnc) {
$args = func_get_args();
array_shift($args);
$lambda = sprintf(
'$args = func_get_args(); ' .
'return call_user_func_array(\'%s\', array_merge(unserialize(\'%s\'),$args));',$fnc, serialize($args));
return create_function('', $lambda);
}

Monday, March 12, 2007

net-get-randomIP()

/*
Returns a random IP address
Credit: randomize at randomizer dot com
*/
function net-get-randomIP(){
// Get random number and convert to IP.
return long2ip(rand(0, "4294967295"));
}

Blog Archive