keep last modified date when uploading file - php

Is there a way to preserve the last modified date when uploading a file via HTTP POST?
I already read that it gets changed when you use copy() (See here).
But in my case, it's already changed in the temp folder.
HTML:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
PHP:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
echo "Modified: ".date('d/m/Y H:i:s', filemtime($_FILES['fileToUpload']["tmp_name"]));
?>
The output is: Modified: 17/02/2016 09:02:39
But the file is actually last edited on 10/02/2016 09:34:23
Properties: (created, modified, access)
Is there a way to prevent that?

The last modified date can be captured in the browser using the File.lastModified property. You can use JavaScript to set the value of a hidden input element to this date. Once the form is submitted, read the timestamp from the hidden input and use the method touch to set the timestamp on the newly created file on the server-side.
https://developer.mozilla.org/en-US/docs/Web/API/File/lastModified
https://www.php.net/touch

Sorry you cannot keep the file information. The uploaded file is considered as new file.

Related

How to create directory and save image in it using php

I have a code where I am selecting an image and then entering the name of the directory I want to create to save that image. After this, once a button is clicked the directory should be created in the given path and file should be saved in it.
Below is the code I am using:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file"/>
<input type="text" name="idtest" value=<?php echo $idtest; ?> >
<input type="submit" value="Send File" multiple/>
</form>
upload.php
<?php
$uploaddir = 'G:/dataset/' . $idtest;
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']) ;
echo $uploadfile;
?>
Here in the above code I have not include the create directory part which I still have to work on. Now ideally the variable idtest should be appended with uploaddir variable so whenever I am printing the value of uploadfile the last directory should be the one which I entered in the text box. But its not working. Can anyone please throw some light on why its not working. Thanks
Give this upload script a try. Based on your comments, it seems the first issue is the directory name entered in the form not being added to the full uploadfile path. You will need to grab idtest from the $_POST variable first. I would also recommend using move_uploaded_file to move the uploaded file.
upload.php
<?php
$uploaddir = 'G:/dataset/' . $_POST['idtest'];
// check if directory exists
if(!is_dir($uploaddir)){
mkdir($uploaddir);
}
$uploadfile = $uploaddir ."/". basename($_FILES['userfile']['name']) ;
echo $uploadfile;
move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile);
?>
Please ensure proper form validation and file name checks for security reasons, but that is beyond the scope of this answer. As the other commenters have mentioned, ensure file system permissions are set to allow writing to G:/dataset/.

Saving image with PHP on localhost uploaded with a form

i'm trying to save an image uploaded with a HTML form on my localhost server (working with Xampp), but although there are no errors, the file isn't saved anywhere.
This is the form, really simple:
<form id="form1" action="result.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="imguploaded" id="imguploaded" accept=".png, .jpg, .jpeg"></br>
<input class="btn btn-outline-danger btn-lg" id="inputbtn" type="submit" value="Upload Image" name="submit">
</form>
and this is the PHP code (on result.php):
<?php
$result=false;
$error=false;
if (isset($_FILES['imguploaded'])){
$nomefile = strtolower($_FILES['imguploaded']['name']);
$path = "caricamenti/$nomefile";
move_uploaded_file($_FILES['imguploaded']['name'], $path);
echo($path);
}
?>
the path exists and it is in the same folder of the .PHP files.
In move_uploaded_file($_FILES['imguploaded']['name'], $path); the first parameter isn't correct. It should be the temporary path where php stored it intermediatly, which you find in $_FILE['imguploaded']['tmp_name'].
So change that line to
move_uploaded_file($_FILES['imguploaded']['tmp_name'], $path);
relevant docs
Be sure to:
sanitize filename & extention first
check for allowed mimetypes, size, ..
Right now I could easily upload a php script and execute that.
Try this:
$file_name= $_FILES['imguploaded']['name'];
$file_tmp_name= $_FILES['imguploaded']['tmp_name'];
$div= explode('.',$file_name );
$file_txt= strtolower(end($div));
$unique_image= substr(md5(time()),0,10).".".$file_txt;
$uploaded_image= "caricamenti/".$unique_image;
move_uploaded_file($file_tmp_name,$uploaded_image);

php - Upload .dat file to be stored in json

