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

Thursday, September 10, 2009

PHP directory listing : convert a folder tree into an array

Hi there!

in a post few months ago i talked about Directory listing in php, there i show a pair of function to list a directory and turn it into an array.

Well today i come back to that function and change it a little to get it better.

It's quite simple, it start from a path (btw thinking correct) and push it into a structured array. In wich every array element mean a subdirectory, and a null value mean a file.

You can choose the recursive mode in which, when a subfolder is found goes deep into it (recursively too) to fill the array with file and subfolder of that directory.

It's simple, it just check the params $recurrent for true and that the "entry" scaned by read method from metaclass dir is a directory.

Hope someone could find it useful.


function array_converter($path, $recurrent = false, $tree = array())
{
$path = realpath($path);
$d = dir($path);
while(false != ($entry = $d->read()))
{
$complete = $d->path."/".$entry;
if(is_dir($complete) && $entry !== '.' && $entry !== '..')
{
$tree[$entry] = array();
if($recurrent && $entry !== '.' && $entry !== '..')
{
$tree[$entry] = array_converter($complete, $recurrent, $tree[$path][$entry]);
}
} elseif($entry !== '.' && $entry !== '..') {
$tree[$entry] = null;
}
}
$d->close();
return $tree;
}

Tuesday, September 1, 2009

PHP RESTful WebService

Lately im working on a restful php webservice.
In its concepts RESTful is quite easy, but it is still not really understand by most of web programmers.

So if you are interested, first of all you should start to study what behind REST, so its architecture. Good resources are of course wikipedia and Roy Thomas Fielding's dissertation which start the most of works.

Then you may try to develop, or study already coded RESTful web service, the most comes from ruby and python programming languages. Im quite sure to be blind, but in the end i really didn't find goods PHP resources about RESTful (genuine RESTful i mean!) from surfing the web.

The really best i found is an article signed by Gareth Jones: Building a RESTful Web application with PHP and it's starting point lornajane.

A really good book (which i found such likes a REST bible) is RESTful Web Service, written by Leonard Richardson and Sam Ruby.

I know it's a lot of things, this is the RESTful price to pay!

But it's good, trust me people!

Thursday, July 9, 2009

Directory listing in PHP

[edit] i write a new function: PHP directory listing : convert a folder tree into an array [/edit]

Hello world!

Lately im working on a series of tools which can be useful to organize works in web. Of course, nothing new, but im developing somthing mine and small that i can overwork instead of more complex tools.

This run for web of course and my interest is about:
  • deploy
  • backup
  • maintenance
Well about deploy i actually don't know what i want.
Backup it's what im working at.
maintenance i mean a simple tool that switch web-sites/single page in maintenance or work.

