I am trying to have a file name generated randomly from specific ranges but be unique. I used w3schools to make the upload code and tried modifying it to change it to the generated filename but it fails to upload each time with this error
Notice: Undefined variable: tiledir in /home/rngsites/public_html/b/upload.php on line 67
Warning: move_uploaded_file(): Filename cannot be empty in /home/rngsites/public_html/b/upload.php on line 67
Warning: move_uploaded_file(): Unable to move '/tmp/phpGVMrRA' to '' in /home/rngsites/public_html/b/upload.php on line 67 Sorry, there was an error uploading your file. I assumed that running the function at the beginning of the document would define the variable by the time upload function is run.
HTML:
<html>
<body>
<form class='form' action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
PHP (updated):
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
tile();
function tile(){
$z = rand(1,3);
if ($z === 1) {
$x = rand(0,1);
$y = rand(0,1);
} elseif ($z === 2) {
$x = rand(0,3);
$y = rand(0,3);
} elseif ($z === 3) {
$x = rand(0,15);
$y = rand(0,15);
}
$tile = $z.'-'.$x.'-'.$y.'.png';
$tiledir = 'tiles/'.$tile;
if (file_exists($tiledir)) {
tile();
} else {
upload();
}
}
function upload(){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "png" ) {
echo "Sorry, only PNG files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $tiledir)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
I tried this solution earlier and it didn't quite help.
I remember being able to this exact thing several years ago on a different site and it worked. I don't understand what I missed this time around.