Codice PHP pezzi di codice vario

In questo articolo pubblico vari pezzi utili di codice PHP, nell’ augurio che vi tornino utili.

AGGIUNGERE LO SLASH FINALE AL PERCORSO DI UN FILE
function add_ending_slash($path){
$slash_type = (strpos($path, ‘\\’)===0) ? ‘win’ : ‘unix’;
$last_char = substr($path, strlen($path)-1, 1);
if ($last_char != ‘/’ and $last_char != ‘\\’) {
$path .= ($slash_type == ‘win’) ? ‘\\’ : ‘/’;
}
return $path;
}
CONTROLLARE SE LA STRINGA TERMINA PER IL TESTO INDICATO
function EndsWith($Haystack, $Needle){
// VERSIONE RACCOMANDATE, UTILIZZANDO STRPOS
return strrpos($Haystack, $Needle) === strlen($Haystack)-strlen($Needle);
}
// VERSIONE ALTERNATIVA, CON SUBSTR
function EndsWith_Old($Haystack, $Needle){
return substr($Haystack, strlen($Needle)*-1) == $Needle;
}
DOWNLOAD FILE CON LIMITE DI VELOCITA
// nome del file locale che deve essere inviato al client
$local_file = ‘test-file.zip’;
// nome del file restituito all’utente che esegue il download
$download_file = ‘your-download-name.zip’;
// limite di velocità del download (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file)) {
// invio degli headers
header(‘Cache-control: private’);
header(‘Content-Type: application/octet-stream’);
header(‘Content-Length: ‘.filesize($local_file));
header(‘Content-Disposition: filename=’.$download_file);
// esegue un aggiornamento del contenuto
flush();
// apre lo stream del file
$file = fopen($local_file, “r”);
while(!feof($file)) {
// invio delle prima parte del file al browser
print fread($file, round($download_rate * 1024));
// aggiorna il contenuto del browser
flush();
// dormicchia un secondo
sleep(1);
}
// chiude lo stream del file
fclose($file);}
else {
die(‘ERRORE: IL FILE ‘.$local_file.’ NON ESISTE!’);
}
ESTRARRE GLI INDIRIZZI EMAIL DA UNA STRINGA O DA UN FILE
function extract_emails($str){
// questa espressione regolare estrae tutte le email da una stringa
$regexp = ‘/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i’;
preg_match_all($regexp, $str, $m);
return isset($m[0]) ? $m[0] : array();
}
$test_string = ‘Questa è una stringa di testo…
[email protected]
Test in formati differenti:
[email protected];
<a href=”[email protected]”>foobar</a>
<[email protected]>
formati strani:
[email protected]
test6[at]example.org
[email protected]
test8@ example.org
test9@!foo!.org
‘;
print_r(extract_emails($test_string));
/*
Il risultato è il seguente ARRAY:
Array
(
[0] => [email protected]
[1] => [email protected]
[2] => [email protected]
[3] => [email protected]
[4] => [email protected]
[5] => [email protected]
)
*/
GENERARE UNA PASSWORD CASUALE
function random_password($length, $characters=’abcdefgh1234567890′){
if ($characters == ”){ return ”; }
$chars_length = strlen($characters)-1;
mt_srand((double)microtime()*1000000);
$pwd = ”;
while(strlen($pwd) < $length){
$rand_char = mt_rand(0, $chars_length);
$pwd .= $characters[$rand_char];
}
return $pwd;
}
RANDOMIZZARE IL CONTENUTO DI UN ARRAY
// prima controllo se è un array
$array = (!is_array($array)) ? array($array) : $array;
$a = array();
$max = count($array) + 10;
while(count($array) > 0){
$e = array_shift($array);
$r = rand(0, $max);
// find a empty key:
while (isset($a[$r])){
$r = rand(0, $max);
}
$a[$r] = $e;
}
ksort($a);
$a = array_values($a);
return $a;
}
REDIRECT SICURO
function SecureRedirect($url, $exit=true) {
// controllo se gli headers sono già stati inviati
if (!headers_sent()){
header(‘HTTP/1.1 301 Moved Permanently’);
header(‘Location: ‘ . $url);
}
// Se il redirect sopra funziona, l’utente non vedrà mai questa pagina
print ‘<html>’;
print ‘<head><title>Sto cambiando pagina…</title>’;
print ‘<meta http-equiv=”Refresh” content=”0;url=’.$url.'” />’;
print ‘</head>’;
print ‘<body onload=”location.replace(\”.$url.’\’)”>’;
// se l’istruzione location, il javascript e
// il meta redirect non funzionano ancora,
// l’utente potrà sempre utilizzare il seguente link:
print ‘Stai per essere re-indirizzato verso questa URL:<br/>’;
print ‘<a href=”‘.$url.'”>’.$url.'</a><br/><br/>’;
print ‘Se il redirect non funzione, per favire clicca sul seguente link.<br/>’;
print ‘</body>’;
print ‘</html>’;
// forza la fine dello script
if ($exit){
exit;
}
}