About Backup:
I first thought at a tool for a full and incremental backup, but in the end i decided to add the possibility to manage backup as project, saving status about multiple projects. Im currently working and the first piece of code i will give you is a pair of functions that help you to list directories recursively (and turn it into a PHP array.

function create_tree ($path) {
if(is_dir($path)) {
$tree["$path"] = array();
$tree = get_tree($path, $tree);
return $tree;
} else {
echo "<$path> is not a directory";
exit;
}
}

function get_tree($path, $tree) {
$dir = dir($path);
while(false !== ($entry = $dir->read())) {
$complete = "$path/$entry";
if(is_dir($complete) && $entry != "." && $entry != "..") {
$tree["$path"]["$entry"] = get_tree($complete, $tree[$path][$entry]);
} elseif($entry != "." && $entry != "..") {
$mod = date('d-m-Y H:i:s', filemtime($complete));
$tree[] = array( "fn" => $entry, "mod" => $mod);
}
}
return $tree;
}
And that is that, as you can see when it adds a new entry into the array it save last modification time too, sure will be useful to incremental backup.

TODO: pretty print!!!!

Wednesday, April 1, 2009

MySql Table to HTML Table

Hi to all!!

happy april :p like CADIE?

Well now i want to exctract a little preview form dbi that should be useful to someone.

This is a php function and could needed to be a little change from you. in_table function print out a HTML table showing the results of a SELECT query. Actually the function (as it is) need an existent mysql connection and the function mysql_select_db() already called. Then you could add classes to HTML Table element to style as you want.

All the game is based on mysql_fetch_assoc() and array_keys(). It first execute the query (without security check =P) then while cycle result with mysql_fetch_assoc(); then check an internal counter with a value as modulus to "decide" if print headers again or not (headers is the field name or their aliases).
Here the function:

function in_table($query, $repeat = 50) {
$result = mysql_query($query);
if(!$result) {
echo "Error: ".mysql_error();
die();
}
$counter = 0;
echo "<table>";
while($data = mysql_fetch_assoc($result)) {
echo "<tr>";
if($counter % $repeat == 0) {
$fields = array_keys($data);
foreach($fields as $field)
echo "<th>$field</th>";
echo "</tr><tr>";
$counter = 0;
}
foreach($data as $val)
echo "<td>$val</td>";
echo "</tr>";
$counter++;
}
echo "</table>";
}


Here a little snapshoot about the output ^^

Friday, March 13, 2009

Xiaolin wu circle php implementation



Gentle reader,
thank you for stumbling upon this old post. While it still lives here as a snapshot of the past, I’ve since moved to a new blog where I’m publishing updated and hopefully better-written content.

You can find the updated Xiaolin Wu article here.
Feel free to stop by I’d be glad to have you there.

In this post i will finally close this works: Xiaolin Wu look like circle.

Here the function wu_cirlce (helped by distance() and new_color()) that plot an antialiased circle. You need GD supports, the params are commented. Hope this could help someone:


<?php
/*
@author mauro p
*/
function distance($r, $y) {
$real_point = sqrt(pow($r, 2) - pow($y, 2));
return ceil($real_point) - $real_point;
}

function new_color($i) {
return round(($i * 127));
}

/**
* $image a gd image resource
* $r circle's radius
* $color rgb array like array('red' => int(0 : 255), 'green' => int(0 : 255), 'blue' => int(0 : 255))
* $offset_x x axis circle's center
* $offset_y y axis circle's center
*/
function wu_circle($image, $r, $color, $offset_x = null, $offset_y = null) {
$red = $color["red"];
$green = $color["green"];
$blue = $color["blue"];
$offset_x = (is_null($offset_x)) ? 0 : $offset_x;
$offset_y = (is_null($offset_y)) ? 0 : $offset_y;
$x = $xx = $r;
$y = $yy = -1;
$t = 0;
$color = imagecolorallocate($image, $red, $green, $blue);
while($x > $y) {
$y++;
$current_distance = distance($r, $y);
if($current_distance < $t) {
$x--;
}

$trasparency = new_color($current_distance);
$alpha = imagecolorallocatealpha($image, $red, $green, $blue, $trasparency );
$alpha2 = imagecolorallocatealpha($image, $red, $green, $blue, 127 - $trasparency);
imagesetpixel($image, $x + $offset_x, $y + $offset_y, $color);
imagesetpixel($image, $x + $offset_x - 1, $y + $offset_y, $alpha2 );
imagesetpixel($image, $x + $offset_x + 1, $y + $offset_y, $alpha );

imagesetpixel($image, $y + $offset_x, $x + $offset_y, $color);
imagesetpixel($image, $y + $offset_x, $x + $offset_y - 1, $alpha2);
imagesetpixel($image, $y + $offset_x, $x + $offset_y + 1, $alpha);

imagesetpixel($image, $offset_x - $x , $y + $offset_y, $color);
imagesetpixel($image, $offset_x - $x + 1, $y + $offset_y, $alpha2);
imagesetpixel($image, $offset_x - $x - 1, $y + $offset_y, $alpha);

imagesetpixel($image, $offset_x - $y, $x + $offset_y, $color);
imagesetpixel($image, $offset_x - $y, $x + $offset_y - 1, $alpha2);
imagesetpixel($image, $offset_x - $y, $x + $offset_y + 1, $alpha);

imagesetpixel($image, $x + $offset_x, $offset_y - $y, $color);
imagesetpixel($image, $x + $offset_x - 1, $offset_y - $y, $alpha2);
imagesetpixel($image, $x + $offset_x + 1, $offset_y - $y, $alpha);

imagesetpixel($image, $y + $offset_x, $offset_y - $x, $color);
imagesetpixel($image, $y + $offset_x, $offset_y - $x - 1, $alpha);
imagesetpixel($image, $y + $offset_x, $offset_y - $x + 1, $alpha2);

imagesetpixel($image, $offset_x - $y, $offset_y - $x, $color);
imagesetpixel($image, $offset_x - $y, $offset_y - $x - 1, $alpha);
imagesetpixel($image, $offset_x - $y, $offset_y - $x + 1, $alpha2);

imagesetpixel($image, $offset_x - $x, $offset_y - $y, $color);
imagesetpixel($image, $offset_x - $x - 1, $offset_y - $y, $alpha);
imagesetpixel($image, $offset_x - $x + 1, $offset_y - $y, $alpha2);

$t = $current_distance;
}

return $image;
}

$image = imagecreatetruecolor(500, 500);
$c = array("red" => 255, "green" => 0, "blue" => 255);

$image = wu_circle($image, 50, $c, 150, 150);

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);


