PHP and javascript snippets you can copy and paste.

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"));
}