Caputo’s blog

Informatica, tecnologia, programmazione, fai da te, papercraft e papertoy

Conoscere quanso è stata effettuata l’ultima visita dallo stesso utente in PHP

novembre 16th, 2009 by Giovanni Caputo

Conoscere quando è stata effettuata l’ultima visita dall’utente può essere molto utile.
Vediamo come realizzarla in PHP con l’utilizzo dei cookie.

< ?php
if(isset($_COOKIE['AboutVisit']))
{
$last = $_COOKIE['AboutVisit']; }
$year = 31536000 + time() ;
//this adds one year to the current time, for the cookie expiration
setcookie(AboutVisit, time (), $year) ;
if (isset ($last))
{
$change = time () - $last;
if ( $change > 86400)
{
echo "Welcome back!  You last visited on ". date("m/d/y",$last) ;
// Tells the user when they last visited if it was over a day ago
}
else
{
echo "Thanks for using our site!";
//Gives the user a message if they are visiting again in the same day
}
}
else
{
echo "Welcome to our site!";
//Greets a first time user
}
?>

Category: Siti Web, Tecnologia, tutorial | No Comments »

print_r() & var_dump() formattati per sviluppatori PHP

novembre 16th, 2009 by Giovanni Caputo

Molti sviluppatori PHP usano print_r() e var_dump() per effettuare il debug delle proprie applicazioni. I risultati di tali funzioni sono difficile da leggere e non sono formattati.

Krumo rimpiazza queste funzioni  per poter visualizzare le informazioni relative alle variabili in maniera strutturata.

Website: http://krumo.kaloyan.info/
Demo: http://krumo.kaloyan.info/#example
Download: http://krumo.kaloyan.info/#download

Category: Programmazione, Tecnologia, tutorial | No Comments »

Scrivere un testo su una immagine in PHP

novembre 9th, 2009 by Giovanni Caputo

Questa funzione permette di scrivere un testo e di fonderlo con un’immagine esistente. Se l’immagine non esiste restituisce un’immagine con un messaggio di errore!

< ?php

/*** set the header for the image ***/
header("Content-type: image/jpeg");

/*** specify an image and text ***/
$im = writeToImage('test.jpg', 'PHPRO rules again');

/*** spit the image out the other end ***/
imagejpeg($im);

/**
 *
 * @Write text to an existing image
 *
 * @Author Kevin Waterson
 *
 * @access public
 *
 * @param string The image path
 *
 * @param string The text string
 *
 * @return resource
 *
 */
function writeToImage($imagefile, $text){
/*** make sure the file exists ***/
if(file_exists($imagefile))
    {
    /*** create image ***/
    $im = @imagecreatefromjpeg($imagefile);

    /*** create the text color ***/
    $text_color = imagecolorallocate($im, 233, 14, 91);

    /*** splatter the image with text ***/
    imagestring($im, 6, 25, 150,  "$text", $text_color);
    }
else
    {
    /*** if the file does not exist we will create our own image ***/
    /*** Create a black image ***/
    $im  = imagecreatetruecolor(150, 30); /* Create a black image */

    /*** the background color ***/
    $bgc = imagecolorallocate($im, 255, 255, 255);

    /*** the text color ***/
    $tc  = imagecolorallocate($im, 0, 0, 0);

    /*** a little rectangle ***/
    imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

    /*** output and error message ***/
    imagestring($im, 1, 5, 5, "Error loading $imagefile", $tc);
    }
return $im;
}

?>

Fonte: http://www.sastgroup.com

Category: Programmazione | No Comments »

Alcune classi Utili per PHP

settembre 30th, 2009 by Giovanni Caputo

LETTORE PSD

Utilizzo:

<?php
// Send header to client browser
header("Content-type: image/jpeg");
// Includes the requested class
include_once('classPhpPsdReader.php');
// Finally display the PSD on the screen
imagejpeg(imagecreatefrompsd('yourPsdFile.psd'));
?>

Download

Determinare BROWSER

Download

ADOdb

La maggior parte dei siti web usano il database per salvare tutti i dati. ADOdb è una libreria PHP che estrae dal database e supporta MySQL, PostgreSQL, Interbase, Firebird, Oracle, MS SQL e altri.

Download


WPGet

WPGet è una classe PHP che permette facilmente di ottenere infomrazioni da un database di Wordpress 2.X. In altre parole permetter di ottenere post, commenti, e altro di un blog Wordpress per visualizzarle su un sito non realizzato con questo CMS.
Download

Category: Open Source, Programmazione, Tecnologia, tutorial | No Comments »

Creare file Zip in PHP

settembre 18th, 2009 by Giovanni Caputo

* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
	//if the zip file already exists and overwrite is false, return false
	if(file_exists($destination) && !$overwrite) { return false; }
	//vars
	$valid_files = array();
	//if files were passed in...
	if(is_array($files)) {
		//cycle through each file
		foreach($files as $file) {
			//make sure the file exists
			if(file_exists($file)) {
				$valid_files[] = $file;
			}
		}
	}
	//if we have good files...
	if(count($valid_files)) {
		//create the archive
		$zip = new ZipArchive();
		if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		}
		//add the files
		foreach($valid_files as $file) {
			$zip->addFile($file,$file);
		}
		//debug
		//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

		//close the zip -- done!
		$zip->close();

		//check to make sure the file exists
		return file_exists($destination);
	}
	else
	{
		return false;
	}
}

ESEMPIO APPLICATO

 
$files_to_zip = array(
	'preload-images/1.jpg',
	'preload-images/2.jpg',
	'preload-images/5.jpg',
	'kwicks/ringo.gif',
	'rod.jpg',
	'reddit.gif'
);
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');
Fonte: sastgroup

Category: Programmazione, Siti Web | No Comments »

Trovare la posizione di un IP su google maps

agosto 31st, 2009 by Giovanni Caputo

Volevo segnalare un tutorial che permette di identificare la posizione geografica di un IP su google maps.

LINK

Category: Programmazione, Siti Web, Tecnologia, tutorial | 2 Comments »

Sicurezza PHP e MySQL: proteggersi dalla SQL Injections

giugno 1st, 2009 by Giovanni Caputo

Vediamo alcune funzioni utili che possono essere utilizzati per proteggersi dalla SQL Injections. Questo tipo di attacco/problema è causato da alcuni caratteri speciali come apostrofi o slash che, se inseriti in una query, possono compromottere la sicurezza del database.

Vediamo, quindi, alcune funzioni PHP molto utili che preanalizzano i dati prima di effettuare una query.

add_slashes

Funzione built-in che aggiunge uno slash prima di apici, doppi apici, backslash, etc…

Per esempio se usata per la stringa O’Reilly,  la funzione, resituisce O\’Reilly. Questo però non basta per rendere una query sicura.

magic_quotes_gpc

Magic Quotes non è una funzione ma una opzione di configurazione. Questa opzione permette di aggiungere automaticamente blackslask ad ogni variabile, $_GET, $_POST e $_COOKIE,  che contiene uno dei caratteri menzionati precedentemente.

mysql_escape_string

Protegge i caratteri speciali come slash singoli o doppi, backslash, \x00, \n, \r, and \x1a.

Questa funzione è stata progettata proprio per essere utilizzata per query da eeguire su MySQL.

Category: Programmazione, Siti Web, tutorial | No Comments »

Lettore feed in PHP

maggio 27th, 2009 by Giovanni Caputo

<?php

/*

$insideitem = false;

$tag = "";

$title = "";

$description = "";

$link = "";

echo"

";

$xml_parser = xml_parser_create();

xml_set_element_handler($xml_parser, "startElement", "endElement");

xml_set_character_data_handler($xml_parser, "characterData");

$fp = fopen("http://www.nomesito.com/rss.xml","r") or die("Error reading RSS data.");

while ($data = fread($fp, 4096))

xml_parse($xml_parser, $data, feof($fp))

or die(sprintf("XML error: %s at line %d",

xml_error_string(xml_get_error_code($xml_parser)),

xml_get_current_line_number($xml_parser)));

fclose($fp);

xml_parser_free($xml_parser);

echo"";

*/

 ?

function startElement($parser, $name, $attrs) {

global $insideitem, $tag, $title, $description, $link;

if ($insideitem) {

$tag = $name;

} elseif (strtolower($name) == "item") {

$insideitem = true;

}

}

function endElement($parser, $name) {

global $insideitem, $tag, $title, $description, $link;

if (strtolower($name) == "item") {

printf("

•	%s",

trim($link),trim($title),trim($title));

printf("%s",trim($description));

$title = "";

$description = "";

$link = "";

$insideitem = false;

}

}

function characterData($parser, $data) {

global $insideitem, $tag, $title, $description, $link;

if ($insideitem) {

switch (strtolower($tag)) {

case "title":

$title .= $data;

break;

//case "description":

//$description .= $data;

//break;

case "link":

$link .= $data;

break;

}

}

}