the result:

Tuesday, March 10, 2009

MySql Database Inspector

Well, came back,
im very busy lately so my posts as you can see, decrease in number. Now i want to start in a new project (lol added to the lot i've already started). It's about mysql database, a simple web application that only show all databases structure in a web browser.

You need to download jquery to let it works.

The workflow is easy: it first put in a multidimensional php array all the information
array[dbs_name][tables_name][fields_name] = field_type.
then create div inside div to graphically render the structure, helped by jquery and putting information out with php.

In the future should be interesting improving it by adding a query box that helps the user in building the query by selecting the type of the query and filling it by clicking on the graphically structure, and obviously manually filling too.

Here the code:
"db_struct.php"
This file contains the function get_structure($mysql_connection_resource) which convert the databases into the array.

function get_structure($conn_res) {
$resdbs = null;
$restbls = null;
$resclmns = null;
$resdbs = mysql_list_dbs($conn_res);
$structure = array();

while($dbs = mysql_fetch_object($resdbs)) {
$dn = $dbs->Database;
$restbls = mysql_list_tables($dn, $conn_res);
while($tbls = mysql_fetch_array($restbls)) {
$tn = $tbls[0];
$resclmns = mysql_list_fields($dn, $tn, $conn_res);
$result = mysql_query("SHOW COLUMNS FROM $tn");
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$fn = $row['Field'];
$structure["$dn"]["$tn"]["$fn"] = $row["Type"];
}
}
}
}
return $structure;
}


"web gui"
This file is the web render. You need to put your connection data and a link to jquery (i used 2.6)
<?
require_once "db_struct.php";
$conn = mysql_connect("yourhost", "youruser", "yourpass");
$s = get_structure($conn);
?>
<!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>
<script type="text/javascript" src="jquery_source"></script>
<style>
#main {
width: auto;
}
.database {
float: left;
border: 1px solid darkred;
background: #CCCCCC;
margin: 5px;
padding: 2px;
width: 300px;
overflow: auto;
}
.table {
border: 1px solid darkgreen;
background: #DDDDDD;
margin-bottom: 4px;
padding: 3px;
width: 280px;
overflow: auto;
}
.field {
border: 1px solid darkblue;
background: #EEEEEE;
margin-bottom: 2px;
padding: 2px;
width: 260px;
overflow: auto;
}
span {
font-weight: bold;
}
span.Db {
color: darkred;
font-size: 150%;
}
span.Tb {
color: darkgreen;
font-size: 130%;
}
</style>
</head>
<body>
<div class="closer">
<p>Collapse: </p>
<button id="cdb">All DBS</button>
<button id="ctb">All TBS</button>
<button id="cfd">All FDS</button>
</div>
<div id="main"></div>
<script type="text/javascript">
var main = $("#main");
<? foreach($s as $db => $tbls): ?>
var td = $("<div>");
td.html("<span class='Tit Db'><?= $db ?></span>");
td.addClass("database");
<? foreach($tbls as $tbl => $flds): ?>
var tt = $("<div>");
tt.html("<span class='Tit Tb'><?= $tbl ?></span>");
tt.addClass("table");
<? foreach($flds as $fld => $type): ?>
var tf = $("<div>");
tf.html("<i><?= $fld ?></i> : <?= $type ?>");
tf.addClass("field");
tt.append(tf);
<? endforeach; ?>
td.append(tt);
<? endforeach; ?>
main.append(td);
<? endforeach; ?>
$("#cdb").click(function() {
$(".database").toggle();
});
$("#ctb").click(function() {
$(".table").toggle();
});
$("#cfd").click(function() {
$(".field").toggle();
});
</script>
</body>
</html>
<? mysql_close($conn); ?>

Tuesday, November 4, 2008

Regex in markup

