Caputo's blog

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

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 | No Comments »

Le espressioni regolari più utili in PHP

Maggio 9th, 2009 by Giovanni Caputo

Di seguito alcune espressioni regolari molto utili per chi programma in PHP. Naturalmente i controlli sono esclusivamente sintattici.

  1. Validare indirizzo email

    $email = "test@example.com";
    if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$email)) {
        echo "Your email is ok.";
    } else {
        echo "Wrong email address format";
    }

    Una soluzione migliore è usare filter_var.

    if (filter_var('test+email@fexample.com', FILTER_VALIDATE_EMAIL)) {
        echo "Your email is ok.";
    } else {
        echo "Wrong email address format.";
    }
  2. Validare usernames

    Validare username composti da caratteri alfanumerici (a-z, A-Z, 0-9), underscores, con minimo 5  e massimo 20 caratteri.

    $username = "user_name12";
    if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
        echo "Your username is ok.";
    } else {
        echo "Wrong username format.";
    }
  3. Validare numeri telefonici

    In questo caso numeri telefonici americani,  semplice da adattare per quelli di altre nazionalità.

    $phone = "(021)423-2323";
    if (preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x', $phone)) {
        echo "Your phone number is ok.";
    } else {
        echo "Wrong phone number.";
    }
  4. Validare indirizzi IP

    $IP = "198.168.1.78";
    if (preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)) {
        echo "Your IP address is ok.";
    } else {
        echo "Wrong IP address.";
    }
  5. Validare codici postali

    Anche in questo caso validati codici postali statunitensi.

    $zipcode = "12345-5434";
    if (preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zipcode)) {
        echo "Your Zip code is ok.";
    } else {
        echo "Wrong Zip code.";
    }
  6. Validare numeri di carta di credito

    $cc = "378282246310005";
    if (preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc)) {
        echo "Your credit card number is ok.";
    } else {
        echo "Wrong credit card number.";
    }
  7. Validare domini

    $url = "http://komunitasweb.com/";
    if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
        echo "Your url is ok.";
    } else {
        echo "Wrong url.";
    }
  8. Estrarre dominio da una certa URL

    echo $host;
    
    echo $text;
    $url = "http://komunitasweb.com/index.html";
    preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
    $host = $matches[1];

Read the rest of this entry »

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

Validatore sintattico di carte di credito

Maggio 7th, 2009 by Giovanni Caputo

Sastgroup fornisce codice PHP che permette di validare sintatticamente i numeri di carta di credito.

< ?

if( checkCreditCard (“40236007878787”, “Visa”, &$errornumber, &$errortext))
echo “OK”;
else echo”MO”;

function checkCreditCard ($cardnumber, $cardname, &$errornumber, &$errortext) {

$cards = array ( array (‘name’ => ‘American Express’,
‘length’ => ’15’,
‘prefixes’ => ‘34,37’,
‘checkdigit’ => true
),
array (‘name’ => ‘Carte Blanche’,
‘length’ => ’14’,
‘prefixes’ => ‘300,301,302,303,304,305,36,38’,
‘checkdigit’ => true
),
array (‘name’ => ‘Diners Club’,
‘length’ => ’14’,
‘prefixes’ => ‘300,301,302,303,304,305,36,38’,
‘checkdigit’ => true
),
array (‘name’ => ‘Discover’,
‘length’ => ’16’,
‘prefixes’ => ‘6011’,
‘checkdigit’ => true
),
array (‘name’ => ‘Enroute’,
‘length’ => ’15’,
‘prefixes’ => ‘2014,2149’,
‘checkdigit’ => true
),
array (‘name’ => ‘JCB’,
‘length’ => ‘15,16’,
‘prefixes’ => ‘3,1800,2131’,
‘checkdigit’ => true
),
array (‘name’ => ‘Maestro’,
‘length’ => ‘16,18’,
‘prefixes’ => ‘5020,6’,
‘checkdigit’ => true
),
array (‘name’ => ‘MasterCard’,
‘length’ => ’16’,
‘prefixes’ => ‘51,52,53,54,55’,
‘checkdigit’ => true
),
array (‘name’ => ‘Solo’,
‘length’ => ‘16,18,19’,
‘prefixes’ => ‘6334,6767’,
‘checkdigit’ => true
),
array (‘name’ => ‘Switch’,
‘length’ => ‘16,18,19’,
‘prefixes’ => ‘4903,4905,4911,4936,564182,633110,6333,6759’,
‘checkdigit’ => true
),
array (‘name’ => ‘Visa’,
‘length’ => ‘13,16’,
‘prefixes’ => ‘4’,
‘checkdigit’ => true
),
array (‘name’ => ‘Visa Electron’,
‘length’ => ’16’,
‘prefixes’ => ‘417500,4917,4913’,
‘checkdigit’ => true
)
);

$ccErrorNo = 0;

$ccErrors [0] = “Unknown card type”;
$ccErrors [1] = “No card number provided”;
$ccErrors [2] = “Credit card number has invalid format”;
$ccErrors [3] = “Credit card number is invalid”;
$ccErrors [4] = “Credit card number is wrong length”;

// Establish card type
$cardType = -1;
for ($i=0; $i

// See if it is this card (ignoring the case of the string)
if (strtolower($cardname) == strtolower($cards[$i][‘name’])) {
$cardType = $i;
break;
}
}

// If card type not found, report an error
if ($cardType == -1) {
$errornumber = 0;
$errortext = $ccErrors [$errornumber];
return false;
}

// Ensure that the user has provided a credit card number
if (strlen($cardnumber) == 0) {
$errornumber = 1;
$errortext = $ccErrors [$errornumber];
return false;
}

// Remove any spaces from the credit card number
$cardNo = str_replace (‘ ‘, ”, $cardnumber);

// Check that the number is numeric and of the right sort of length.
if (!eregi(‘^[0-9]{13,19}$’,$cardNo)) {
$errornumber = 2;
$errortext = $ccErrors [$errornumber];
return false;
}

// Now check the modulus 10 check digit – if required
if ($cards[$cardType][‘checkdigit’]) {
$checksum = 0; // running checksum total
$mychar = “”; // next char to process
$j = 1; // takes value of 1 or 2

// Process each digit one by one starting at the right
for ($i = strlen($cardNo) – 1; $i >= 0; $i–) {

// Extract the next digit and multiply by 1 or 2 on alternative digits.
$calc = $cardNo{$i} * $j;

// If the result is in two digits add 1 to the checksum total
if ($calc > 9) {
$checksum = $checksum + 1;
$calc = $calc – 10;
}

// Add the units element to the checksum total
$checksum = $checksum + $calc;

// Switch the value of j
if ($j ==1) {$j = 2;} else {$j = 1;};
}

// All done – if checksum is divisible by 10, it is a valid modulus 10.
// If not, report an error.
if ($checksum % 10 != 0) {
$errornumber = 3;
$errortext = $ccErrors [$errornumber];
return false;
}
}

// The following are the card-specific checks we undertake.

// Load an array with the valid prefixes for this card
$prefix = split(‘,’,$cards[$cardType][‘prefixes’]);

// Now see if any of them match what we have in the card number
$PrefixValid = false;
for ($i=0; $i
$exp = ‘^’ . $prefix[$i];
if (ereg($exp,$cardNo)) {
$PrefixValid = true;
break;
}
}

// If it isn’t a valid prefix there’s no point at looking at the length
if (!$PrefixValid) {
$errornumber = 3;
$errortext = $ccErrors [$errornumber];
return false;
}

// See if the length is valid for this card
$LengthValid = false;
$lengths = split(‘,’,$cards[$cardType][‘length’]);
for ($j=0; $j
if (strlen($cardNo) == $lengths[$j]) {
$LengthValid = true;
break;
}
}

// See if all is OK by seeing if the length was valid.
if (!$LengthValid) {
$errornumber = 4;
$errortext = $ccErrors [$errornumber];
return false;
};

// The credit card is in the required format.
return true;
}
?>

Read the rest of this entry »

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

Piattaforma WAMPP da cd o usb

Maggio 4th, 2009 by Giovanni Caputo

Server2Go è una soluzione WAMPP (Windows, Apache, MySQL, Php, Perl) che può girare da un drive rimovibile come un cd, dvd, penna usb o flash card.

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