PHP auto-growth file names

I have a file downloader and I want the file names to increment automatically. I don’t feel the need to use a database for this, and I want the code to be relatively clean, I’m pretty new to downloading and managing files in PHP, so I'm not quite sure what to do. Can someone direct me on the right path?

Here is my current code, it just uses md5 from a seed heap.

<?php
if(isset($_FILES['imagedata']['tmp_name']))
{
// Directory related to the location of your gyazo script
    $newName = 'images/' . substr(md5(rand() . time()), 0, 20) . '.png';
    $tf = fopen($newName, 'w');
    fclose($tf);
    move_uploaded_file($_FILES['imagedata']['tmp_name'], $newName);
// Website
    echo 'http://davidknag.com/' . $newName;
}
?>
+3
source share
5 answers
function enc($length = "string") {
if(!is_numeric($length) || $length > 255 || $length < 1){
$length = rand("3","6");
}

  //  $randomID = substr(uniqid(sha1(crypt(md5("".time("ysia", true)."".rand())))), 0, $length);
    $randomID = genUnique($length);
    $count = 0;
while(glob("$randomID.*") || fetch("select * from `short` where `short` = '$randomID'") || fetch("select * from `images` where `name` = '$randomID'") || glob("img/$randomID.*") || is_numeric($randomID)){
        if($count > 20){
        $length++;
        }
    $randomID = genUnique($length);
    $count++;
    }
    return $randomID;
}

this code is pretty old (not even using mysqli), but I thought I'd turn it on first

<?php
include_once "functions.php";
if(!isset($_REQUEST['api'])){
notfound("");
}
$con = connect();
$key = $_REQUEST['api'];
$ver = $_REQUEST['version'];
if($ver != "10-26-2016" || $key == "zoidberg")
{
  die("Please upgrade your in4.us.exe by logging in and clicking download.");
}
if($key == "nokey"){
  die("You need to keep the exe with the ini file to pair your api key. Copy ini file to same directory or redownload.");
}
$key = mysql_real_escape_string($key);
$findkey = fetch(" SELECT * from `users` where `key` = '$key' ");
if(!is_array($findkey)){
die("No user with that API Key found. Configure the INI File using your api key on in4.us");
}
$user = $findkey['username'];
    if(isset($_FILES['imagedata']['tmp_name'])){
        $newName =  enc();
    $tf = fopen("img/".$newName.".png", 'w');
    fclose($tf);
    move_uploaded_file($_FILES['imagedata']['tmp_name'], "img/".$newName.".png");
        $domain = $_SERVER['HTTP_HOST'];
    date_default_timezone_set('America/New_York');
    $mysqldate = date("Y-m-d H:i:s");
    $qry = mysql_query("INSERT INTO `images` (`name`, `added`, `dateadded`) VALUES ('$newName', '$user', '$mysqldate');");
    if(!qry){
          die('Invalid query: ' . mysql_error());
    }
    echo "http://$domain/$newName.png";

    disconnect($con);
}else{
notfound("");
}
?>
0
source
<?php
if(isset($_FILES['imagedata']['tmp_name'])) {
    // Directory related to the location of your gyazo script
    $fileCount = count (glob ('images/*.png'));
    $newName = 'images/' . ( $fileCount + 1) . '.png';
    $tf = fopen($newName, 'w');
    fclose($tf);
    move_uploaded_file($_FILES['imagedata']['tmp_name'], $newName);
    // Website
    echo 'http://davidknag.com/' . $newName;
}

It simply counts all the .png files in the directory, increments this number by 1, and uses it as its file name.

, (, 10.000 ), , jus tfine.

+4

. . .

​​, getNextNumber(), , . $_SERVER [], .

<?PHP
// a basic example
function getNextNumber() {
    $count = (int)file_get_contents('yourFile.txt');
    $count+=1;
    file_put_contents('yourFile.txt',$count);
    return $count;
}

?>

, , , 2 - .

+2

. .png outdir/

$filename = uniqFile('outdir', '.png');
move_uploaded_file($_FILES['imagedata']['tmp_name'], $filename);


function uniqFile($dir, $ext)
{
    if (substr($dir, -1, 1) != '/')
    {
        $dir .= '/';
    }

    for ($i=1; $i<999999; $i++)
    {
        if (!is_file($dir . $i . $ext))
        {
            return $i . $ext;
        }
    }
    return false;
}
+1

A bit late in the game, but this pair of functions does its job and follows the familiar file name format, followed by "(n)", and then the file extension:

incrementFileName () returns the updated file name increased by 1 with the input file name and destination directory. splitLast () is a diversity modification to split only the last occurrence of some substring.

function incrementFileName($name,$path){
    if (!array_search($name,scandir($path))) {
        return $name;
    } else {
        $ext=splitLast($name,".")[1];
        $baseFileName=splitLast(splitLast($name,".")[0],"(")[0];
        $num=intval(splitLast(splitLast($name,"(")[1],")")[0])+1;
        return incrementFileName($baseFileName."(".$num.").".$ext,$path);
    }
}

function splitLast($string,$delim) {
    $parts = explode($delim, $string);
    if (!$parts || count($parts) === 1) {
        $before=$string;
        $after="";
    } else {
        $after = array_pop($parts);
        $before=implode($delim, $parts);
    }
    return array($before,$after);
}

When processing the download, specify the file name:

$fileName = incrementFileName($_FILES['file']['name'], $path);

This will return someFileName (1) .jpg or someFileName (2) .jpg, etc.

0
source

All Articles