Well, in an older post (the italian one only) i made intensive use of regex to retrive HTML tags text content. Well, now i want to give you a simple trick to do this in a more elegant way.
Be careful: this post doesn't want to explain regex at all!
We all know that a markup tag with a content look like <tag_name>content</tag_name>.
Well to retrive the content we only need to match everything between tag_name, we match it as:
"everything tat is not the character 'less than'".
So the regex look like: /<tag_name>([^<]+)<\/tag_name>/

here a php interactive session:

Interactive shell

php > $string = "<tag_name_one>http://tag_name_one.com</tag_name_one><tag_name_two>123 ## @ jhkasdfh</tag_name_two>";
php > $tag_name = "tag_name_one";
php > $result = array();
php > preg_match("/<$tag_name>([^<]+)<\/$tag_name>/", $string, $result);
php > print_r($result);
Array
(
[0] => <tag_name_one>http://tag_name_one.com</tag_name_one>
[1] => http://tag_name_one.com
)
php > $tag_name = "tag_name_two";
php > preg_match("/<$tag_name>([^<]+)<\/$tag_name>/", $string, $result);
php > print_r($result);
Array
(
[0] => <tag_name_two>123 ## @ jhkasdfh</tag_name_two>
[1] => 123 ## @ jhkasdfh
)

Thursday, October 9, 2008

Numeri di telefono on the fly

NB: Italian only, this script is useful for italian only readers. This script recive as input an italian phone number and give its holder as output.

In questo post vediamo come ricavere on the fly informazioni su intestatari di numeri di telefono.

Si tratta di due scritp pensati per essere eseguiti direttamente dall'interprete php.

Può essere utile in ufficio sapere in anticipo chi sta telefonando e consultare il sito delle pagine bianche può risultare un dispendio di tempo. Questi script si occupano di interrogare il sito delle pagine bianche fornendo un numero di telefono; se questo è presente nell'elenco verrà visualizzato nella shell evitando i tempi di attesa del browser.

Gli script si servono della libreria curl, quindi è necessario averla propriamente installata sulla propria macchina.

Grazie alla curl, lo script interroga lo script delle pagine bianche incaricato di restituire il numero di telefono; ricevono in risposta il codice html che verrebbe normalmente visualizzato nel broswer. A questo punto il comportamento degli script è differente. Uno ricava i dati servendosi di regex; l'altro istanzia due oggetti: un DOMDocument e un DOMXPath; i dati vengono ricavati con query xpath.

La pagina di risposta delle pagine bianche formatta i dati all'interno di tag che (salvo grosse modifiche alla pagina!!) sono sempre gli stessi;, in questo modo è possibile ricavare i dati. Vediamo il codice degli script, tenendo presente che grosso modo la performance è praticamente identica.

pagine_bianche_regex.php

if($argc != 2) die("Parametro necessario: Numero di telefono\nNon devono essere presenti spazi all'interno del numero.\n\n");
$tel = $argv[1];
$url = "http://www.paginebianche.it/execute.cgi?btt=1&ts=106&cb=8&l=it&mr=10&rk=&om=&qs=$tel";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$out = curl_exec($ch);
$m = array();
$test = preg_match('/<h3 class\=\"org\">([a-zA-z\s]+)<\/h3>/',$out, $m);
echo "\n\t$tel";
if($test == 0) die("\n\tNumero Non Trovato\n\n");
echo "\n\tIntestatario/a: ".$m[1]."\n";
preg_match('/<span class="postal\-code">([0-9]+)<\/span>/', $out, $m);
echo "\tIndirizzo: ".$m[1]." ";
preg_match('/<span class="locality">([a-zA-z\s]+)<\/span>/', $out, $m);
echo $m[1]." ";
preg_match('/<span class="region">\(([A-Z]{2})\)<\/span>/', $out, $m);
echo $m[1]." ";
preg_match('/<span class="street\-address">([A-Za-z\s0-9,]+)<\/span>/', $out, $m);
echo $m[1]."\n\n";
curl_close($ch);

pagine_bianche_xpath.php

