EDIT
I have this PHP code now:
$name = isset($_POST['image_file']) ? $_POST['image_file'] : '';
$date_added = date ("F d Y H:i:s.", filectime(basename($_FILES["image_file"]["tmp_name"])));
$path = "../uploads/".basename($_FILES["image_file"]["name"]);
$patient_id = $_POST['patient_id'];
$remark = $_POST['remark'];
//$date_added = $_POST['date_added'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
...
And the result of any file (except images) is: January 01 1970 01:00:00.
And when I try to upload an image it send me to an empty page where no errors are shown and the image isn't uploaded into folder.
END EDIT
I need to add scanned images into patient file using this form:
<form enctype="multipart/form-data" id="myForm" name="myForm" action="add_scan.php" method="post">
<div class="box-body" id="toggleDiv">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label style="float:left">File Description</label>
<input type="text" class="form-control" id="remark" name="remark"/>
<label style="float:left">Upload File</label>
<input type="file" class="form-control" id="image_file" name="image_file"/>
<input type="hidden" class="form-control" id="patient_id" name="patient_id" value="<?php echo $patient_id ?>"/>
</div><!-- /.form-group -->
<button type="submit" class="btn btn-warning" id="add_scan" name="add_scan">Add File</button>
</form>
Usually, my client add a date but sometimes he forgot in what date the image is taken. So I need to access the system date of the image.
I tried the following:
Add_scan.php page:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('../include/global.php');
//session_start();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_scan']))
{
try
{
$name = isset($_POST['image_file']) ? $_POST['image_file'] : '';
$path = "../uploads/".basename($_FILES["image_file"]["name"]);
$date_added = date ("Y-m-d", filectime(basename($_FILES["image_file"]["name"])));
$patient_id = $_POST['patient_id'];
$remark = $_POST['remark'];
//$date_added = $_POST['date_added'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
move_uploaded_file($_FILES["image_file"]["tmp_name"], $path.$name);
$sqlUpd = "INSERT INTO scan_image(id_logged, patient_id, image_file, remark, date_added)
VALUES(:id_logged, :patient_id, :image_file, :remark, :date_added)";
$stmt = $conn->prepare($sqlUpd);
$stmt->bindValue(':id_logged', $id_logged);
$stmt->bindValue(':patient_id', $patient_id);
$stmt->bindValue(':image_file', $path);
$stmt->bindValue(':remark', $remark);
$stmt->bindValue(':date_added', $date_added);
$stmt->execute();
header("Location: patients.php?patient=".$patient_id);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Where I used this line: $date_added = date ("Y-m-d", basename($_FILES["image_file"]["name"])); to access the date according to PHP PDO documentations in this link.
But nothing added and I only see a blank page of my add_scan.php code and it is not redirected to patient.php page.
SOLUTION:
Because you're uploading a file the date on the system is going to be the upload date. Your solution if it is an image file is to read the image file meta-data, which is a bit of a pain because there are multiple types of meta data for each type of image file and finding the one you want is not in itself efficient.
I think Imagick PHP plugin does this but I can't vouch for the quality or worth of this/these functions.
To clarify further:
When you upload a file from a computer to a server, the server will hold NO filesystem information about the file on the computer.
Meta Data is data about something, and typically data about a file (such as its created date) is not stored within the file itself as a standard, but in the operatng system that stores the file contents.
The server which recieves your uploaded file can not tell you when the file was saved on to the computer it came from, or anything else filesystem related because the server has only been given the file contents data, not the file systems metadata about storage and modification (etc).
If this information is available from within a file, it is stored in what is called "MetaData" inside the file itself, and to reach these bits of metadata you need to use something like Imagick for images .
Alternatively, if you simply want the date the file was added to this system you can read that in this Stack Answer.
NOTES:
You want filectime.
After you header add an exit to cease execution.
You have a $_POST and a $_FILES value with the same name, you are using $_POST['upload_file'] and $_FILES['upload_file'] I'm not sure if this will break your script but the POST values of this will be empty unless you have another field in your form with the same name which is clearly bad practise.
Your require and/or include do not need to be in brackets.
It is also bad practise for pathinfo to be given a relative path, you should as much as possible give PHP functions absolute paths, using $_SERVER['DOCUMENT_ROOT'] or other magical constants.
Remove basename in filectime, it's unneed.
it looks like $path.$name should infact be $path.$name.$ext when using move_uploaded_file
Your problem (from your comment) is that you are looking for the time of a string that is not the file. Replace $_FILES["image_file"]["name"] in you filectime call to instead be ['tmp_name'] because this is the location address of where the uploaded file is (temporarily) stored.
The name array value in $_FILES simply tells you the name of the file from the place it was uploaded from.
BUT This time will simply only tell you the uploaded time.
Your Error log should have shown you that your filectime is tying to get the data from a non-file entity.
filemtime reports the files modification time, not its creation time (this is not available on most operating systems).
That's not the PDO documentation.
The file uploaded is a copy of the data held in the original file - so the mtime you see on the copy will always be about 'now'.
The user can see the modification time on their local machine. If they can't provide this information then the only option would be to take a backup of the files, restore it on your server (using an appropriate method which does not change the mtime, e.g. untar as root) then load the files directly from there rather than uploading over the web.
Related
I am having a problem with using this php script to store an uploaded image file name in a database and store the file with a random generated name in a folder.
I get error show up on my sceen as a result of my script producing an echo however no real errors show up. The file is being stored in my directory folder however it doesn't have a random name given to it and it is not being stored in the database. I have spent an hour trying to figure what could be wrong. I would seriously appreciate help.
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<label>Title</label>
<input type="text" name="title">
<label>File Upload</label>
<input type="File" name="file">
<input type="submit" name="submit">
</form>
</body>
</html>
<?php
$localhost = "localhost"; #localhost
$dbusername = "root"; #username of phpmyadmin
$dbpassword = " "; #password of phpmyadmin
$dbname = "fun"; #database name
#connection string
$conn = mysqli_connect($localhost,$dbusername,$dbpassword,$dbname);
if (isset($_POST["submit"]))
{
#retrieve file title
$title = $_POST["title"];
#file name with a random number so that similar dont get replaced
$pname = rand(1000,10000)."-".$_FILES["file"]["name"];
#temporary file name to store file
$tname = $_FILES["file"]["tmp_name"];
#upload directory path
$uploads_dir = "images/";
#TO move the uploaded file to specific location
move_uploaded_file($tname, $uploads_dir.'/'.$pname);
#sql query to insert into database
$sql = "INSERT into fun(image) VALUES('$pname')";
if(mysqli_query($conn,$sql)){
echo "File Sucessfully uploaded";
}
else{
echo "Error";
}
}
?>
I had the same problem in uploading a file using php with you. I think you should add $_SERVER['DOCUMENT_ROOT'] to the part of your code where you’re specifying the destination directory in so that the move_uploaded_file() function will look like this :
move_uploaded_file($tname, $_SERVER['DOCUMENT_ROOT'].$uploads_dir.'/'.$pname);
I have had exactly this problem some years ago. What I surmised was that the PHP function move_uploaded_file() does not actually result in a file than is moved as far as the operating system is concerned, until the PHP script exits and closes its file handles.
I forget which workaround I used - Possibly I used php to COPY the file instead of move it.
It is a real limitation when putting user supplied data in a database.
Ah. I found the code I used.
$filename=basename($filename);
$newname=$tmpname.$id;
copy($tmpname,$newname);
$query=sprintf("update product set picture=LOAD_FILE('%s'),picture_filename='%s', picture_size='%d' where id='%d'",
$newname, $filename,$filesize,$id);
mysql_query($query); //there!
unlink ($newname);
This should be enough of a fragment to get the general idea.
In later versions of doing similar I read the file into memory, and if it's binary, turn it into a hex string and insert that.
I am completely a novice in all this ...
I have created a Social Networking project in which there is a module which allows user to upload photos..
I have hosted this project in my college server
I access that server using bitvise client with my server credentials.
My problem is i don't know how to setup upload mechanism for remote server ... In my localhost i simply use
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
function but i don't know how to do this for remote server ...
I tried FTP by looking at some tutorials but that didn't worked for me.
In my project structure there is a directory
users/user_id (diff for all users)/photos
here i want to place the uploaded files....
A proper description with example and proper functioning might be very helpful for me.... Thank you
EDIT:
Below is my code.
Photos.php
<form class="input-group-btn" method="post" action="editPhotos.php"enctype="multipart/form-data" id="myForm">
<input type="file" name="file" id="imgInp">
<button type="submit" class="btn btn-primary" name="form-submit">Done</button>
</form>
editPhotos.php
if( isset($_POST['form-submit']) ){
$target_file = "users/".$email."/pictures/Photos/" . basename($_FILES["file"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$img =str_replace(" ", "",basename($_FILES["file"]["name"]));
rename($target_file, "users/".$email."/pictures/Photos/".$img);
header('Refresh: 1; url=Photos.php?user='.$email);
}
Small tutorial how to upload file.
For sure, you need correct encryption and file's type in your form (ommited other fields, to clear example):
form.html
< form action="upload.php" method="post" enctype="multipart/form-data">< /form>
< input name="test" type=file>
upload.php
In $_FILES you have all data of uploaded file. In given example, we have field named test.
Advice, to always first check error $_FILES['test']['error'] - the values you can find in here.
If this is correct, then prepare upload path. Some advices:
remember that if you use original filename ($_FILES['test']['name']), then is User upload second file, with same name, you will need overwrite file or ignore upload. Other way, is to save data to database and generate temporary name form him.
destination path(target_file) - regardless if upload folder is in the same catalog, you should always use global path, as good practice. You can use DIR for that.
don't use in path data, like email - is you have project, and want give opportunity to change email in configuration, what you will do with files? Better save user to Database and use his ID as key.
If you have path, then you simply need only use of move_uploaded_file, but remember to check result, as it not always will return true. You can have error, when you don't have permissions to destination folder (you'll need debug this).
I see that you, first upload file, then rename (then you should check, if rename was success). Don't extends this process, if it not necessary. Upload file for final path and name.
Example of code (I this rattle off)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$fileName = basename($_FILES["file"]["name"]);
$fileName = str_replace(" ", "", $fileName);
$target_file = sprintf(__DIR__ . "/users/%s/pictures/Photos/%s", $email, $fileName);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
// File was uploaded
header('Refresh: 1; url=Photos.php?user=' . $email);
} else {
// File was not uploaded;
throw new \Exception('File was not uploaded. Check warnings.');
}
}
Used other method to check, if this is POST
use method sprintf, for better code quality
checked effect of move_uploaded_file
use global path for destination file
Below code is risky in live environment, please use cautiously
Use a relative path to the uploads folder. For example, if your uploads folder is placed outside your current folder. Then
$PATH = '/absolute/example/path/to/uploads';//from config file
$target_file = "$PATH/file_name";
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
The above code will work both in local and remote server.
Other checks are below:
Check for errors while uploading file in server
To enable error handling use below code in your upload logic:
ini_set('display_errors', 1);
error_reporting(E_ALL);
Another important note is to make uploads folder writable otherwise file upload wont work.
I want to get the path of a selected file and store it in the database for future use.
I have the following code but it does not work.
$path = $_FILES['txtImage']['tmp_name'];
$sql = "INSERT INTO tblquestions (q_category, q_question, q_image, q_correct, q_answer2, q_answer3, q_answer4) VALUES ('$_POST[txtCategory]','$_POST[txtQuestion]','$path','$_POST[txtCorrect]','$_POST[txtChoice2]','$_POST[txtChoice3]','$_POST[txtChoice4]')";
txtImage is the name of my input type="file" and $path is the code i am using but it does not work. IT just returns blank.
Anyone who can help me or lead me to a different, hopefully easier method? Thank you in advance. :)
PHP will store submitted files in a temporary directory, which you shouldn't be storing in the database as it'll be volatile.
Use PHP's move_uploaded_file function to move the file to where you'd like in your file system, and then store that path in your database.
Docs: http://php.net/manual/en/function.move-uploaded-file.php
$tmp_path = $_FILES['txtImage']['tmp_name'];
$dest_path = path_where_in_your_server_you_want_this_image_to_be_moved.$_FILES['textImage']['name']; (eg: 'images/'.$_FILES['name'])
if(move_uploaded_file($tmp_path,$dest_path)){ //this will move the file from tmp location in server to the destination you provide in the second parameter
$sql = "INSERT INTO tblquestions (q_category, q_question, q_image, q_correct, q_answer2, q_answer3, q_answer4) VALUES ('$_POST[txtCategory]','$_POST[txtQuestion]','$dest_path','$_POST[txtCorrect]','$_POST[txtChoice2]','$_POST[txtChoice3]','$_POST[txtChoice4]')";
}else{
echo "Image could not be uploaded"
}
Also keep in mind that there can be permission issues (with the directory that you want the image to be uploaded to) while uploading the file.
Good Luck!
Have you set your form enctype correctly on the HTML side so that it is correctly able to work as it should.
Secondly, TMP is just a temporary location, you MUST move that file to a server readble directory using PHP function move_uploaded_file
Read about enctypes, in this answer or on w3 schools.
<form name="YourForm" method="post" enctype="multipart/form-data" action="">
I'm quite new to PHP and trying to upload an image to the server and then write it to the database using a form and php using the code and form below but it doesnt seem to be working for, if I take all of the photo content out the form works perfectly well with the other variables and content such as writing the out the article title and content, would anyone be able to tell me where I'm going wrong at all? thanks in advance guys.
<?php
session_start();
include_once('../php/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_POST['title'], $_POST['content'], $_FILES['photo1'])) {
$title = $_POST['title'];
$content = nl2br($_POST ['content']);
$photo1=($_FILES['photo1']);
$target = "../lifestlye";
$target = $target . basename( $_FILES['photo1']);
$query =$pdo->prepare('INSERT INTO article (article_title, article_content, photo_1) VALUES (?,?,?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $photo1);
$query->execute();
move_uploaded_file($_FILES['photo1'], $target);
{
}
header('Location: index.php');
}
?>
<form action="add.php" method="post" autocomplete="off"/>
<dl class="field four columns centered">
<dd><label for="title">Article Title</label></dd>
<dt class="text"><input type="text" name="title" id="title"/>
</dt>
</dl>
<dl class="field nine columns centered">
<dd><label for="content">Content</label></dd>
<dt class="textarea">
<textarea name="content" id="message"></textarea></dt>
</dl>
<p class="blacktext">Photo</p>
<input type="file" name="photo1">
<input type="submit" id="add article"/>
</form>
Try this code:
<?php
session_start();
include_once('../php/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_POST['title'], $_POST['content'], $_FILES['photo1'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
$name = $_FILES['photo1']['name'];
$tmp_name = $_FILES['photo1']['tmp_name'];
$target = '../lifestlye/'.$name;
if (move_uploaded_file($tmp_name,$target)) {
$stmt = $pdo->prepare('INSERT INTO article (article_title, article_content, photo_1) VALUES (?,?,?)');
$stmt->execute(array($title,$content,$name));
header('Location: index.php');
exit();
}
}
}
You are making it way too simple. You need to read the manual page: http://www.php.net/manual/en/features.file-upload.post-method.php
First, add this to your form as parameter: enctype="multipart/form-data"
Then, understand that $_FILES['photo1'] will be an array, and $_FILES['photo1']['tmp_name'] will contain a temporary filename, which is the uploaded file. You can then move the file to a new location, or read it and put it into the database as a BLOB (but why do you want to keep binary data in a database?)
You should use absolute paths for moving the file. If you want to do something in the current dir, use __DIR__ or dirname(__FILE__) depending on your php version. The first one is to preferred if it's available.
You should do error checking - read up on $_FILES array on php.net manual for what to look out for.
Check the return value of move_uploaded_file, errors, notices - there might also be a problem with writing permissions (the target directory/file has to be writable by the webserver)
You should consider generating a filename, otherwise if 2 ppl upload a file with the same name, the second one will override the first one. Then starts the fun about race conditions and the impossibility of php itself to do an atomic lock (using mysql get lock is the best I've come up so far, as semaphores and file locking suck in a web context with php)
You should add some security checking, e.g. str_replace("\0", "", $filename) for avoding nul poisoning (and depending on your system and filesystem there are probably other things you should filter/check)
This is just a tip, but really: Don't do anything with user input, especially file upload, in the open (e.g. publicly available web address) if you haven't got enough experience in regards to php/security. Otherwise you will see your server crashed, taken over, ... in a very short time. PHP is already very insecure as it is, adding in mysql and file upload doesn't really make it better. There is no guarantuee that the filename you get from $_FILES is safe - an attacker could send ANY filename (i can easily do with a few lines of script myself, and I'm not a real hacker).
Also, basename does not filter filenames, it just gives you whatever is before the last '.'.
Edit: + everything Palantir wrote, to make it work (sorry, there were so many things on this that I skipped some)
Okay, so I set up an upload engine for a website so that an authenticated user can upload a audio file (a key) for a song in the library, but I come across this strange problem when I try to upload any file over 5MB.
I set my php.ini max filesize to 50MB by the way
Everything uploads properly, but there is no data associated with the file on the other end.
HTML CODE:
<form action="keyUpload.php?id=<?php echo $id;?>" method="post" enctype="multipart/form-data">
<p style="color:#fff;font-size:30px;font-family:Times">
Add a new Key:<br/><input name="uploaded" type="file" id="file"><br />
<input type="text" name="kname" id="kname" value placeholder="Key Name (Ex. Demo, A#, etc.)" style="width:300px;"><br/>
<button class="button">Upload File</button><br/>
<span style="font-size:12px;">*Max Filesize is 50 MB*</span>
</p>
</form>
PHP CODE:
<?php
$id=$_GET["id"];
$name=$_POST["kname"];
$name = str_replace(" ","%20",$name);
$allowed_filetypes = array('.mp3','.m4a','.wav','.wma');
$filename = $_FILES['uploaded']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
Both $filename and $ext are empty variables when I upload a file larger than 5 MB. In all other cases, this engine works perfectly.
When echoed, simply nothing happens, so obviously the engine will not save the file if it doesn't exist. What's going on?
var_dump:
array(0) { }
Thanks for all your help!
Check for upload errors:
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['uploaded']['error']);
}
The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php
As well, do NOT use filenames to validate the uploads. It is beyond trivial for a malicious user to fake a filename and upload malicious files, eg.
ren nastyvirus.exe good_tune.mp3
And don't use string operations on filenames. There's a whole whack of PHP functions for filename manipulation, e.g. http://php.net/basename
Set max_post_size in php.ini as well.