Skip to main content

Make Random Number

Nov 19, 2022CodeCatch
Loading...

More PHP Posts

Get File Extension

Nov 19, 2022CodeCatch

0 likes • 2 views

<?php
function getFileExtension($file) {
return end(explode(".", $file));
}
?>

preg_match() username sanitization

Nov 18, 2022AustinLeath

0 likes • 0 views

<?php
$username = "Austin Leath -_#";
$username_err = "no error";
if(preg_match('/[^a-z_\-0-9]/i', $string)) {
$username_err = "Username can only contain alphanumeric characters, dashes, and underscores.";
}
echo $username_err
?>

Access Associative Array

Nov 18, 2022AustinLeath

0 likes • 1 view

<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array), "\n";
}
next($array);
}
?>

List Files in Directory

Nov 18, 2022AustinLeath

0 likes • 1 view

<?php
$listOfFiles = glob("*.{jpg,png,gif,tiff,jpeg}", GLOB_BRACE);
echo 'images = []; ';
for($x = 0; $x <= count($listOfFiles)-1; $x++) {
echo "images[" . $x . "] =" . '"' . $listOfFiles[$x] . '"' . "; ";
}
?>

ID Generator

Nov 18, 2022AustinLeath

0 likes • 0 views

<?php
function uniqidReal($length = 8) {
// uniqid gives 8 chars, can be changed
if (function_exists("random_bytes")) {
$bytes = random_bytes(ceil($length / 2));
} elseif (function_exists("openssl_random_pseudo_bytes")) {
$bytes = openssl_random_pseudo_bytes(ceil($length / 2));
} else {
throw new Exception("no cryptographically secure random function available");
}
return substr(bin2hex($bytes), 0, $length);
}
/*
//for testing
for($i = 0; $i < 10; $i++) {
echo "<br>";
echo uniqidReal();
}
*/
?>

Crop an image

Nov 19, 2022CodeCatch

0 likes • 0 views

<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
imagepng($im2, 'example-cropped.png');
imagedestroy($im2);
}
imagedestroy($im);
?>