» tagged pages
» logout
PHP
Return to PHP

PHP Code Snippets

(or Cancel)

(Editing anonymously: to be credited for your changes, login or register a new account)

other page actions:

Tags Applied to this Topic

1 person has tagged this page:

Sunday, July 06, 2008

Zend Framework view helper for generating menus


/**
* ----------------------------------------------------------------
* Copyright (C) 2008 Agencja Interaktywna Blue Paprica
* Maciej Pa艂ubicki. All rights reserved.
* ----------------------------------------------------------------
*
* /framework/application/Modules/Admin/views/helpers/Menu.php
*
* @author 艁ukasz Kazimierz Bandzarewicz
* @copyright Copyright (C) 2008 Agencja Interaktywna Blue Paprica
* Maciej Pa艂ubicki. All rights reserved.
*/

class Zend_View_Helper_Menu
{

protected function _prepareMenu()
{
return array(
array(
'title' => 'Strona g艂贸wna',
'controller' => 'index'
)

, array(
'title' => 'U偶ytkownicy systemu',
'controller' => 'users',
)

, array(
'title' => 'System Punkt贸w',
'controller' => 'point_categories',
)

, array(
'title' => 'Produkty',
'controller' => 'store_products',

'submenu' => array(
array(
'title' => 'Lista produkt贸w',
'action' => 'list'
),
array(
'title' => 'Dodaj produkt',
'action' => 'create'
)
)
)

, array(
'title' => 'Kupony',
'controller' => 'store_coupons',

'submenu' => array(
array(
'title' => 'Lista kupon贸w',
'action' => 'list'
),
array(
'title' => 'Dodaj kupon',
'action' => 'create'
)
)
)

, array(
'title' => 'Kategorie produkt贸w',
'controller' => 'store_categories',

'submenu' => array(
array(
'title' => 'Lista kategorii',
'action' => 'list'
),
array(
'title' => 'Dodaj kategori臋',
'action' => 'create'
)
)
)

, array(
'title' => 'Dostawcy',
'controller' => 'store_suppliers',

'submenu' => array(
array(
'title' => 'Lista producent贸w',
'action' => 'list'
),
array(
'title' => 'Dodaj producenta',
'action' => 'create'
)
)
)

, array(
'title' => 'Producenci',
'controller' => 'store_manufacturers',

'submenu' => array(
array(
'title' => 'Lista producent贸w',
'action' => 'list'
),
array(
'title' => 'Dodaj producenta',
'action' => 'create',
'params' => '/type/'
)
)
)

, array(
'title' => 'Aktualno艣ci',
'controller' => 'static_news',
'action' => 'list',

'submenu' => array(
array(
'title' => 'Lista aktualno艣ci',
'action' => 'list'
),
array(
'title' => 'Dodaj aktualno艣膰',
'action' => 'create'
)
)
)

, array(
'title' => 'Strony statyczne',
'controller' => 'static_pages',
'action' => 'list'
)

, array(
'title' => 'Logi',
'controller' => 'maintenance_logs',
)
);
}

/**
* @var Zend_View_Interface
*/
public $view;

public function setView(Zend_View_Interface $view)
{
$this->view = $view;
}

public function menu()
{
$menu = $this->_prepareMenu();

$ctrl = Zend_Controller_Front::getInstance();
$controller = $ctrl->getRequest()->getControllerName();
$action = $ctrl->getRequest()->getActionName();
?>


var timeoutID;

function displaySubmenu(submenu_id) {
// hide all elements
$('ul[id*=bp_submenu_]').each(function(e) {
$(this).hide();
});

// show the chosen one
$(submenu_id).show();
}

$(document).ready(function () {

// for each main menu elements
$('a[@id*=bp_menu_]').each(function(e) {

var controller = this.id.substring('bp_menu_'.length);
var submenu_id = '#bp_submenu_' + controller;
var menu_id = '#bp_menu_' + controller;

$(menu_id).mouseover(function() {

timeoutID = setTimeout(function() {
displaySubmenu(submenu_id);
}, 1000);

});

$(menu_id).mouseout(function() {
if (timeoutID) {
clearTimeout(timeoutID);
}
});

$(menu_id).click(function() {
if ($(submenu_id).is(':hidden')) {
displaySubmenu(submenu_id);
return false;
}
});

});

});
//-->






}

}

Saturday, July 05, 2008

Return several values from a function PHP

Return several values from a function PHP



function return_several_values() {
$variable_n_1 = 'One';
$variable_n_2 = 'Two';
$variable_n_3 = '333';

return array($variable_n_1, $variable_n_2, $variable_n_3);
}

list($variable_n_1, $variable_n_2, $variable_n_3) = return_several_values();

?>


Source code: retourner plusieurs valeurs depuis une fonction PHP

Saturday, June 28, 2008

Formating monetary values

Formating monetary values in euro



$number = 1234.567;


// First method
echo sprintf('%.2f €', $number); // 1234.57 鈧


// Second method
echo number_format($number, 2, ',', ' ') . ' €'; // 1 234,57 鈧


// Third method
setlocale(LC_MONETARY, 'en_US');
echo money_format('%n', $number); // $1,234.57

setlocale(LC_MONETARY, 'fr_FR');
echo money_format('%n', $number); // 1 234,57 Eu
echo money_format('%!n €', $number); // 1 234,57 鈧

?>


Retour 脿 la source: Formating monetary values

Thursday, June 26, 2008

image loading with wml links


I'm developing a wap site using wml and php.
my php code is retrievig and displaying blob image from database.
but i cannot include any wml part to this page.
actually i want to display image from database with some links.
is it possible ? plz help me....

my code is.......


function db_connect($user='root', $password='admin', $db='example')
{
mysql_connect('localhost', $user, $password) or die('I cannot connect to db: ' . mysql_error());
mysql_select_db('example');
}
// echo "hellow world";
db_connect();
$sql = "select imgdata from pix where title=1";
$result = mysql_query("$sql");
while($row = mysql_fetch_array($result))
{
$bytes = $row['imgdata'];
}
header("Content-type: image/jpeg");
print $bytes;

exit ();
mysql_close();
?>


--------------------------------------------------------------------------

OUTPUT : DISPLAYING IMAGE
--------------------------------------------------------------------------

BUT IF I REMOVE COMMENT FOR echo "hellow world"; THE OUTPUT WILL B LIKE THIS

-------------------------------------------------------------------------

hellow world

Warning: Cannot modify header information - headers already sent by
(output started at C:\web\htdocs\show\image.php:7) in C:\web\htdocs\show\image.php on line 15

每脴每脿JFIF``每谩* ExifMM*bj*(1*r*2沤鈥陇脨娄'*
H录鈥斅?*卯脹鈥灻潞D没i*脟?c霉脹貌*每忙枚媒:+隆t每茫鈥÷盲芒脿g鲁
\,3cr]赂C*q楼鈥漍忙*脥s鈥÷ヂ統?8"录艩脻鈥楽铆 *露露;脫{鈥好宦得樏
脰_b禄脢谩脟(*脠qK梅ul?*脦娄W脰每炉 禄矛鹿*K.禄脹镁 猫;_st?脽鹿C镁
}}s芦么N锚鈩 枚?铆楼脌沤脧脼脥没驴卢禄^鈥γ得仿镁鈥爅v*艗锚*-啪鈥擬娄没*
枚脺脟?禄*脥么陋么陆*;么么煤隆脝么媒/W霉碌V录每帽]脭啪o锚}2矛
鈥⒚毭箄鈥搣垄芦6m脽镁*脩每卤*=脛鹿}"k脪?芦禄镁+:每X毛X*脦锚鈩脢v=卢eNsZ*k

