Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 311 total  RSS 

PHP Dynamic Checkbox Table Creator (data retrieved from MySQL DB)

Hi All.
This is a function for Dynamically Create a Checbox Table retrieving information for from a MySQL Database.
As it is quite commented, it's also good for learning how this things work :)
Hope you find it useful.
Feedback is welcome.
Cheers
Dan

function dynamic_checkbox_table ($sql_str, $col_label, $col_name, $val_checked="S", $cant_cols_tbl=3){
/*
	by Daniel Neumann
	this script creates dynamically permite a table containing checkboxes 
	getting the data for the checkboxes from a MySQL DB
	$sql_str, SQL select string to retrieve data from DB (see example in last comment line)
	$col_label, DB column that has values for the checkbox label 
	$col_name, DB column that has values for the checkbox name
	$val_checked="S", value when checked (value="" attribute) it uses the same value for all of them. If you whish to use a dynamic value from a DB, you should comment the line (it´s explained next to the code in the middle of the function) and de-comment the other line (check the code,. you'll understand what I mean). Also, you should use this parameter to specify the column name for the values
	$cant_cols_tbl=3, quantity of columns for the table, it defaults to 3
	usage example: dynamic_checkbox_table("SELECT * FROM keywords", "Keyword", "ID_Keywrd");
*/
	
	//connect DB and run query
	$db="MyDB";
	$db_user="MyUser";
	$pass="MyPass";
	$host="localhost";
	@mysql_connect($host,$db_user,$pass);
	@mysql_select_db($db) or die ("cannot connect to DB");
	$q_resultado = mysql_query($sql_str);
	mysql_close();
	if (mysql_num_rows($q_resultado)==0) exit("no rows returned");
	
	$next_row = mysql_fetch_array($q_resultado); //fetch first row
	
	$output = "<table  border=\"1\">\n"; //open table tag
	do {
		$output .= "<tr>\n"; //open row tag
		for ($i=1 ; $i <= $cant_cols_tbl ; $i++ ){ //loops as many times as $cant_cols_tbl
			$row=$next_row; //assign $row, next row will be checking next one, that avoids starting a new row when it's gonna be empty
			$output .= "<td>"; //open TD tag
			$output .= (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$val_checked.'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should comment this line if you whish to use dynamic $val_checked****)
//			echo (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$row[$val_checked].'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should de-comment this line if you whish to use dynamic $val_checked****)
			$next_row = mysql_fetch_array($q_resultado); //retrieve next row
			$output .= "</td>\n"; //close TD
		} //close for loop
		$output .= "</tr>\n"; //close row
	} while ($next_row); //close do-while (and checks if there's another row)
	$output .= "</table>\n"; //close table
	return $output; 
}

Replace working as PHP str_replace //JavaScript Function

Useless JavaScript implementation of the php function str_replace.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

function replace(f, r, s){
	var ra = r instanceof Array, sa = s instanceof Array, l = (f = [].concat(f)).length, r = [].concat(r), i = (s = [].concat(s)).length;
	while(j = 0, i--)
		while(s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j < l);
	return sa ? s : s[0];
}

Output JavaScript variables from PHP

Class with useful static methods for outputting PHP values into JavaScript format.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

class JS{
	//generic and maybe not the desired results xD
	function value($o){
		if($o === null)
			return 'null';
		$t = strtolower(gettype($o));
		if($t == 'string' && is_numeric($o) && ($o[0] || strlen($o) == 1) || in_array($t, array('double', 'integer')))
			$t = 'number';
		elseif($t == 'string' && preg_match('@^\d{4}(?:-\d{1,2}){1,2}(?: (?:\d{1,2}:){2}\d{1,2})?$@', $o)) //strtotime works also with "strange" values strtotime('x')
			$t = 'date';
		elseif($t == 'array' && ($c = count($k = array_keys($o))) && $k !== range(0, $c - 1))
			$t = 'object';
		elseif(!in_array($t, array('boolean', 'string', 'array', 'object')))
			$t = 'string';
		$t = 'from' . $t;
		return self::$t($o);
	}
	function fromNumber($o){
		return +$o . '';
	}
	function fromObject($o){
		$r = array();
		foreach($o as $n => $v)
			$r[] = self::fromString($n) . ':' . self::value($v);
		return '{' . implode(',', $r) . '}';
	}
	function fromBoolean($o){
		return $o ? 'true' : 'false';
	}
	//$q = should quote? 
	//$c = char that will be used to quote
	function fromString($o, $q = true, $c = '"'){
		return ($p = $q ? $c : '') . preg_replace('/\r\n|\n\r|\r/', '\n', str_replace($c, '\\' . $c, str_replace('\\', '\\\\', $o))) . $p;
	}
	function fromArray($o){
		$s = '';
		foreach($o as $v)
			$s .= ($s ? ',' : '') . self::value($v);
		return '[' . $s . ']';
	}
	function fromDate($o){
		(is_numeric($o) && $o = +$o) || ($o = strtotime($o)) > 0 || ($o = mktime());
		$o = explode(',', date('Y,n,j,G,i,s', $o));
		foreach($o as $i => $v)
			$o[$i] = +$v;
		return 'new Date(' . implode(',', $o)  . ')';
	}
}


Example

$o = new stdClass;
$o->abc = 123;
echo implode("\n<br />", array(
	JS::value('1984-07-22 11:30:12'),
	JS::value('Test'),
	JS::value(1234),
	JS::value(true),
	JS::value(array(1,2,3)),
	JS::value(array('lala' => 'x')),
	JS::value($o)
));

Retrieve Cisco router traffic statistics using perl and RRDTOOL and PHP

Traffic retrieving perl script:
    #!/opt/csw/bin/perl -w
    ##################################################
    # rrdtraf.pl
    #
    # Trafego de equipamentos Cisco
    #
    # 2006.01.12 - Adriano P. 
    # $Id: $

    ######################
    require 5.003;
    use strict;
    use SNMP_Session;
    use BER;
    use SNMP_util "0.90";
    use Time::Local;
    use RRDs;
    use Getopt::Long;
    use Pod::Usage;

    ##### GLOBAL #####
    my %opt;
    my @routers;
    my $IP_APPEND="::2:2";
    my $ERROR;
    my %rrd;

    ##################################################################
    sub main {
    init();

    Options(%opt);

    open(PAR, "rrdtraf.par") || die "Problema ao abrir rrdtraf.parn";

    Msg("* Coletando dados dos switches");
    while () {
    next if grep(/^(#)/,$_);

    my ($community,$ip,$net,@if) = split /:/;
    #$ip = "${community}@${ip}"; #host:port:timeout:retries

    LeituraSNMP($community, $ip,@if);

    syswrite(STDOUT,'.',1) if (!$opt{verbose} && !$opt{V});
    }
    close(PAR);
    Msg("n","* Fim");
    }

    main;
    exit 0;

    ##################################################################
    sub CriaRRD($) {
    my $arquivo = shift;

    print "- Criando base de dados:($arquivo) - " if $opt{verbose};

    RRDs::create ("$arquivo", "--start", time(),
    "--step", "300",
    "DS:ifInOctets:COUNTER:600:0:U",
    "DS:ifOutOctets:COUNTER:600:0:U",
    "RRA:AVERAGE:0.5:1:600",    #2 dias, com amostra de 5min
    "RRA:AVERAGE:0.5:6:700",    #2 semanas, com amostra de 30min
    "RRA:AVERAGE:0.5:24:775",    #2 meses, com amostra de 2h
    "RRA:AVERAGE:0.5:288:400");    #1 ano, com amostra de 1 dia
    if ($ERROR = RRDs::error) {
    die "$0: unable to graph $arquivo: $ERRORn";
    }

    print "okn" if $opt{verbose};
    }

    ##################################################################
    sub LeituraSNMP($$$) {
    my $community = shift;
    my $ip = shift;
    my (@if) = @_;

    my ($idx, $arquivo);
    my $ifInBroadcastPkts = "1.3.6.1.2.1.2.2.1.12";
    my $ifOutBroadcastPkts = "1.3.6.1.2.1.2.2.1.18";
    my @oids = ('ifIndex','ifDescr','ifInOctets','ifOutOctets');

    my @stack = &SNMP("${community}@${ip}", @oids);
    #$ip =~ s/.*@//;

    print "--[ $ip ]-----------n" if $opt{verbose};

    foreach $idx (@stack) {
    my ($id,$nome) = SNMP_util::Check_OID('ifDescr');
    next if (!${$idx}{$id});
    # Ignora interfaces nao cadastradas
    if( !grep(/^${$idx}{$id}$/,@if) ) {
    next;
    }

    my @dados = ();
    $dados[0] = $ip;                # 1: ip
    @dados[1,2,3,4] = &Dados($idx,@oids);
    my $ifIndex = $dados[1];

    $arquivo = "${ip}_${ifIndex}.rrd";
    if (! -e "$arquivo") {
    CriaRRD($arquivo);
    }
    AtualizaRRD($arquivo, @dados);
    }
    }

    ##################################################################
    sub AtualizaRRD(@) {
    my $arquivo = shift;
    my (@dados) = @_;

    print "- $dados[0], $dados[1], $dados[2], $dados[3], $dados[4]n" if $opt{verbose};

    RRDs::update ($arquivo, "N:$dados[3]:$dados[4]");
    }

    ##################################################################
    sub GrafRRD {
    my ($start_date,$eqto) = @_;

    print "Gerando grafico ($start_date)...";

    my @option = ("-s", $start_date, "-w", "600", "-h", "170",
    "-e", "now", "--alt-autoscale", "-l 0",
    "-x", "HOUR:1:DAY:1:HOUR:2:0:%H");

    if ($start_date >= 2) {

    ######################
    # GRAPH 1
    RRDs::graph ("$eqto.gif", @option,
    "DEF:in=$eqto.gif:ifInOctets:AVERAGE",
    "DEF:out=$eqto.gif:ifOutOctets:AVERAGE",
    "LINE2:c13#0000aa:Entrada",
    "LINE2:c14#ff66ff:Saida");
    if ($ERROR = RRDs::error) {
    die "$0: unable to graph $eqto.gif: $ERRORn";
    }

    }

    print "okn";
    }

    ##################################################################
    sub SNMP($@) {
    my $ip = shift;
    my @oids = @_;

    my $ip_="$ip${IP_APPEND}";
    my ($idx,$oid,@stack);

    foreach my $tuple (snmpwalk($ip_, @oids)) {
    my($var,$counter) = split /:/, $tuple, 2;
    $idx = substr($var, rindex($var,'.')+1);
    $oid = substr($var, 0, length($var)-length($idx)-1);
    #warn "* $vart$countern" if $opt{V};
    $stack[$idx]{$oid} = $counter;
    }

    return @stack;
    }

    ##################################################################
    sub Dados($$) {
    my $var = shift;
    my @oids = @_;

    my @dados = ();

    for(my $i=0; $i  2) if $$opt{man};
    }

    ##################################################################
    sub init {
    # queue up reading the MIB file
    #&snmpQueue_MIB_File("/home/adr/mibs/IWFG.MIB");
    $SNMP_Session::suppress_warnings = 2;
    $SNMP_util::Debug = 0;
    $= = 1000;
    }

    #eof


rrdtraf.par - sample file
    community:10.1.2.3:Comment:FastEthernet0/1:FastEthernet0/2
    community:10.1.2.4:Comment:FastEthernet0/1
    community:10.1.2.5:Comment:FastEthernet0/1:FastEthernet0/2:FastEthernet0/12:FastEthernet0/18


PHP script to plot the traffic graph:
    {!--
    ##################################################
    # rrdgraph.php
    #
    # Plotagem dos graficos de arquivos rrd
    #
    # 2006.01.12 - Adriano P.
    # $Id: $
    --}
    {?php
    $display = $_GET['display'];

    if ($display == 'image') {

    header ("Content-type: image/png",false);

    $display = $_GET['display'];
    $rrdtool = "/opt/csw/bin/rrdtool ";
    $graph_opt =     "--height 150 --width 550 " .
    "--start -172800 ".
    "--imgformat PNG ".
    "--no-minor ".
    "-c BACK#ffffff ".
    "-c SHADEA#ffffff ".
    "-c SHADEB#ffffff ".
    "-c FRAME#ffffff ".
    "-v 'bits/seg' -L 8  ";

    $arq1="/home/aprado/proj/traf/".$_GET['arq1'];

    $graph =
    "DEF:in1=$arq1:ifInOctets:AVERAGE ".
    "DEF:out1=$arq1:ifOutOctets:AVERAGE ".
    "CDEF:in1_bps=in1,8,* ".   #NÃO ESQUECER DE MULTIPLICAR POR 8
    "CDEF:out1_bps=out1,8,* ".  #(1 byte = 8 bits)
    "HRULE:0#000000:'       ' ".
    "AREA:in1_bps#6699cc:'Saida' ".
    "LINE2:out1_bps#003399:'Entrada' ";

    # function for rrdtool execution
    function rrdtool_execute($rrdtool, $command) {
    return fpassthru(popen($rrdtool . $command, "r"));
    }

    $command = $graph_opt . $graph;
    return rrdtool_execute($rrdtool, " graph - $command");
    }
    ?}

    {HTML}
    {HEAD}
    {STYLE TYPE="text/css"}
    H1 {
    font-weight: bold;
    font-size: 18pt;
    line-height: 18pt;
    font-family: arial,helvetica;
    font-variant: normal;
    font-style: normal;
    }
    BODY {
    color: black;
    background-color: white;
    font-size: 11pt;
    line-height: 12pt;
    font-family: arial,helvetica;
    font-variant: normal;
    font-style: normal;
    }
    {/STYLE}
    {/HEAD}
    {BODY}

    {CENTER}
    {TABLE}
    {?php

    function graphit($arq1, $descr1) {
    print "{tr align='center'}{td}{font color='#003399'}{b}$descr1{/b}{/font}{br}n";
    print "{/td}{/tr}n";
    print "{tr}{td align='center'}{img xsrc='/traf/rrdgraph.php?display=image&arq1=$arq1' border='0'}";
    print "{hr width='100%' size='2'}{/td}{/tr}n";
    }

    graphit("10.1.2.3_2.rrd","10.1.2.3 - f0/1: Comentario");
    graphit("10.1.2.3_3.rrd","10.1.2.3 - f0/2: Comentario");

    ?}
    {/TABLE}
    {/CENTER}
    {/BODY}
    {/HTML}

Post to Jaiku using PHP

This example uses the ProjectX API to post to Jaiku.com
<?php
  $msg = 'this is just a test message using the ProjectX API for posting to Jaiku';

  $xml_result =  simplexml_load_file('http://rorbuilder.info/api/projectx.cgi?xml_project=<project name="jaiku"><methods><method name="post"><params><param var="user" val="jrobertson"/><param var="msg" val="' . $msg . '"/><param var="location" val="London"/><param var="apikey" val="9ee6ffd165r364492"/></params></method></methods></project>');
  $method_result = $xml_result->post2jaiku;
  echo 'result' . $method_result;
?>


Reference: SimpleXML processing with PHP [ibm.com]

Remove magic quotes on GPC data

Removes magic quotes on $_GET, $_POST, $_COOKIE, $_FILES and $_REQUEST, when they are enabled.

<?php

// remove magic_quotes
if(get_magic_quotes_gpc())
{
  function undo_magic_quotes_array($array)
  {
    return is_array($array) ? array_map('undo_magic_quotes_array', $array) : str_replace("\\'", "'",
							                                                               str_replace("\\\"", "\"",
                                                                             str_replace("\\\\", "\\",
                                                                             str_replace("\\\x00", "\x00", $array))));
  }

  $_GET = undo_magic_quotes_array($_GET);
  $_POST = undo_magic_quotes_array($_POST);
  $_COOKIE = undo_magic_quotes_array($_COOKIE);
  $_FILES = undo_magic_quotes_array($_FILES);
  $_REQUEST = undo_magic_quotes_array($_REQUEST);
}

?>

Remove magic quotes on GPC data

Removes magic quotes on $_GET, $_POST, $_COOKIE, $_FILES and $_REQUEST, when they are enabled.

<?php

// remove magic_quotes
if(get_magic_quotes_gpc())
{
  function undo_magic_quotes_array($array)
  {
    return is_array($array) ? array_map('undo_magic_quotes_array', $array) : str_replace("\\'", "'",
							                                                               str_replace("\\\"", "\"",
                                                                             str_replace("\\\\", "\\",
                                                                             str_replace("\\\x00", "\x00", $array))));
  }

  $_GET = undo_magic_quotes_array($_GET);
  $_POST = undo_magic_quotes_array($_POST);
  $_COOKIE = undo_magic_quotes_array($_COOKIE);
  $_FILES = undo_magic_quotes_array($_FILES);
  $_REQUEST = undo_magic_quotes_array($_REQUEST);
}

?>

Load PRX document and display elements

//Using a simple curl library (not shown) to get xml text
$curl = new CURL();
//$prx contains the url of a PRX document (e.g. http://www.prxbuilder.com/link.aspx?p=1)
$xml = $curl->get($prx);

//Load the XML file
$doc = new DOMDocument();
$doc->loadXML($xml);

//Retrieve specific PRX elements (subheadline, dateline, body)
$subheadline = $doc->getElementsByTagName('subheadline')->item(0)->nodeValue;
$dateline = $doc->getElementsByTagName('dateline')->item(0)->nodeValue;
$body = $doc->getElementsByTagName('body')->item(0)->nodeValue;

//Format and display - apply_filters is a WP function.
$content = '<p>'.$subheadline.'</p>';
$content .= '<p>'.$dateline.'</p>';
$content .= '<p>'.$body.'</p>';
$content = apply_filters('the_content_rss', $content);
$content = str_replace(']]>', ']]&gt;', $content);

echo $content;

Load PRX document and display elements

//Using a simple curl library (not shown) to get xml text
$curl = new CURL();
//$prx contains the url of a PRX document (e.g. http://www.prxbuilder.com/link.aspx?p=1)
$xml = $curl->get($prx);

//Load the XML file
$doc = new DOMDocument();
$doc->loadXML($xml);

//Retrieve specific PRX elements (subheadline, dateline, body)
$subheadline = $doc->getElementsByTagName('subheadline')->item(0)->nodeValue;
$dateline = $doc->getElementsByTagName('dateline')->item(0)->nodeValue;
$body = $doc->getElementsByTagName('body')->item(0)->nodeValue;

//Format and display - apply_filters is a WP function.
$content = '<p>'.$subheadline.'</p>';
$content .= '<p>'.$dateline.'</p>';
$content .= '<p>'.$body.'</p>';
$content = apply_filters('the_content_rss', $content);
$content = str_replace(']]>', ']]&gt;', $content);

echo $content;

Automating Zend MVC Structure

Automating Zend MVC Structure
This is what I use... It's very useful.


<?php
#
# Automate the creation of the Zend MVC Framework
# Script Written by: Fernando Barajas
# Usage: php ./zendcreate.php
#

# Create the Zend MVC Framework.
define('ZEND_FILE_TYPE', '.tar.gz');
define('ZEND_FILE_NAME', 'ZendFramework-1.5.0'. ZEND_FILE_TYPE);
define('ZEND_FRAMEWORK_URL', 'http://framework.zend.com/releases/ZendFramework-1.5.0/'. ZEND_FILE_NAME);
define('APPLICATION_NAME', 'zend_'. time());


passthru("wget ". ZEND_FRAMEWORK_URL);


if(file_exists(ZEND_FILE_NAME)) {
	# unzip the file -- tar zxvf ./ZEND_FILE_NAME
	passthru("tar zxvf ". ZEND_FILE_NAME);
	
	# Make the Applications Directories
	passthru("mkdir ". APPLICATION_NAME);
	
	# Move the Library directory into the application directory
	passthru("mv ./". basename(ZEND_FILE_NAME, ZEND_FILE_TYPE) ."/library ./". APPLICATION_NAME ."/library");
	
	# Make the App Directory 
	passthru("mkdir ". APPLICATION_NAME ."/app");
	
		passthru("mkdir ". APPLICATION_NAME ."/app/controllers");
		passthru("mkdir ". APPLICATION_NAME ."/app/models");
		passthru("mkdir ". APPLICATION_NAME ."/app/views");
			
			passthru("mkdir ". APPLICATION_NAME ."/app/views/scripts");
			
	
	# Make the public Directory
	passthru("mkdir ". APPLICATION_NAME ."/public");
	
	# Make the Front Controller / Bootstrap file
$zend_bootstrap_code = '
<?php
# Set Error Reporting
error_reporting(E_ALL|E_STRICT);
ini_set(\'display_errors\', \'on\');

# Set include path the DOCUMENT_ROOT / library for Zend Library
ini_set(\'include_path\', $_SERVER[\'DOCUMENT_ROOT\']."/../library");

# Zend Framework Includes
require_once \'Zend/Loader.php\';

Zend_Loader::loadClass(\'Zend_Controller_Front\');

# Un-Comment the two lines below if you will be using Routes
# Most likely you will be. I recommend that you do. 
# They are very useful
#
# Zend_Loader::loadClass(\'Zend_Controller_Router_Rewrite\');
# Zend_Loader::loadClass(\'Zend_Controller_Router_Route_Regex\');
#

# Get the front controller instance
$front = Zend_Controller_Front::getInstance();
$front->setControllerDirectory("../app/controllers");

$front->throwExceptions(true);

#
# Get an Instance For Routing
# $route = $front->getRouter(); // Returns a rewrite router by default
# $route->addRoute(\'user\',
#	new Zend_Controller_Router_Route(\'user/:username\', array(\'controller\' => \'index\', \'action\' => \'test\'))
# );
#
# $route->addRoute(\'product\',
#	new Zend_Controller_Router_Route_Regex(\'product/(\d+)\', array(\'controller\' => \'index\', \'action\' => \'test\'))
# );
#
# $route->addRoute(\'login\',
#	new Zend_Controller_Router_Route_Regex(\'login\', array(\'controller\' => \'index\', \'action\' => \'test\'))
# );
#

# Start the dispatch
$front->dispatch();

?>
';
	# Write the Bootstrap file
	file_put_contents("./". APPLICATION_NAME ."/public/index.php", trim($zend_bootstrap_code));
	
# Write The Index Controller
$zend_index_controller_code = '
<?php

class IndexController extends Zend_Controller_Action {

	public function indexAction() {
		# => Logic code here...
		$this->view->random_number = rand(0,10);
		$this->view->status = "It works!";
		$this->render("index");
	}
}

?>
';
	# Write the First Index Controller
	file_put_contents("./". APPLICATION_NAME ."/app/controllers/IndexController.php", trim($zend_index_controller_code));


# Write the index view file
$zend_index_view_code = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title>Zend Framework</title>
</head>
<body>
<h2>Status: <?= $this->status ?></h2>
<div>
	Random Number: <?= $this->random_number ?>
</div>
</body>
</html>
';
	# Write the First Index View File
	passthru("mkdir ./". APPLICATION_NAME ."/app/views/scripts/index");
	file_put_contents("./". APPLICATION_NAME ."/app/views/scripts/index/index.phtml", $zend_index_view_code);
	
	
# Create the .htaccess file
$zend_htaccess_code = '
RewriteEngine On
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php
';
	# Write the .htaccess code to disk
	file_put_contents("./". APPLICATION_NAME ."/public/.htaccess", trim($zend_htaccess_code));
	
	
	# Delete the Downloaded Framework Directory and tar file
	passthru("rm -f ./". ZEND_FILE_NAME);
	passthru("rm -rf ./". basename(ZEND_FILE_NAME, ZEND_FILE_TYPE));
	
	passthru("clear");
	
	echo "\nZend Framework has been created... Done!\n\n";
}

?>
« Newer Snippets
Older Snippets »
Showing 1-10 of 311 total  RSS