Read the rest of this entry »

Category: Programmazione, Siti Web | No Comments »

File manager in PHP, Ajax e Javascript

maggio 24th, 2009 by Giovanni Caputo

1. AjaXplorer

Ajax File Manager

2. fileNice

Ajax File Manager

fileNice is a free php file browser, particularly useful if you have a ‘dump’ folder on your server where you regularly upload files and you want to be able to see what’s there.

3. File Thingie

Ajax File Manager

4. MooTools based FileManager

Ajax File Manager

5. Relay

Ajax File Manager

6. Kae’s File Manager

Ajax File Manager

7. eXtplorer

Ajax File Manager

Read the rest of this entry »

Category: Open Source, Programmazione, Siti Web | No Comments »

Funzioni utili per PHP

maggio 9th, 2009 by Giovanni Caputo

  1. Generare password random

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <?php
    
    function generatePassword($length) {
        $character = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $password = "";
        for($i=0;$i<$length;$i++) {
            $password .= $character[rand(0, 61)];
        }
        return $password;
    }
    
    echo generatePassword(7);
    
    ?>
  2. Calcolare anni a partire dalla data di nascita

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <?php
    
    $testcase = array("12-03-1985", "15-01-1987", "01-01-2000");
    
    function getAge($year) {
        return floor(abs(strtotime('now') - strtotime($year))/31536000);
    } 
    
    foreach($testcase as $test) {
        echo "Born in $test, approximately age is " . getAge($test)." years<br/>";
    }
    ?>
  3. Ottenere indirizzo IP dei visitatori

    1
    2
    3
    4
    5
    <?php  
    
    echo "Your IP address is " . $_SERVER['REMOTE_ADDR'];  
    
    ?>
  4. Ottenere l’estensione di un file

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <?php
    
    $testcase = array("sample.txt", "sample.jpg", "sample.case.txt");
    
    function extension($filename){
        return substr(strrchr($filename, '.'), 1);
    }
    
    foreach($testcase as $test) {
        echo "Extension from $test is " . extension($test) . "<br/>";
    } 
    
    ?>
  5. Ordinamento di un array

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?php
    
    $data_list = array("lychee", "pineapple", "apple", "mango", "strawberry", "banana", "orange", "grape", "guava");
    
    sort($data_list);
    foreach($data_list as $data) {
        echo $data . "<br/>";
    } 
    
    ?>
  6. Tempo trascorso da una certa data

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    <?php
    
    $testcase = array("12-03-1985", "15-01-2007", "04-04-2009", "01-01-2009", "30-03-2009", "07-04-2009", "07-04-2009 11:12");
    
    define("MINUTE", 60);
    define("HOUR", 3600); // 60 * 60 
    define("DAY", 86400); //  60 * 60 * 24 
    define("WEEK", 604800); // 60 * 60 * 24 * 7
    define("MONTH", 2592000); // 60 * 60 * 24 * 30
    define("YEAR", 31536000); // 60 * 60 * 24 * 365
    
    function timeSince($date) {
    
        $since = abs(strtotime('now') - strtotime($date));
    
        if($since > YEAR) {
            $year = floor($since / YEAR);
            return "more than $year year(s) ago";
        }    
    
        if ($since > MONTH) {
            $month = floor($since / MONTH);
            return "about $month month(s) ago";
        } 
    
        if ($since > WEEK) {
            $week = floor($since / WEEK);
            $day = floor(($since - ($week * WEEK)) / DAY);
            return "about $week week(s), and $day day(s) ago";
        }
    
        if ($since > DAY) {
            $day = floor($since / DAY);
            $hour = floor(($since - ($day * DAY)) / HOUR);
            return "about $day day(s), $hour hour(s) ago";
        }
    
        if ($since > HOUR) {
            $hour = floor($since / HOUR);
            $minute = floor(($since - ($hour * HOUR)) / MINUTE);
            return "about $hour hour(s), $minute minute(s) ago";
        }
    
        if ($since > MINUTE) {
            $minute = floor($since / MINUTE);
            return "$minute minute(s) ago";
        }
    
        return "under 1 minute ago";	
    
    }
    
    foreach($testcase as $test) {
        echo "Time since $test is " . timeSince($test)."<br/>";
    }   
    
    ?>

Read the rest of this entry »

Category: Programmazione, Siti Web, tutorial | 1 Comment »