Info
Content

Funzioni utili PHP

Generare stringa base 62 (Veloce non sicuro)
<?php
function getRandomString($len) {
  $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
  $string = '';
  $max = strlen($characters) - 1;
  for ($i = 0; $i < $len; $i++) {
    $string .= $characters[mt_rand(0, $max)];
  }
  return $string;
}
?>
Generare stringa base 62 (Lento sicuro)
<?php
function getRandomString($len) {
  $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
  $string = '';
  $max = strlen($characters) - 1;
  for ($i = 0; $i < $len; $i++) {
    $string .= $characters[random_int(0, $max)];
  }
  return $string;
}
?>
Stringa esadecimale (veloce sicuro)

<?php
function getRandomString($len) {
  return bin2hex(random_bytes($len/2));
}
?>

 

Varie

rot13

<?php
$d str_rot13("Uryyb Jbeyq");
echo $d; // Hello World
?>

base64

<?php
$r = base64_encode($str);
$r = base64_decode($str); 
?>

JSON

<?php
//Oggetto
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);

//Array
$myArr = array("John", "Mary", "Peter", "Sally");
$myJSON = json_encode($myArr);

//JSON -> Array
json_decode($myArr, true);

//JSON -> Object
json_decode($myObj, false);
?>

AddSlash (Utile quando si genera qualcosa in JS)

<?php
$str = addslashes('<h1 onclick="action("titoloClick")">test</h1>');
?>

 

No Comments
Back to top