Customize save uploaded file name - php

I use the following code to upload the file:
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $filename)){
echo $filename . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file. Please try again.";
}
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
I want to save the uploaded file with "1.jpg" name. If it already exists in the "upload" folder, save with "2.jpg", and if file "2.jpg" already exists in the "upload" folder, Wait until the another script clears one of them. If, after some time (about 120 seconds), none of the two files was erased, it will display an error message. What code should I use?

In PHP your code works while the request being processed. You cannot pause your script and wait until another request.
To realize your task you can store the file in a temporary location if file with name 1 or 2 exists and respond to the client. Then another script should process another request from client which contains information of client’s choice. This second script could delete old file and copy the new one to specified location.

Related

How to put the name of the file in advance when uploading?

I want to save the uploaded file with 1.jpg name. If it already exists in the "upload" folder, save with 2.jpg,
if file 2.jpg already exists in the "upload" folder, Wait until the another script clears one of them. If, after some time (about 120 seconds), none of the two files was erased, it will display an error message. What code should I use?
My code is:
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $filename)){
echo $filename . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file. Please try again.";
}
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
First, ensure that PHP is configured to allow file uploads.In php.ini file, search for the file_uploads directive, and set it to On. Then update your code as follows.
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["photo"]["tmp_name"]);
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
file_rename();//call for your other script
}
else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
echo "Your file was uploaded successfully.";
}

Uploading Error in docx file but able to upload pdf in same code

Am tried to upload docx file format and xlsx it not moving file to location it throwing error.
here the code for uploading
/* Upload Pdf */
if(isset($_FILES["file"]) && $_FILES["file"]["error"] == 0){
$allowed = array('pdf' => "application/pdf",'doc' => "application/msword",'docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$filename = $_FILES["file"]["name"];
$filetype = $_FILES["file"]["type"];
$filesize = $_FILES["file"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than 5MB the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("../../upload/courses/pdf/" . $_FILES["file"]["name"])){
unlink("../../upload/courses/pdf/" . $_FILES["file"]["name"]);
$tmph = $_FILES["file"]["tmp_name"];
$pathh = "../../upload/courses/pdf/" . $_FILES["file"]["name"];
move_uploaded_file($tmph,$pathh );
} else{
$tmph = $_FILES["file"]["tmp_name"];
$pathh = "../../upload/courses/pdf/" . $_FILES["file"]["name"];
move_uploaded_file($tmph,$pathh );
//echo "Your file was uploaded successfully.";
}
} else{ echo "Error: There was a problem uploading your file. Please try again."; }
}
$filepath =substr("../../upload/courses/pdf/" . $_FILES["file"]["name"],3);
if($_FILES["file"]["size"] == 0 && $_FILES["file"]["error"] == 4){
$file ='';
}
else{
$file = ",file='".$filepath."'";
}
Error in the link move_uploaded_file() part
By using same file code am able to upload pdf file but cause error in docx and xlsx file format.
On above part i checked MIME with printing filetype, it got me the file mimetype i need to use.
So i changed
$allowed = array('pdf' => "application/pdf",'doc' => "application/msword",'docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
To
$allowed = array('pdf' => "application/pdf",'doc' => "application/msword",'docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document','docx'=>'application/octet-stream');
On my case it worked with this match 'docx'=>'application/octet-stream', in-case error mean try to check $_FILES["file"]["type"]; by echo or print it.

PHP upload a file to selected subdirectory

I have a form that will upload to the directory it is in, but I need it to upload to subdirectories or subdirectories of subdirectories from a select. But unsure how to use the select info.
My folder structure is 4 layers of folders
Produce
Produce/Meat
Produce/Meat/Beef
Produce/Meat/Beef/Portions
Produce/Meat/Beef/Packaged
Produce/Vegtables
Produce/Vegetables/Fresh
Produce/Vegetables/Fresh/Local etc,.
This is my form
<form id="Upload" action="upload_file.php" method="post" enctype="multipart/form-data">
<br>
<label for="fileSelect"><strong>There is a 10MB limit Filesize limit.</strong> Allowed file types are pictures, MSWord, MSExcel, PDF, and plain text. Navigate and choose:</label>
<input type="file" name="file" id="fileSelect"><br><br>
Upload to:
<select name="folder"><option value="this" selected>This folder</option><option value="BBB">Meat</option><option value="CCC">Meat/Beef</option><option value="DDD">Meat/Beef/Portions</option><option value="EEE">Meat/Beef/Packaged</option><option value="FFF">Vegetables</option><option value="GGG">Vegetables/Fresh</option><option value="HHH">Vegetables/Fresh/Local</option><option value="III">Vegetables/Fresh/Packaged</option></select>
<input class="button" type="submit" name="action" value="Upload to Shared Folder"><br><br>
</form>
Then the upload_file.php has this PHP code
<?php
if(isset($_FILES["file"]["error"])){
if($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png", "doc" => "application/msword", "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "xls" => "application/vnd.ms-excel", "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "pdf" => "application/pdf", "txt" => "text/plain");
$filename = $_FILES["file"]["name"];
$filetype = $_FILES["file"]["type"];
$filesize = $_FILES["file"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: This file is not an accepted file type.</br></br>");
// Verify file size - 10MB maximum
$maxsize = 200000 * 60;
if($filesize > $maxsize) die("Error: File size is larger than the allowed 10MB limit.</br></br>");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("general/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. Go back and choose another file or rename the original.</br></br>";
} else{
move_uploaded_file($_FILES["file"]["tmp_name"], "" . $_FILES["file"]["name"]);
echo "The file was uploaded successfully.</br></br>";
}
}
else{
echo "Error: There was a problem uploading the file - please try again.";
}
}
} else{
echo "Error: Invalid parameters - something is very wrong with this upload.";
}
?>
Is there a way I can take the select value and upload to the subdirectory selected?
There are plenty of ways to do this, so here's one way:
Check to see if the POST array is set (for the dropdown select), then inside check to see if it is equal to a value from the options, then move your file inside the chosen folder:
if(isset($_POST['folder'])){
if($_POST['folder'] == 'this'){
// move_uploaded_file to said folder
}
if($_POST['folder'] == 'BBB'){
// move_uploaded_file to said folder
}
// ... do the same for the others below
}
you can also set a default upload folder.
Edit:
Note: Look for my original snippet inside // My snippet START --- // My snippet END.
<?php
if(isset($_FILES["file"]["error"])){
if($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png", "doc" => "application/msword", "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "xls" => "application/vnd.ms-excel", "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "pdf" => "application/pdf", "txt" => "text/plain");
$filename = $_FILES["file"]["name"];
$filetype = $_FILES["file"]["type"];
$filesize = $_FILES["file"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: This file is not an accepted file type.</br></br>");
// Verify file size - 10MB maximum
$maxsize = 200000 * 60;
if($filesize > $maxsize) die("Error: File size is larger than the allowed 10MB limit.</br></br>");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("general/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. Go back and choose another file or rename the original.</br></br>";
} else{
// My snippet START
if(isset($_POST['folder'])){
if($_POST['folder'] == 'this'){
// move_uploaded_file to said folder
$uploaddir = '/var/www/uploads/Produce/';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
echo "The file was uploaded successfully.</br></br>";
}
if($_POST['folder'] == 'BBB'){
// move_uploaded_file to said folder
$uploaddir = '/var/www/uploads/Produce/Meat/';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
echo "The file was uploaded successfully.</br></br>";
}
// ... do the same for the others below
}
// My snippet END
}
}
else{
echo "Error: There was a problem uploading the file - please try again.";
}
}
} else{
echo "Error: Invalid parameters - something is very wrong with this upload.";
}
?>

How to make auto updating image gallery?

Well I have a upload script. What I need is how would I go about making it auto upload to a page on my site where it can be displayed as an image gallery?
Code:
<?php
// Configuration - Your Options
$allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); // These will be the types of file that will pass the validation.
$max_filesize = 1000000; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './images/uploaded_images/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if ( ! in_array($ext, $allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if ( ! is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if (move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
?>
Any Ideas?
One approach would be to scan the directory you are storing the images and write html for each file you encounter. Take a look at the scandir function. Some rudimentary code to get you started:
$upload_path = './images/uploaded_images/';
$files = scandir($upload_path);
foreach($files as $filename) {
if(is_image($filename)) {
echo "<div class='gallery-image'><img src='{$filename}'/></div>";
}
}
function is_image($filename) {
$image_extensions = array('jpg', 'jpeg', 'png', 'gif');
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
return in_array($ext, $image_extensions);
}

How to Rename Image File on Upload Using this Script

Please could someone show me where i need to change the code so that the image uploaded is renamed to "freddy" for e.g.
But still carries the correct existing extension i.e jpg, png, gif.
Thanks In Advance
<?php
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 1024 * 50);
if (array_key_exists('upload', $_POST)) {
// define constant for upload folder
define('UPLOAD_DIR', '/home/richard/public_html/testing/editable-images/');
// replace any spaces in original filename with underscores
$file = str_replace(' ', '_', $_FILES['image']['name']);
// create an array of permitted MIME types
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg',
'image/png');
// upload if file is OK
if (in_array($_FILES['image']['type'], $permitted)
&& $_FILES['image']['size'] > 0
&& $_FILES['image']['size'] <= MAX_FILE_SIZE) {
switch($_FILES['image']['error']) {
case 0:
// check if a file of the same name has been uploaded
// Uncomment to stop overwritten files >>>> if (!file_exists(UPLOAD_DIR . $file)) {
// move the file to the upload folder and rename it
$success =
move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR .
$file);
// Uncomment to stop overwritten files >>>> } else {
// Uncomment to stop overwritten files >>>> $result = 'A file of the same name already exists.';
// Uncomment to stop overwritten files >>>>> }
if ($success) {
$result = "$file uploaded successfully.";
} else {
$result = "Error uploading $file. Please try again.";
}
break;
case 3:
case 6:
case 7:
case 8:
$result = "Error uploading $file. Please try again.";
break;
case 4:
$result = "You didn't select a file to be uploaded.";
}
} else {
$result = "$file is either too big or not an image.";
}
}
?>
// get file extension
$ext = end(explode($_FILES['image']['name']));
// name your file and preserve file extension
$file = "freddy.".$ext;
// create an array of permitted MIME types
....
Check description of method move_uploaded_file here

Resources