I am trying to upload .dat file, I want to get the content inside the file and have it in json.
I have this code:
HTML:
<from action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<button type="submit" name"btnSubmit">Upload</button>
</form>
PHP:
If(isset($_POST["btnSubmit"])) {
$file = file_get_contents($_FILES["fileUpload"]["name"], true);
$r = json_encode($file);
}
The error I get is file_get_contents("fileName.dat"): failed to open stream
I am not trying to upload the file to my server or a folder, I am trying to get the data inside it and store it into json.
A file upload will save the file in the php's defined temporary directory. From there you can either move the file to a desired location, or get the content from it. In your case you can simply get the content by using "tmp_name" instead of "name".
Future more, you have to make sure you have the enctype set in your form.
<?php
// check if file is given
if(!empty($_FILES)) {
// get file from temporary upload dir
$file = file_get_contents($_FILES["fileUpload"]["tmp_name"], true);
$r = json_encode($file);
// show restult
var_dump($r);
}
?>
<!-- add multipart -->
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<button type="submit" name"btnSubmit">Upload</button>
</form>

how to count number of uploaded files in php

How can i count the number of uploaded files?
This is my form:
<div id="dragAndDropFiles" class="uploadArea">
<h1>Drop Images Here</h1>
</div>
<form id="sfmFiler" class="sfmform" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" multiple />
<input type="submit" name="submitHandler" id="submitHandler" class="buttonUpload" value="Upload">
</form>
and this is the piece of php which uploads the files:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$tmpFilePath = $_FILES['file']['tmp_name'];
$newFilePath = $dir.'/' . $_FILES['file']['name'];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "xxx files are successfully uploaded";
}
}
In this code you are getting only one file thats why you are getting count result 1. if change your input file name like "file[]"
<input type="file" name="file[]" id="file" multiple />
and then use the below line code you will get your desire result. Cause its needs an array filed to hold the input data.
<?php echo count($_FILES['file']['name']); ?>
Thanks, i tried in my system get the result.
AFriend is correct. The above answers always return 1.
Try:
echo count(array_filter($_FILES['file']['name']))
Worked for me anyway.
_t
Using the array_filter function it works
try
$countfiles = count(array_filter($_FILES['file']['name']));
It returns 0 in case of NULL, 1 in case of 1 file uploaded, etc.
Check this answer
<?php echo count($_FILES['file']['name']); ?>
php multiple file uploads get the exact count of files a user uploaded and not the count of all input fields in the array
You could use the count function:
$no_files = count($_FILES);
If no files are selected and your file count is 1, you can use this line before moving the file:
if (!empty($_FILES['file']['tmp_name'][0])) {
for($i=0;$i<$countfiles;$i++){

make a upload field using php and send the url to database

I want to create a form to submit an image file in the front-end and send it to the wordpress upload directory and database using php ,but my php says the file is a image but dont upload it :
<div id="recibo">
<form action="" method="post" enctype="multipart/form-data">
<p>upload do recibo:
<input type="file" name="pictures[]" />
<input type="submit" value="Enviar" />
</p>
</form>
</div>
php:
<?php
$target_dir = "wp-content/uploads/recibos";
$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;
}
}
?>
There are a few things wrong here.
Firstly, the file input's name attribute is name="pictures[]" yet you are using $_FILES["fileToUpload"], those must match.
So rename it: name="fileToUpload[]"
Sidenote: Using brackets implies an array to upload multiple files; you don't need it here since the rest of your code doesn't support multiple files uploading.
Change it to name="fileToUpload"
Then your folder path:
$target_dir = "wp-content/uploads/recibos";
You have no directory seperator after recibos
This would translate to recibosFILE.JPG rather than recibos/FILE.JPG.
Change it to:
$target_dir = "wp-content/uploads/recibos/";
Make sure the folder you are uploading to has the correct permissions to write to it.
Another thing: I can't see how if(isset($_POST["submit"])) {...} would work here, since your submit button does not have the name attribute to match it with.
<input type="submit" value="Enviar" /> to <input name="submit" type="submit" value="Enviar" />
Special note:
If you do want to upload multiple files, then you will need to find yourself another script to do that and this isn't what your question is about.
See also:
PHP change the maximum upload file size
to increase upload size
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.

Categories