Tomas Berger Tomas Berger - 6 months ago 32
PHP Question

Php custom name to files

How can I make a custom name to the pictures they/I upload, preferably I want them to get numbers as names, and the next picture get the number of the last name +1.

<?php
$target_dir = "../image/DBFilmCover/";

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);

// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
} else {

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>


I appreciate all the help I can get, if I didn't give enough information, just ask

Answer

Yes you can. Just change target_file according to your need:

E.g:

$target_file = $target_dir . "custom name";

For counting number of files in your directory simply do:

$files = scandir($target_dir);
$files_count = count($files)-2; // -2 for ignoring . and ..

Now filename would be:

$path = $_FILES['fileToUpload']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$files_count++;
$filename = $files_count.".".$ext;
$target_file = $target_dir . $filename;
Comments