拧\谩潞露鲁禄梅脳r*玫O锚每B猫藴鹿*tL鈥b忙陇玫+:n**锚*c鈥犈撀р篍U鲁{[搂鈥燶毛\忙禄么啪脰zj漏?鹿鈥橿脺t&脌冒]掳脮铆S@X每Vz
茂铆庐??脭.kq卯脠u拢矛谩没鈥笶v脹C*卢=卯脵W禄脷麓卯脢脟 *}卢篓;F鈥斅6c脙qQ?A ?B
S$篓鲁么{*忙W鸥艗梅3W5路VH*脢*脮虏枚
赂藴*2x?*IL脪U锚脦脙鹿脹)戮禄\*芒*枚赂脟茂CJ*][楼脻?1漏脤垄脤鈥*[K ....

Monday, June 16, 2008

export and import by php

There are at least three ways to backup your MySQL Database :

Execute a database backup query from PHP file.
Run mysqldump using system() function.
Use phpMyAdmin to do the backup.


Execute a database backup query from PHP file

Below is an example of using SELECT INTO OUTFILE query for creating table backup :

include 'config.php';
include 'opendb.php';

$tableName = 'mypet';
$backupFile = 'backup/mypet.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysql_query($query);


include 'closedb.php';
?>
To restore the backup you just need to run LOAD DATA INFILE query like this :

include 'config.php';
include 'opendb.php';

$tableName = 'mypet';
$backupFile = 'mypet.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysql_query($query);


include 'closedb.php';
?>
It's a good idea to name the backup file as tablename.sql so you'll know from which table the backup file is


Run mysqldump using system() function

Wednesday, June 11, 2008

Use the current filename as the HTML body id

// Makes the body id = the current filename - extension
// Useful while working on static markup that relies on styles/scripts targeting the current page


$page = $_SERVER['PHP_SELF'];
$page = str_replace("/","",$page);
$page = str_replace(".php","",$page);
?>


Wednesday, June 04, 2008

Random password generator in PHP

A little function which generates random password of a certain length. It uses all letters, both lowercase and uppercase and all numbers.


//generates a random password which contains all letters (both uppercase and lowercase) and all numbers
function generatePassword($length) {
$password='';
for ($i=0;$i $chr='';
switch (mt_rand(1,3)) {
case 1:
$chr=chr(mt_rand(48,57));
break;
case 2:
$chr=chr(mt_rand(65,90));
break;
case 3:
$chr=chr(mt_rand(97,122));

}
$password.=$chr;
}
return $password;
}

Wednesday, June 04, 2008

Convert Code Page

// Convert from tis to utf


$content = @file_get_contents("http://www.manager.co.th/RSS/Sport/Sport.xml");
header("Content-Type: text/xml; charset=utf-8");
echo iconv('windows-874', 'utf-8', $content);
?>

Tuesday, June 03, 2008

Generate unique filenames in PHP

This code is from http://www.weberdev.com/get_example-3543.html.

It produces filenames similar to this: 4293d8fd-ab63-7c82.tmp


function uniqueFilename($strExt = '.tmp') {
// explode the IP of the remote client into four parts
$arrIp = explode('.', $_SERVER['REMOTE_ADDR']);
// get both seconds and microseconds parts of the time
list($usec, $sec) = explode(' ', microtime());
// fudge the time we just got to create two 16 bit words
$usec = (integer) ($usec * 65536);
$sec = ((integer) $sec) & 0xFFFF;
// fun bit--convert the remote client's IP into a 32 bit
// hex number then tag on the time.
// Result of this operation looks like this xxxxxxxx-xxxx-xxxx
$strUid = sprintf("%08x-%04x-%04x", ($arrIp[0] // tack on the extension and return the filename
return $strUid . $strExt;
}

Wednesday, May 28, 2008

PHP redirect code (with correct header)


header ('HTTP/1.1 301 Moved Permanently');
header('Location: http://domain.com/');
exit;
?>

Sunday, May 25, 2008

[PHP] A simple error function for everyday use...

... It uses the php function "error_log".

define("PATH_LOG","./log/");

function error($line,$method,$class,$system_error,$user_error = "",$date = "",$log = true,$show = true) {
if (empty($date)) {
$date = date('r');
}

if (empty($user_error)) {
$user_error = $system_error;
}


$error = "$date - $method at $line - $system_error\n";

if ($log == true) {
error_log($error,3,PATH_LOG."$class.log");
}

if ($show == true) {
echo "
$user_error
";
}

return true;
}


//Example
class Test {
private showError true;

public function __construct() {
$test = false;

if ($test === false) {
error(__LINE__,__METHOD__,__CLASS__,"sys error blub","There are internal problems. Sorry for that.","",true,$this->showError);
}
}
}

$test = new Test();

Sunday, May 25, 2008

undo_magic_quotes and PHP 6



if(!function_exists('get_magic_quotes_gpc')) {
// for PHP 6.x
function get_magic_quotes_gpc() { return 0; }
}

if(get_magic_quotes_gpc()) {
function undo_magic_quotes(&$array) {
foreach($array as $key => $value) {
if(is_array($value)) {
undo_magic_quotes($array[$key]);
} else {
$array[$key] = stripslashes($value);
}
}
}

undo_magic_quotes($_GET);
undo_magic_quotes($_POST);
undo_magic_quotes($_COOKIE);
undo_magic_quotes($_REQUEST);
undo_magic_quotes($_FILES);
}



Code source magic_quotes and $_GET, $_POST, $_COOKIE, $_REQUEST ( php6 )

Tuesday, May 20, 2008

ZendFramework controller plugin for executing modules specific code

// This is ZF controller plugin for executing module specific code during request dispatch process.
// In this example I am setting different settings for Zend_Layout component for different modules.


class My_Controller_Plugin_ModuleSwitcher extends Zend_Controller_Plugin_Abstract
{
private $_frontController;
private $_moduleDirectory;
private $_moduleName;

public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$this->_init($request);

$method = '_module' . ucfirst($this->_moduleName);
if (method_exists($this, $method)) {
$this->$method($request);
}
}

private function _init(Zend_Controller_Request_Abstract $request)
{
$this->_moduleName = $request->getModuleName();
$this->_frontController = Zend_Controller_Front::getInstance();
$this->_moduleDirectory = dirname($this->_frontController->getControllerDirectory(
$this->_moduleName));
}

private function _moduleWebsite(Zend_Controller_Request_Abstract $request)
{
Zend_Layout::startMvc(array(
'layoutPath' => $this->_moduleDirectory . '/views/layouts',
'layout' => 'common',
));
}

private function _moduleAdmin(Zend_Controller_Request_Abstract $request)
{
Zend_Layout::startMvc(array(
'layoutPath' => $this->_moduleDirectory . '/views/layouts',
'layout' => 'common',
));
}
}

Monday, May 19, 2008

Replace text template for parameter hash table

/*

Replace text template for parameter hash table

Ex:
$mytext = 'Hi, my name is {%name%}, and my address is {%address%}';
rep_templates($mytext, array('name'=>'Steven', 'address'=>'Rua Beira Mar, 12'));
print $text; //Output: Hi, my name is Steven, and my address is Rua Beira Mar, 12

Other ex.

$row = mysql_fetch_assoc($my_result_from_query);

$mytext = file_get_contents('./text_for_email_template.txt');

tranf_dados($mytext, $row);

sendmail($row['email', 'Subject:Hi mane!', $mytext);


*/

function rep_templates(&$t, $d){
preg_match_all ( '/{\%(\w*)\%\}/' , $t , $matches );
foreach($matches[1] as $m){
if($d[$m]!=null){
$pattern = "/{\%".$m."\%\}/";
$t = preg_replace( $pattern, $d[$m], $t);
}
}
}

Friday, May 02, 2008

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 = "\n"; //open table tag
do {
$output .= "\n"; //open row tag
for ($i=1 ; $i $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 .= "\n"; //close TD
} //close for loop
$output .= "\n"; //close row
} while ($next_row); //close do-while (and checks if there's another row)
$output .= "
"; //open TD tag
$output .= (!$row) ? "" : ''.$row[$col_label]; //create checkbox and data from $row (**** you should comment this line if you whish to use dynamic $val_checked****)
// echo (!$row) ? "" : ''.$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 .= "
\n"; //close table
return $output;
}

Wednesday, April 16, 2008

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 return sa ? s : s[0];
}

Wednesday, April 09, 2008

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

Friday, March 28, 2008

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}

Wednesday, March 19, 2008

Post to Jaiku using PHP

This example uses the ProjectX API to post to Jaiku.com

$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=');
$method_result = $xml_result->post2jaiku;
echo 'result' . $method_result;
?>


Reference: SimpleXML processing with PHP [ibm.com]

Wednesday, March 19, 2008

Remove magic quotes on GPC data

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



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

?>
Page 1 | Next >>
Username:
Password:
(or Cancel)