if($argc != 2) die("Parametro necessario: Numero di telefono\nNon devono essere presenti spazi all'interno del numero.\n\n");
$tel = $argv[1];
$url = "http://www.paginebianche.it/execute.cgi?btt=1&ts=106&cb=8&l=it&mr=10&rk=&om=&qs=$tel";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$out = curl_exec($ch);
$html = DOMDocument::loadHTML($out);
$xp = new DOMXpath($html);
echo "\n\t$tel";
$data = $xp->query("//h3[@class=\"org\"]");
if($data->length == 0) exit("\n\tNumero Non Trovato\n\n");
echo "\n\tIntestatario/a: ".$data->item(0)->nodeValue;
$data = $xp->query("//span[@class=\"postal-code\"]");
echo "\n\tIndirizzo: ".$data->item(0)->nodeValue;
$data = $xp->query("//span[@class=\"locality\"]");
echo " ".$data->item(0)->nodeValue;
$data = $xp->query("//span[@class=\"region\"]");
echo " ".$data->item(0)->nodeValue;
$data = $xp->query("//span[@class=\"street-address\"]");
echo " ".$data->item(0)->nodeValue."\n\n";
curl_close($ch);

Wednesday, October 8, 2008

A little help

Im gonna show you a simple function in php that will help you to generate the easiest insert mysql query (yet another...).

I use it in a personal web application, someone could find it useful too. It's just an alpha definition, but i really doubt to bring new modifications.

Context:

This function have been called in a asynchronous way from javascript (by XHR), so the parameters comes from $_GET array.

The function accept these parameters as input:

  • $table: name of the table the query concern;
  • $get_unset: ignored $_GET array's indexes that don't need to build the query;
  • $auto_id: this boolean flag is set to true if in that table exist an index called id which is autoincrement

It is clear the follow adaptations should be take into consideration: add an array parameter as a substitute of $_GET array, so $unset_get could be remove from the parameters list. 

Here the code:

function generate_query($table, $get_unset = null, $auto_id = true) {
  $field = "";
  $value = "";
  foreach($get_unset as $gu) unset($_GET[$gu]);
  $query = "INSERT INTO $table(";
  foreach($_GET as $k => $v) {
    $field .= "$k, ";
    $value .= "'$v', ";
  }
  if($auto_id) $query .= "id, ";
  $query .= substr($field, 0, -1).") VALUES(";
  if($auto_id) $query.="null, ";
  $query .= substr($value, 0, -1).")";
  return $query;
}

Tuesday, October 7, 2008

Xiaolin Wu look like circle



Gentle reader,
thank you for stumbling upon this old post. While it still lives here as a snapshot of the past, I’ve since moved to a new blog where I’m publishing updated and hopefully better-written content.

You can find the updated Xiaolin Wu article here.
Feel free to stop by I’d be glad to have you there.

 

 

Xiaolin Wu had implement an algorithm to draw fast antialiased lines and circles.

In this post i will consider the circle.

His idea is based on draw the points next to the real circumference. Drawing that points with different intensity so that will be inverse proportion to the distance from the center and the total sum of the intensities will be constant.

The lemma that leads the plot loop is interesting as complex, so i advise you to search others resources, such as "Graphics Gems II" (you can find on google books the description i'm talkin about).

But i thought to change a little Xiaolin Wu's algorithm in this way:

  • I first plot the original circle;
  • I add two points with different intensity to the nearest real one.
It's a very fast way to draw antialias circle in php.

If you need a fast antialias cirlce to draw in php here's an implementation:

[EDIT : antialias circle full implementation here]

function distance(rad, y) {
real_point = SQRT ( rad*rad - y*y)
return CEIL(real_point) - real_point
}

i = rad
j = 0
I(i, j) = I
T = 0

WHILE ( i <= j ) { j = j + 1; IF distance(rad, j) > T THEN i = i + 1
I(i, j) = distance(rad, j)
I(i - 1, j) = distance(rad, j)
T = distance(rad, j)
}

How I translate sum pieces in PHP?

function distance($r, $y) {
$real_point = sqrt(pow($r, 2) - pow($y, 2));
return ceil($real_point) - $real_point;
}

function new_color($i) {
return $i * 127;
}

// ... plot loop

$current_distance = distance($r, $y);
$transparency = new_color($current_distance);

$alpha = imagecolorallocatealpha($img, /* colore */, $transparency);
$alpha2 = imagecolorallocatealpha($img, /* colore */, 127 - $transparency);

imagesetpixel($image, $x, $y, imagecolorallocate(/* ... */)); // real point
imagesetpixel($image, $x - 1, $y, $alpha2 ); // nearest, inside
imagesetpixel($image, $x + 1, $y, $alpha ); //nearest, outside

The results, high zoom to recognize how the algorithm works:

Finally the result: