I have a form from which I gather quite a bit of information and am then required to upload Multiple Files.
All other aspects of the form are now working perfectly thanks to Devi on this forum. And to try and focus on only the one problem I now have I have decided to start the new thread: The previous / old thread can be viewed Insert into one Table, while updating another & File Upload
My problem now is to actually get the files to upload. My form is working in two parts. Part one is the basic HTML layout which then has the method pointing to the PHP file which handles the writing of info to the database tables.
The form has the following code for each file upload (There are 4 uploads, each for a different file reference, ie. License Document, Renewal Document, Identity Document, Other Documents):
<div class="form-group">
<label>Permit Renewal :</label>
<div class="input-group">
<label>
<input type="radio" class="minimal" value="0" <?php echo ($permit_renewal=='No')?'checked':'' ?> name="permit_renewal">
No
</label>
<label>
<input type="radio" class="minimal" value="1" <?php echo ($permit_renewal=='Yes')?'checked':'' ?> name="permit_renewal">
Yes
</label>
</div>
</div>
<div class="box-body">
<div class="form-group">
<div class="form-group">
<label for="scanned_permit_renewal">Attach File</label>
<input type="file" id="scanned_permit_renewal" name="scanned_permit_renewal">
<p class="help-block">Select a file to link to this outlet, the file name must be prefixed with the Outlet. E.g. 102987 - License 2016</p>
</div>
</div><!-- /.form-group -->
And the relevant processing part is
if (isset($_FILES["file"]["name"])) {
foreach($_FILES['file']['tmp_name'] as $key => $tmp_name){
$file_name = $key.$_FILES['file']['name'][$key];
$file_size =$_FILES['file']['size'][$key];
$file_tmp =$_FILES['file']['tmp_name'][$key];
$file_type=$_FILES['file']['type'][$key];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
}
if($res1){
echo "Records added / updated successfully.";
}
header("refresh:2;url=../outlet_capture.php");
// close connection
$link->close();
I have also confirmed my rot directory and ensured that there is an /uploads/ folder present.
If don't see the definition, but it MUST have the enctype like
The $_FILES variable works with the name of the field in the form.
On your example it should be scanned_permit_renewal. And for access it from the PHP when the form was sent you should use $_FILES['scanned_permit_renewal'].
You uses on the foreach
foreach($_FILES['file']['tmp_name'] as $key => $tmp_name)
Which seems to be the problem.
IMHO you should use this:
foreach($_FILES as $fieldNameInTheForm => $file)
{
$file_name = $fieldNameInTheForm .$file['name'];
$file_size =$file['size'];
$file_tmp =$file['tmp_name'];
$file_type=$file['type'];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
You have done everything right, you are simply not pointing to the right input names...
$_FILES['file'] does not exist. You should use $_FILES['scanned_permit_renewal'] instead just like when you access $_POST, the key is the name of the form field.
Actually, you are looping through the $_FILES['file'] as if you had put many inputs with the name file[*something*]. If you question is complete, you should simply be using
if (isset($_FILES["scanned_permit_renewal"])) {
$file_name = $_FILES['scanned_permit_renewal']['name'];
$file_size =$_FILES['scanned_permit_renewal']['size'];
$file_tmp =$_FILES['scanned_permit_renewal']['tmp_name'];
$file_type=$_FILES['scanned_permit_renewal']['type'];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
To answer your comment, an efficient way of doing it could be 2 ways. First, which will require no PHP changes, rename your input fields to file[scanned_permit_renewal] this will let you use the foreach as you seem to intend.
Another way could be to use an array of possible inputs:
$file_inputs = array('scanned_permit_renewal','my','other','documents');
foreach($file_inputs as $input_name){
if (isset($_FILES[$input_name])) {
$file_name = $input_name.$_FILES[$input_name]['name'];
$file_size =$_FILES[$input_name]['size'];
$file_tmp =$_FILES[$input_name]['tmp_name'];
$file_type=$_FILES[$input_name]['type'];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
}
A third way could be to just loop through the $_FILES array. But I wouldn't do that, as there could be anything there. You'll prefer to filter on your wanted files.
For uploading multiple files, input field should be:
<input type="file" id="scanned_permit_renewal" name="scanned_permit_renewal[]" multiple="multiple">
processing part:
if (count($_FILES["scanned_permit_renewal"]["name"]) > 0) {
foreach($_FILES['scanned_permit_renewal']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['scanned_permit_renewal']['name'][$key];
$file_size =$_FILES['scanned_permit_renewal']['size'][$key];
$file_tmp =$_FILES['scanned_permit_renewal']['tmp_name'][$key];
$file_type=$_FILES['scanned_permit_renewal']['type'][$key];
$file_to_save = date("Ymd_his") . "_" . $file_name;
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" .$file_to_save;
//echo $new_file;
if(move_uploaded_file($file_tmp,$new_file)){
// update database
$query = "UPDATE `table` SET `field_name` = '".$file_to_save."' WHERE ..... ";
}
}
}
Related
I am using yii2. I am trying to select a file and then want to save it to my database table. I am using core PHP for it. Below is my code
<form action = <?=\yii\helpers\Url::toRoute(['meteracceptanceheader/import'])?> method ="post"
enctype="multipart/form-data">
.
.
.
.
.
.
.
<div class="row">
<div class="col-md-2">
Upload-Image
<input type="file" name="file"/>
<br />
<input type="submit" class="btn btn-primary pull-left" />
</div>
</div>
</form>
Controller
public function actionImport()
{
.
.
. // my other code
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileExt = explode('.',$fileName);
print_r($file);
die();
.
.
.
.
return $this->render('excel_finish', ['records_saved' => $ok_count,'status_arr'=>$status_arr]);
}
Database Table
In the above table, id is auto-increment accpt_id is the model id which I already have and file_path is the name of the file which should be saved like 123.jpg.
The file should be saved into a folder uploads/meter_acceptance/ and append with the file name.
Note:
I have already know how to upload images via the active form but here I want to do it in a traditional way.
Any help would be highly appreciated.
your controller should be like this
public function actionUpload(){
$model = new Images();
$uploadPath = Yii::getAlias('#root') .'/uploads/';
if (isset($_FILES['image'])) {
$file = \yii\web\UploadedFile::getInstanceByName('image');
$original_name = $file->baseName;
$newFileName = \Yii::$app->security
->generateRandomString().'.'.$file->extension;
// you can write save code here before uploading.
if ($file->saveAs($uploadPath . '/' . $newFileName)) {
$model->image = $newFileName;
$model->original_name = $original_name;
if($model->save(false)){
echo \yii\helpers\Json::encode($file);
}
else{
echo \yii\helpers\Json::encode($model->getErrors());
}
}
}
else {
return $this->render('upload', [
'model' => $model,
]);
}
return false;
}
I can't get the picture to display/show when viewing, although the files are already stored in the database (table 'menu') http://i.imgur.com/wo1w90H.png. Also when I upload the images all at once, their file name would change automatically. I don't know how and why this happens. I use array to upload multiple images.
if (isset($_POST["Submit"])) {
--some code here--
if (isset($_POST["id_list"])) {
// if id list available
foreach($_POST["id_list"] AS $id) {
--some code here--
/* Handle file upload */
if ($_FILES['upload']['error'][$id] == 'UPLOAD_ERR_OK') {
$path = "images/newmenu/";
$path_parts = pathinfo($_FILES["upload"]["name"][$id]);
$extension = $path_parts['extension'];
$picture = md5(uniqid()) . "." . $extension;
if (move_uploaded_file($_FILES['upload']['tmp_name'][$id], $path . "/" . $picture)) {
$update = " UPDATE menu
SET MenuPicture='$picture'
WHERE MenuID=$id";
$mysqli->query($update) or die(mysqli_error($mysqli));
}
}
}
}
}
}
Below is the form and yes it does include enctype="multipart/form-data"
<input type="file" multiple name="upload[' . $id . ']" value="' . $record["MenuPicture"] . '">
Filename changes because you are generating it this way
$picture = md5(uniqid()) . "." . $extension;
uniqid() is based on current time and hashing it will cause the filename to change everytime
When I upload the images all at once, their file name would change automatically
It was due to this:
$picture = md5(uniqid()) . "." . $extension;
// And later
move_uploaded_file($_FILES['upload']['tmp_name'][$id], $path . "/" . $picture)
Basically, you are moving your uploaded file to a new filename for your image file, which is generated using uniqid() and hashed with md5(), with the file extension appended at the end.
I can't get the picture to display/show when viewing
How are you trying to display the picture? Is it from web browser, or you go straight to the directory and open from there? What error(s) did you get, if any?
Actually, have you tried to go to the directory and see whether the file is created inside the images/newmenu/ directory?
Also, for the target upload directory, you might want to append it with $_SERVER['DOCUMENT_ROOT'] so that the target directory is not dependent on where your script is located, but it's always based on the root.
By the way, you might know already, but there is an entry in PHP manual page on uploading multiple files
I'm trying to make the folder with mkdir but no success, I can see that the path is correct but $_post isn't getting the name of folder from form input ($_post['foldername' is empty) don't know what's the problem. (I have all the permissions to make the folder safe_mode is off
You need to use $_POST to get the filename.
As has been posted in the comments, you also need to do something with $_POST['filename'] to insure that the user is not trying to post a relative path to your script and trying to create folders in locations that you don't intend. At the very least make sure that the variable doesn't contain '..' Since you are prepending a path, I don't think that you have to worry about a direct path to '/' but you may also want to invalidate inputs with a '/' in them.
You could always try this:
<?php
include("models/db-settings.php");
include("models/config.php");
$foldername = $_POST["foldername"];
$filename = $foldername;
$path = __DIR__ . "/uploads/" . $loggedInUser->username;
$fullPath = $path . "/" . $filename;
if (!file_exists($fullPath)){
mkdir($fullPath, 0777);
echo "The directory was successfully created.";
}
echo $fullPath;
?>
<form action="mkdir.php" method="post">
<input type="text" name="foldername" id="foldername" value="FolderName">
<input type="submit" value="submit">
</form>
Change
if (!file_exists($path)) {
mkdir("$path/$filename", 0777);
echo "The directory was successfully created.";
}
to
if (!is_dir($path)) {
mkdir("$path/$filename", 0777);
echo "The directory was successfully created.";
}
I have been trying to upload multiple files into a folder and save the names in a database table. Here's the code: I need to get the names of those uploaded files. I know my code is crap :(
Is there a way to loop through uploading those files and still return the file names?
I need those names to be able to insert them into mysql table.
Thanks for your assistance.
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="pic1" type="file" /><br />
<input name="pic2" type="file" /><br />
<input name="pic3" type="file" /><br />
<input name="pic4" type="file" /><br />
<input type="submit" value="Send files" />
</form>
And the PHP script is below:
<?php
$target = "uploads/";
$target = $target . basename( $_FILES['pic1']['name']);
$target = $target . basename( $_FILES['pic2']['name']);
$target = $target . basename( $_FILES['pic3']['name']);
$target = $target . basename( $_FILES['pic4']['name']);
$pic1 =($_FILES['pic1']['name']);
$pic2 =($_FILES['pic2']['name']);
$pic3 =($_FILES['pic3']['name']);
$pic4 =($_FILES['pic4']['name']);
$con = mysql_connect("localhost", "root", "");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("people", $con);
$sql="INSERT INTO mtpupload (name, age, pic1, pic2, pic3, pic4 )
VALUES('$_POST[name]','$_POST[age]','$pic1', '$pic2', '$pic3', '$pic4')";
//---------Here, I want to insert all the pictures----------//
if(move_uploaded_file($_FILES['pic1']['tmp_name'], $target)) {
//do nothing
}
if(move_uploaded_file($_FILES['pic2']['tmp_name'], $target)) {
//do nothingelse{
}if(move_uploaded_file($_FILES['pic3']['tmp_name'], $target)) {
//do nothing echo "Sorry, the image was not moved from temp folder.";
}if(move_uploaded_file($_FILES['pic4']['tmp_name'], $target)) {
//do nothing
echo "The was a problem uploading one of your images.";
}
//--------------Ends here---------------------//
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
UPDATE: turns out that this code is working but only saving one image in the folder. I think my move_uploaded_file is wrong. Any pointers?
Thanks again for your help.
Maybe this is helpful, using an array with the files field names and foreach:
$fields = array('pic1', 'pic2', 'pic3', 'pic4');
$fileNames = array();
foreach($fields as $field)
{
$file = $_FILES[$field];
# you can now process each file on it's own.
$fileNames[$field] = $file['name']; # store all names into an array
...
}
Thanks folks for your suggestions, I finally got it working. I was using $target variable in many places. Renaming it to different variable helped.
What about this:
foreach ($_FILES as $file) {
echo $file['name']; // File name of file on user's computer
echo $file['tmp_name']; // Full path to the file on the server
}
in the following code ,i am trying to upload an image to server . there is a folder 'images ' on the server. whenever i am clicking the 'ok' button ...it gives an error " there is problem in uploading file"... where is the problem in my code?
html-----------------------------------------
<form method="post" action="newproduct.php" enctype="multipart/form-data">
Item Image:<input type="file" name= "photo" size="40" />
Description:<textarea name="description" cols="40" rows="1"></textarea>
<input name="submit" type="submit" value = "Submit" />
</form>
php-------------------------------------------------------
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
$description =$_POST["description"];
//checking for empty values
if (empty($pic) || empty($description))
{
echo "Please enter all field values.";
}
else
{
//Connecting to database server
//Connecting to database
//INSERT Query
$SQLstring = "INSERT INTO items VALUES(null,'$pic' ,'$description')";
$QueryResult = #mysqli_query($DBConnect, $SQLstring)
or die ("<p> Unable to execute the query. </p>".
"<p> Error code " . mysqli_errno($DBConnect) . ":" . mysqli_error($DBConnect))."</p>";
if(move_uploaded_file($_FILES['photo']['name'], $target))
{
echo "The file has been added to the directory";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
mysqli_close($DBConnect);
}
?>
The images folder needs to have 777 permissions on it. By default the permissions are 655, and PHP does not have permissions to upload/move/copy a file outside the current folder it is in (subdirectories count as different folder)
you can't do that... you don't update a photo like that in Javascript... (with ajax..)
It is not going to work like that...
But... you can fake this...
You have to submit that post somehow...
You have several solutions: use a flash to fake upload ajax or an iframe..
You can also use jQuery .. he will do all the stuff for you..
Here are some demo & download links:
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
http://www.webdeveloperjuice.com/2010/02/13/7-trusted-ajax-file-upload-plugins-using-jquery/
http://www.fyneworks.com/jquery/multiple-file-upload/
If you want to move the uploaded file you have to move the "tmp_name" with the new name.. like
if (!move_uploaded_file($_FILES['photo']['tmp_name'], $path.$_FILES['photo']['name']))
echo 'CANNOT MOVE {'.$_FILES['photo']['name'].'}' . PHP_EOL;
When you upload your file, apache takes care of it and by default is in /tmp (if you use linux... I don't know in windows case)..
P.S: for your script's performance you should use ' ' instead of " " for strings.. when you use " " PHP is checking every " "(string) for variables == more operations to do.. and ' ' are skipped