Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Pass an array from an HTML form using Hidden field

It is simple way to pass your array using hidden field of form and get to another side  where you want to use this array's value


Snippet

Create Array

$arrNodeIds = array();
foreach ($data as $k => $objNode) {
$arrNodeIds[] = $objNode->nid;
}

Assign array to hideen field of form
<form method="post" action="/ess_upload/save_images">
<input type="hidden" name="hdnArrNodeIds" value="">
</form>

Get value from other side

$arrNodeIds = unserialize(urldecode($_POST["hdnArrNodeIds"]));
foreach($arrNodeIds as $intNodeId){
    echo $intNodeId;
}

important scrips for php (Part -1)

(1) Human readable Sizes

function ByteSize ( $file_size )
{
$file_size = $file_size-1;
if ($file_size >= 1099511627776) $show_filesize = number_format(($file_size / 1099511627776),2) . " TB";
elseif ($file_size >= 1073741824) $show_filesize = number_format(($file_size / 1073741824),2) . " GB";
elseif ($file_size >= 1048576) $show_filesize = number_format(($file_size / 1048576),2) . " MB";
elseif ($file_size >= 1024) $show_filesize = number_format(($file_size / 1024),2) . " KB";
elseif ($file_size > 0) $show_filesize = $file_size . " b";
elseif ($file_size == 0 || $file_size == -1) $show_filesize = "0 b";
return $show_filesize;
}

(2) Remove non alpha numeric characters

function rem_non_alpha_numeric ( $string, $replace )
{
return preg_replace ( '/[^a-zA-Z0-9]/u', $replace, $string );
}

(3) PHP escape for SQL

/**
* Correctly quotes a string so that all strings are escaped. We prefix and append
* to the string single-quotes.
* An example is escape ( "Don't bother",magic_quotes_runtime () );
*
* @param str the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
*
* @return quoted string to be sent back to database
*/
function escape ( $str, $magic_quotes = false )
{
switch ( gettype ( $str ) )
{
case 'string' :
$replaceQuote = "\\'"; /// string to use to replace quotes
if ( ! $magic_quotes ) {

if ( $replaceQuote [ 0 ] == '\\' ){
// only since php 4.0.5
$str = seo_str_replace ( array ( '\\', "\0" ), array ( '\\\\', "\\\0" ), $str );
//$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
}
return "'" . str_replace ( "'", $replaceQuote, $str ) . "'";
}

// undo magic quotes for "
$str = str_replace ( '\\"','"', $str );

if ( $replaceQuote == "\\'" ) {// ' already quoted, no need to change anything
return "'$str'";
}
else {// change \' to '' for sybase/mssql
$str = str_replace ( '\\\\','\\', $str );
return "'" . str_replace ( "\\'", $treplaceQuote, $str ) . "'";
}
break;
case 'boolean' : $str = ($str === FALSE) ? 0 : 1;
return $str;
break;
case 'integer' : $str = ($str === NULL) ? 'NULL' : $str;
return $str;
break;
default : $str = ($str === NULL) ? 'NULL' : $str;
return $str;
break;
}
}

(4) PHP is keyword in string

function is_keyword_in_string_bol ($keyword, $string)
{
if ( strpos ( $string, $keyword ) === false )
{
return FALSE;
}
else {
return TRUE;
}
}

(5) PHP check url if valid

function is_valid_url ( $url )
{
$url = @parse_url($url);

if ( ! $url) {
return false;
}

$url = array_map('trim', $url);
$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
$path = (isset($url['path'])) ? $url['path'] : '';

if ($path == '')
{
$path = '/';
}

$path .= ( isset ( $url['query'] ) ) ? "?$url[query]" : '';

if ( isset ( $url['host'] ) AND $url['host'] != gethostbyname ( $url['host'] ) )
{
if ( PHP_VERSION >= 5 )
{
$headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
}
else
{
$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

if ( ! $fp )
{
return false;
}
fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
$headers = fread ( $fp, 128 );
fclose ( $fp );
}
$headers = ( is_array ( $headers ) ) ? implode ( "\n", $headers ) : $headers;
return ( bool ) preg_match ( '#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers );
}
return false;
}

(6) How to extract google search results using PHP




if(!isset($_POST['q']))
{
echo '

';
}
else
{
// this would be the URL if you want the results on page 2, 3 ... where $_POST['p'] is multiple of 10
// $off_site = 'http://www.google.com/search?q='.urlencode($_POST['q']).'&start='.$_POST['p'];
$off_site = 'http://www.google.com/search?q='.urlencode($_POST['q']).'&ie=UTF-8&oe=UTF-8';
$fp = fopen ($off_site, 'r') or die('Unable to open file '.$off_site.' for reading');
while (!feof ($fp))
{
$buf = trim(fgets($fp, 4096));
$pos = strpos($buf,'

');
if($pos !== false)
{
$parts = explode('

',$buf);
$parts2 = explode('http://',$parts[1]);
$parts3 = explode('>',$parts2[1]);
echo ''.$parts3[0].'
';
}
}
}


?>

(7) PHP word wrap

/** * Example usage: *
* // Your text * $text = "This is a sentence which contains some words.";
* * // Or from a database result * $text = $row['text'];
* * // Then put it into the function * $text = word_wrap($text);
* * // Output the result * echo $text; */ function word_wrap($text)
{ // Define the characters to display per row
$chars = "10"; $text = wordwrap($text, $chars, "
", 1);
return $text;
}?>

8) Page load time calculator

// Insert this block of code at the very top of your page:
$time = microtime();$time = explode(" ", $time);
$time = $time[1] + $time[0];$start = $time;
// Place this part at the very end of your page$time = microtime();
$time = explode(" ", $time);$time = $time[1] + $time[0];
$finish = $time;$totaltime = ($finish - $start);
printf ("This page took %f seconds to load.", $totaltime);
?>


(9) PHP limit words

function word_limiter($str, $n = 100, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}

$words = explode(' ', preg_replace("/\s+/", ' ', preg_replace("/(\r\n|\r|\n)/", " ", $str)));

if (count($words) <= $n)
{
return $str;
}

$str = '';
for ($i = 0; $i < $n; $i++)
{
$str .= $words[$i].' ';
}

return trim($str).$end_char;
}

(10) PHP limit characters

function character_limiter($str, $n = 500, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}

$str = preg_replace("/\s+/", ' ', preg_replace("/(\r\n|\r|\n)/", " ", $str));

if (strlen($str) <= $n)
{
return $str;
}

$out = "";
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
return trim($out).$end_char;
}
}
}

(11) Show page queries

function mysql_query_2($query){
$_SESSION['queries']++;
return mysql_query($query);

// now use mysql_query_2() function in place of mysql_query()
// Each query will execute exactly the same but count up in
// session variable 'queries'

echo "$_SESSION['queries']";

// just output it somewhere like above...

(12) Checks if a path is absolute or relative

function is_absolute($path)
{
return ($path[0] == '/' || (substr(PHP_OS, 0, 3) == 'WIN' && preg_match('#^[a-z]:/#i', $path))) ? true : false;
}

Remove Leading Zeros Using PHP

It is actually two way to remove unnecessary Zeros

(1) ltrim()

Example : echo ltrim(”001″,”0″);
Result : 1

(2) intval()

Example : echo intval(”001″);
Result : 1