Skip to content

Instantly share code, notes, and snippets.

@nektro
Last active January 11, 2019 09:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nektro/0a30ff6817d2c026d63b to your computer and use it in GitHub Desktop.
Save nektro/0a30ff6817d2c026d63b to your computer and use it in GitHub Desktop.
<?php
/**
* A little php script to accept images and make folders based on the hash,
* with a bonus _ folder at the end to detect if collisions occur.
*
* For example, using a form on this page would convert the following image
* https://dev.nektro.net/assets/nektro.png
* http://localhost/imgh/cdn/89/9e/84/39/49/12/16/7a/06/c7/b1/ae/c5/18/e5/3b/d7/8e/b6/a5/eb/7d/29/9e/cf/fa/ec/63/51/d8/19/1b/_0/c.png
*/
$home_dir = '/imgh/';
function getDup($h,$i) {
$d = $h . '/_' . $i . '/';
return !is_dir($d) ? $d : getDup($h, $i+1);
}
// there's a utf face at the end
header("Content-type: text/html; charset=UTF-8");
// make sure the form was sent
if (isset($_FILES['img'])) {
$file = $_FILES['img'];
var_dump($file['name']);
switch ($file['type']) {
case 'image/png':
case 'image/jpeg':
case 'image/gif':
$fgc = file_get_contents($file['tmp_name']);
$hash = hash('sha256', $fgc);
// cdn/ is the content folder, not part of hash
$dir = "cdn/" . implode('/', str_split($hash, 2));
$dirf = getDup($dir, 0);
$name = 'c.' . array( 'image/png'=>'png', 'image/jpeg'=>'jpg', 'image/gif'=>'gif' )[$file['type']];
$path = $dirf . $name;
$d = intval(substr(array_reverse(explode('/', $dirf))[1], 1));
// if _x > 0, check for duplicate images and return link
// ie, has this exact image been uploaded before?
if ($d > 0) {
for ($i = 0; $i < $d; $i++) {
$tf = $dir.'/_'.$i.'/'.scandir($dir.'/_'.$i)[2];
if (file_get_contents($tf) == $fgc) {
var_dump($i);
// copy found, show them the link
echo "<a href='" . $tf . "' target='_blank'>Get your image here.</a><br>";
echo "<a href='$home_dir'>Return</a>";
die();
}
}
// you found a collision in sha-2
}
var_dump($d);
mkdir($dirf, 0777, true);
file_put_contents($path, $fgc);
// new file, give them a link
echo "<a href='" . $path . "' target='_blank'>Upload successful.</a><br>";
echo "<a href='$home_dir'>Return</a>";
break;
default:
echo "<span style='color:red'>Unavailable file type (╯︵╰,)</span><br><a href='$home_dir'>Return</a>";
}
}
else {
echo "<span style='color:red'>Unknown error, cannot find image (╯︵╰,)</span><br><a href='$home_dir'>Return</a>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment