I'm trying to upload a file and rename it if it already exists.
The way I want i to do is that when det same file uploads the name just adds 1, then 2, then 3, and so on.
Example: If file "file" exists, the new file should be "file1", then the next one "file2".
I've seen some examples on the net, but nothing that I could see fit to my code (noob)
This is my code now:
$id = $_SESSION['id'];
$fname = $_FILES['dok']['name'];
if ($_FILES['dok']['name'] !=""){
// Checking filetype
if($_FILES['dok']['type']!="application/pdf") {die("You can only upload PDF files");}
// Checking filesize
if ($_FILES['dok']['size']>1048576) {die("The file is too big. Max size is 1MB");}
// Check if user have his own catalogue
if (file_exists("filer/".$id."/")) {
// Moving the file to users catalogue
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);}
//If user don't have his own catalogue
else {
// Creates new catalogue then move the file in place
mkdir("filer/".$id);
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname); } }
Can somebody help me where I can put in code that solves this problem?
Big thank you!
$id = $_SESSION['id'];
$fname = $_FILES['dok']['name'];
if ($_FILES['dok']['name'] !=""){
// Checking filetype
if($_FILES['dok']['type']!="application/pdf") {
die("You can only upload PDF files");
}
// Checking filesize
if ($_FILES['dok']['size']>1048576) {
die("The file is too big. Max size is 1MB");
}
if(!is_dir("filer/".$id."/")) {
mkdir("filer/".$id);
}
$rawBaseName = pathinfo($fname, PATHINFO_FILENAME );
$extension = pathinfo($fname, PATHINFO_EXTENSION );
$counter = 0;
while(file_exists("filer/".$id."/".$fname)) {
$fname = $rawBaseName . $counter . '.' . $extension;
$counter++;
};
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);
}
But don't forget to secure your script (eg see comment of Marc B above) and maybe you could optimize some more ;-)
so if folder exists:
file_exists("filer/".$id."/")
check if file exists
file_exists("filer/".$id."/".$fname)
and then if it does,
$fname = $fname . "(1)" // or some appending string
So in the end you change your code to:
// Check if user have his own catalogue
if (file_exists("filer/".$id."/")) {
while (file_exists("filer/".$id."/".$fname)) // Now a while loop
$fname = "copy-" . $fname; // Prepending "copy-" to avoid breaking extensions
// Moving the file to users catalogue
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);}
//If user don't have his own catalogue
else {
<form action="test.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
<?php
$id = $_SESSION['id'];
$fname = $_FILES['fileToUpload']['name'];
// Checking filesize
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/".$id."/".$fname)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}else {
echo "Sorry, there was an error uploading your file.";
}
// Check file size$
if ($_FILES['fileToUpload']['size']>1048576) {
die("The file is too big. Max size is 1MB");
}
if(!is_dir("uploads/".$id."/")) {
mkdir("uploads/".$id);
}
$rawBaseName = pathinfo($fname, PATHINFO_FILENAME );
$extension = pathinfo($fname, PATHINFO_EXTENSION );
$counter = 0;
while(file_exists("uploads/".$id."/".$fname)) {
$fname = $rawBaseName . $counter . '.' . $extension;
$counter++;
};
move_uploaded_file($_FILES['fileToUpload'] ['tmp_name'],"uploads/".$id."/".$fname);
?>
Related
This question already has an answer here:
How to upload multiple image with rename in php mysql?
(1 answer)
Closed 1 year ago.
I wanted to upload multiple pictures at once using PHP but I am new to PHP so I don't understand how to do it. I want to upload a lot of pictures for one model. Like the picture below:
Here is my PHP code:
<?php
include_once('inc/header.php');
if (isset($_REQUEST['add'])) {
try {
$name = $_REQUEST['name'];
$category = $_REQUEST['category'];
$age = $_REQUEST['txt_age'];
$height = $_REQUEST['height'];
$haircolor = $_REQUEST['haircolor'];
$eyecolor = $_REQUEST['eyecolor'];
$bust = $_REQUEST['bust'];
$waist = $_REQUEST['waist'];
$about = $_REQUEST['about'];
$image_file = $_FILES["image"]["name"];
$type = $_FILES["image"]["type"]; //file name "txt_file"
$size = $_FILES["image"]["size"];
$temp = $_FILES["image"]["tmp_name"];
$path="../img/model_images/".$image_file; //set upload folder path
if (empty($name)) {
$errorMsg="Please Enter Name";
} elseif (empty($image_file)) {
$errorMsg="Please Select Image";
} elseif ($type=="image/jpg" || $type=='image/jpeg' || $type=='image/png' || $type=='image/gif') { //check file extension
if (!file_exists($path)) { //check file not exist in your upload folder path
if ($size < 5000000) { //check file size 5MB
move_uploaded_file($temp, "../img/model_images/" .$image_file); //move upload file temperory directory to your upload folder
} else {
$errorMsg="Your File To large Please Upload 5MB Size"; //error message file size not large than 5MB
}
} else {
$errorMsg="File Already Exists...Check Upload Folder"; //error message file not exists your upload folder path
}
} else {
$errorMsg="Upload JPG , JPEG , PNG & GIF File Formate.....CHECK FILE EXTENSION"; //error message file extension
}
if (!isset($errorMsg)) {
$insert_stmt=$connect->prepare('INSERT INTO tbl_model(model_name,model_category,model_image,model_age,model_height,model_haircolor,model_eyecolor,model_bust,model_waist,model_description) VALUES(:name,:category,:image,:txt_age,:height,:haircolor,:eyecolor,:bust,:waist,:about)'); //sql insert query
$insert_stmt->bindParam(':name', $name);
$insert_stmt->bindParam(':category', $category);
$insert_stmt->bindParam(':image', $image_file);
$insert_stmt->bindParam(':txt_age', $age);
$insert_stmt->bindParam(':height', $height);
$insert_stmt->bindParam(':haircolor', $haircolor);
$insert_stmt->bindParam(':eyecolor', $eyecolor);
$insert_stmt->bindParam(':bust', $bust);
$insert_stmt->bindParam(':waist', $waist);
$insert_stmt->bindParam(':about', $about);
if ($insert_stmt->execute()) {
echo $insertMsg="Model Added Successfully!"; //execute query success message
}
} else {
echo $errorMsg;
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
?>
But with this code I can only upload one picture but I want to upload many pictures.
This is my html code
<div class="form-group col-12">
<label for="slideImages" class="col-form-label">Model Image</label>
<input type="file" name="image" class="dropify" multiple>
</div>
In html you miss '[]' after name as you have to send array when you upload images and also make sure you write enctype in form tag as shown below
The form tag must contain the following attributes.
method="post"
enctype="multipart/form-data"
The input tag must contain type="file[]" and multiple attributes.
<form action="/action_page_binary.asp" method="post" enctype="multipart/form-data">
<div class="form-group col-12">
<label for="slideImages" class="col-form-label">Model Image</label>
<input type="file" name="image[]" class="dropify" multiple>
</div>
</form>
after this just you have to write for loop or foreach loop in php file as shown below in your code you use single column to store multiple image so apply this loop after you $about
if (isset($_REQUEST['add'])) {
try {
$name = $_REQUEST['name'];
$category = $_REQUEST['category'];
$age = $_REQUEST['txt_age'];
$height = $_REQUEST['height'];
$haircolor = $_REQUEST['haircolor'];
$eyecolor = $_REQUEST['eyecolor'];
$bust = $_REQUEST['bust'];
$waist = $_REQUEST['waist'];
$about = $_REQUEST['about'];
//$path="../img/model_images/".$image_file; //set upload folder path
$path = '';
if (empty($name)) {
$errorMsg="Please Enter Name";
exit;
}
foreach($_FILES["image"]["name"] as $key => $value){
$image_file = implode(',', $_FILES["image"]["name"]);
$image_name = $_FILES["image"]["name"][$key];
$type = $_FILES["image"]["type"][$key]; //file name "txt_file"
$size = $_FILES["image"]["size"][$key];
$temp = $_FILES["image"]["tmp_name"][$key];
if (empty($image_file)) {
$errorMsg="Please Select Image";
exit;
} else if (
($type=="image/jpg" ||
$type=='image/jpeg' ||
$type=='image/png' ||
$type=='image/gif')
) { //check file extension
if (!file_exists($path)) { //check file not exist in your upload folder path
if ($size < 5000000) { //check file size 5MB
move_uploaded_file($temp, "images/" .$image_name); //move upload file temperory directory to your upload folder
} else {
$errorMsg="Your File To large Please Upload 5MB Size"; //error message file size not large than 5MB
exit;
}
} else {
$errorMsg="File Already Exists...Check Upload Folder"; //error message file not exists your upload folder path
exit;
}
} else {
$errorMsg="Upload JPG , JPEG , PNG & GIF File Formate.....CHECK FILE EXTENSION"; //error message file extension
exit;
}
}
echo $name.$category.$age.$height.$haircolor.$eyecolor.$bust.$waist.$about.$image_file;
exit;
after this just bind above $image_file in your query
when you want to fetch display image use explode
$explode_images = explode(",", $images_file);
its gives you array then use foreach loop and key to access image name url or whatever you store in that column.
Hope this help .
if you need explanation of implode and explode check this out Implode Explode
Sorry I know there's a lot of posts about that but I can't find a solution in those.
Here's my form :
<form id="form1" action="upload.php" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Name : </td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td>Image :</td>
<td><input type="file" name="image"/></td>
</tr>
<tr><td id='submitAdd' colspan='2'><input type="submit"
value= " Add " /></td></tr>
</table>
</form>
And here upload.php :
<?php
$ext = strtolower(substr(strrchr($_FILES['image']['name'], '.'),1));
$ret = move_uploaded_file($_FILES['image']['tmp_name'], 'item_images/'.$_POST['name'].'.'.$ext);
if ($ret) {
echo 'works';
}
else {
echo 'doesnt work'."</br>";
echo $_FILES['image']['error'];
}
?>
The directory's permission are ok, no uploading error, but still it won't move the file.
Am I missing something ?
Thanks in advance
I think you need to be specifying the absolute save path rather than the relative path it looks like you have now.
Ex. dirname(__FILE__).'/item_images/'.$_POST['name'].'.'.$ext
I would move the file under the uploaded file name, and then rename it. Also, some file type checking and security should be added to this.. Sanitize the post ect.. Here is how I would do it.
upload.php
<?php
$fileName = $_FILES["image"]["name"]; // The file name
$fileTmpLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$fname = $kaboom[0];
$exten = strtolower($fileExt);
//now we do some security checks
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than xxx Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
//give it the new name
$userstring= $_POST['name'];
$string = $fname.$userstring.'.'.$exten;
$image_name = preg_replace('/\s+/', '', $string);
//now we move it.
$moveResult = move_uploaded_file($fileTmpLoc, "item_images/$image_name");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
$imageFile = "item_images/$image_name";
//$imageFile is the variable to use in the rest of your script.
?>
I just how to fix this problem. This worked for me you can give it a try:
Just change
item_images/'.$_POST['name'].'.'.$ext);
to
'item_images/'basename($_FILES["image"]["name"])
the following piece of code recognizes the image through getimagesize() but then when i try to move the file to an uploaded folder it moves the file there but says it's an array? im confused because im not setting any variables as an array?
<?php
//simple image check using getimagesize() instead of extensions
if($_FILES){
$empty_check = getimagesize($_FILES['file']['tmp_name']);
if(empty($empty_check)){
echo 'this is not an image';
}
else{
echo 'you have uploaded ' . explode('.',$_FILES['file']['name'])[0].'
and it is a ' . explode('.',$_FILES['file']['name'])[1].'.';
//an example of how i would extract the extension
$target = "C:\\xampp\\htdocs";
move_uploaded_file($_FILES['file']['tmp_name'], $target.'\\'.$_FILES['file']);
}
}
?>
$_FILES['file']
is an array, you're trying to use it as the target filename;
comment of deceze.
Echo the file you want to move/save, then you should see what he mentioned..
When using move_uploaded_file you get to pick the filename, so you can pick anything you want.
When you upload the file, its put into a temporary directory with a temporary name, move_uploaded_file() allows you to move that file and in that you need to set the name of the file as well.
Use this coding for multiple file uploading....
//For Multiple file uploading
if (isset($_FILES['photo']) != "") {
$errors = array();
foreach($_FILES['photo']['tmp_name'] as $key = > $tmp_name) {
$file_name = $_FILES['photo']['name'][$key];
$file_size = $_FILES['photo']['size'][$key];
$file_tmp = $_FILES['photo']['tmp_name'][$key];
$file_type = $_FILES['photo']['type'][$key];
//change the image extension as png
$fileExt = "png";
$photorename[$key] = strtolower($property_code.
'_'.$key.
'.'.$fileExt);
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
//Path of Uploading file
$target = "images_property";
if (empty($errors) == true) {
if (is_dir($target) == false) {
mkdir("$target", 0700); // Create directory if it does not exist
}
if (file_exists("$target/".$photorename[$key])) {
unlink("$target/".$photorename[$key]);
}
move_uploaded_file($file_tmp, "$target/".$photorename[$key]);
} else {
print_r($errors);
}
}
if (empty($errors)) {
echo "Success";
}
}
Why does the following code echo "Your files have been successfully loaded." when I try to upload a 20mb .gif file, when it actually a)should have been prevented, and b) doesn't actually get uploaded? Basically, I'm trying to limit file upload type, size using php. Page one has a form, which submits up to 10 photos.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$namebase = $_POST['projectID'].'_';
$ProjID = $_POST['projectID'];
$counter = 0;
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
if ($_FILES['userfile']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$counter = $counter + 1;
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
if (empty($file['name'])) {
break; /* You could also write 'break 1;' here. */
}
$url_base="";
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 1MB).
$upload_path = '../dev/images/uploaded/'; // The place the files will be uploaded to (currently a 'files' directory).
$allowed_filetypes = array('.jpg','.JPG'); // These will be the types of file that will pass the validation.
$ext = substr($file['name'], strpos($file['name'],'.'), strlen($file['name'])-1);// Get the extension from the filename.
$a='photo'.$counter;
${$a} = 'http:xxxxxxxxx'.$namebase.$counter.$ext;
if(!in_array($ext,$allowed_filetypes))
die('The file type of '.$file['name'].' you attempted to upload is not allowed. <INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($file['tmp_name']) > $max_filesize)
die($file['name'].' you attempted to upload is too large.<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// 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.<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Upload the file to your specified path. can rename here.move_uploaded_file(original file name, destination path and filename)
if(move_uploaded_file($file['tmp_name'],$upload_path.$namebase.$counter.$ext)){
echo '<b> '.$file['name'].'</b>'.' Accepted. Renamed '.'<b>'.$namebase.$counter.$ext.'</b>'.'<br>';
// It worked.
}
else
die('There was an error during the file upload. Please try again.'); // It failed :(.
}
}
echo 'Your files have been successfully loaded.<br>';
?>
It's possible that your if ($_FILES['userfile']) is false, so it goes directly to the end of the file ;)
Print out $_FILES array
print_r($_FILES)
if it empty then you will get success message.
I've built a rather straightforward file uploader in PHP. So far I've had no troubles uploading images and zip files. However, I can't seem to upload .mpg's. Whenever I try then it after hanging for a moment the page seems like it didn't try to upload anything at all. For example: this
// This is also manually set in php.ini
ini_set("upload_max_filesize", "524288000");
...
print_r($_FILES);
print_r($_POST); // I'm sending along one variable in addition to the file
returns nothing but empty arrays. For completeness, here's the front-end
<form action="uploadVideo.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="524288000"/>
<input type="hidden" name="extravar" value="value" />
<p>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br />
<i>Accepted formats: .mp4, .3gp, .wmv, .mpeg and .mpg. Cannot exceed 500MB.</i>
</p>
<p>Description:</p>
<textarea name="description" rows="4" cols="40"></textarea>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The file I am testing with is only 33MB and I tested a .wmv of similar size and it uploaded just fine.
Edit: Entire PHP file listed below
<?php
// Ensure that the user can upload up to the maximum size
ini_set("upload_max_filesize", "524288000");
ini_set("post_max_size", "524288000");
print_r($_POST);
print_r($_FILES);
if(!$link = mysql_connect($SERVER_LOCATION, $DB_USER, $DB_PASS)) die("Error connecting to server.");
mysql_select_db($DB_NAME);
$eventID = $_POST['event'];
// Select the event this is associated with
$query = "SELECT eventName FROM event WHERE eventID = $eventID";
if(!$res = mysql_query($query, $link)) die("Error communicating with database.");
$path = mysql_fetch_row($res);
$path = "media/$path[0]";
// If this event doesn't have a media folder, make one
if(!file_exists($path)) {
mkdir($path);
}
// If this event doesn't have a GIS subfolder, make one
$path = "$path/videos";
if(!file_exists($path)) {
mkdir($path);
}
// Generate todays date and a random number for the new filename
$today = getdate();
$seed = $today['seconds'] * $today['minutes'];
srand($seed);
$random = rand(0, 999);
$today = $today['mon']."-".$today['mday']."-".$today['year'];
$fileType = $_FILES["file"]["type"];
$fileExtension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$isMP4 = ($fileType == "video/mp4" && $fileExtension == "mp4");
$isWMV = ($fileType == "video/x-ms-wmv" && $fileExtension == "wmv");
$isMPG = ($fileType == "video/mpeg" && ($fileExtension == "mpeg" || $fileExtension == "mpg"));
$is3GP = ($fileType == "video/3gp" && $fileExtension == "3gp");
$sizeIsOK = ($_FILES["file"]["size"] < 524288000);
if( ($isMP4 || $isWMV || $isMPG || $is3GP) && $sizeIsOK ) {
if($_FILES["file"]["error"] > 0) {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
die();
} else {
// Ensure that the file get's a unique name
$filename = $today . "-" . $random . "." . $fileExtension;
while(file_exists("$path/$filename")) {
$random = rand(0, 999);
$filename = $today . "-" . $random . "." . $fileExtension;
}
move_uploaded_file($_FILES["file"]["tmp_name"], "$path/$filename");
$description = $_POST['description'];
$query = "INSERT INTO media (eventID,FileName,File,filetype,Description) VALUES ($eventID,'$filename','$path','video','$description')";
if(!$res = mysql_query($query, $link))
echo "<p>Error storing file description. Please contact a system administrator.</p>";
else {
echo "<h3>File: <i>".$_FILES["file"]["name"]."</i></h3>";
if(strlen($description) > 0) {
echo "<h3>Description: <i>".$description."</i></h3>";
}
echo "<p><strong>Upload Complete</strong></p>";
}
echo "<button onclick=\"setTimeout(history.go(-1), '1000000')\">Go Back</button>";
}
} else {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
}
?>
You cannot adjust the file upload limits using ini_set() from within the script that the uploads go to - the script does not get executed until after the upload is completed, so the ini_set() overrides cannot take place. The default parameters in PHP will be in place with the lower limit, and will kill the upload if it exceeds the system upload_max_filesize.
You need to override at the .ini level in PHP, or via a php_value directive in a .htaccess file. Those will change PHP's settings as the upload starts.
Ok, the first thing i thougt would be a problem with the filesize but other files with this size are working as you wrote.
But just do get shure it isn't a file size problem:
When you rise the max filesize you hmust also rise the max post size: post_max_size