How to upload & Save Files with Desired name
You can try this,
$info = pathinfo($_FILES['userFile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext;
$target = 'images/'.$newname;
move_uploaded_file( $_FILES['userFile']['tmp_name'], $target);
how to upload and save a file with desired name php
Firstly, you do not have a form element named submit_student
that is why part of your code does not work, as per this conditional statement if (isset($_POST['submit_student']))
Try the following:
<?php
if (isset($_POST['upload_btn'])){
$student_id=mysqli_real_escape_string($cnn,$_POST['student_id']);
$exam_id=mysqli_real_escape_string($cnn,$_POST['exam_id']);
if(isset($_FILES['resultpdf']['name'])){
$newname=mysqli_real_escape_string($cnn,$_POST['student_id']) . "_".mysqli_real_escape_string($_POST['exam_id']) . ".pdf";
$target='karname/'."{$newname}";
move_uploaded_file( $_FILES['resultpdf']['tmp_name'] , $target);
}
echo " <form action='' method='POST' enctype='multipart/form-data'>";
echo " <input type='file' name='resultpdf'><br>";
echo " <input type='hidden' name='exam_id' value=\"{$exam_id}\">";
echo "<input type='hidden' name='student_id' value=\"{$student_id}\">";
echo "<input type='submit' name='upload_btn' value='upload'>";
echo "</form>";
}
?>
Plus, since you are executing everything from the same file you can just do action=""
instead of action='manage_add_result.php'
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Upload file name in database with rename in PHP
Use $_FILES["file"]["name"]
to get name of uploaded file.
$name = $_FILES["file"]["name"];
Then you can rename file name:
$filename = date('mdhms').$name;
To move the file to your folder:
move_uploaded_file($_FILES['file']['tmp_name'], $folder);
Uploading different unique files to the server and their names saved to the database
You have a ton of things messed up, but this should be a working script. Aside from my above comments, I have notated below for additional information and concern:
FORM
<form id="form1" name="contacts_form" method="post" action="" enctype="multipart/form-data">
<table>
<tr>
<!-- You need to array these. The method you have is too manual
You could even use for() to create these -->
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
PHP
<?php
// I can't check this for you...
include("../Connections/Connect.php");
// In general, you have no check to see that anything was submitted.
// That is something you may want to implement or else this script
// will autoload on page load regardless of $_FILES or $_POST submission
// You may want to add document root
$target = $_SERVER['DOCUMENT_ROOT']."/uploads";
// I am filtering the files incase there are empty uploads
// You need to have the proper file input name (item)
$_FILES['item']['name'] = array_filter($_FILES['item']['name']);
$_FILES['item']['type'] = array_filter($_FILES['item']['type']);
$_FILES['item']['size'] = array_filter($_FILES['item']['size']);
$_FILES['item']['tmp_name'] = array_filter($_FILES['item']['tmp_name']);
foreach($_FILES['item']['name'] as $i => $value ) {
$file_name = $_FILES['item']['name'][$i];
$file_size = $_FILES['item']['size'][$i];
$file_tmp = $_FILES['item']['tmp_name'][$i];
$file_type = $_FILES['item']['type'][$i];
$name = ms_escape_string($_POST['nameMember']);
$bandMember = ms_escape_string($_POST['bandMember']);
$about = ms_escape_string($_POST['aboutMember']);
$bands = ms_escape_string($_POST['otherBands']);
$sqlArr['values'][$i] = "'".ms_escape_string($_FILES['item']['name'][$i])."'";
$sqlArr['columns'][$i] = "photo".$i;
// At this point you are only notifying user.
// You have no code to prevent this limitation.
if ($file_type!="application/pdf" || $file_type!="image/gif" || $file_type!="image/jpeg")
$errors[] = 'You can only upload PDFs, JPEGs or GIF files.<br>';
// So far, this is just for notification, you haven't
// actually done anything about this limitation
if($file_size > 2097152)
$errors[]='File size must be less than 2 MB';
// Makes the folder if not already made.
if(!is_dir($target))
mkdir($target,0755,true);
//Writes the files to the server
if(move_uploaded_file($_FILES['item']['tmp_name'][$i], $target."/".$file_name)) {
//If all is ok
echo "The file ". $file_name. " has been uploaded to the directory and records saved to the database";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
if(isset($sqlArr['columns'])) {
// Because this is dependent on all images being uploaded properly, you
// need more validation in your code. This code inserts no matter what.
$sql="INSERT INTO tableName (nameMember,bandMember,`".implode("`,`",$sqlArr['columns'])."`,aboutMember,otherBands)
VALUES ('$name', '$bandMember',".implode(",",$sqlArr['values']).", '$about', '$bands')" ;
$objQuery = sqlsrv_query($conn, $sql);
sqlsrv_close($conn);
} ?>
EDIT: For further clarification on how to process the post and files try using processing functions that will return an array for use in an sql statement:
FORM:
Add this line in the form:
<td class="td_input_form"><input type="file" name="BidIDFile[]"></td>
PROCESSING:
function ProcessRequest($request = array())
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Create insert values
$insert['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$insert['cols'][] = "`".str_replace("txt","",$key)."`";
// For good measure, create an update string
$insert['update'][] = "`".str_replace("txt","",$key)."`".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$insert['bind']['cols'][] = "`".$key."`";
$insert['bind']['cols_bind'][] = ":".$key;
$insert['bind']['vals'][":".$key] = $value;
$insert['bind']['update'][] = "`".$key.'` = :'.$key;
}
// If there are cols/values return them
if(isset($insert))
return $insert;
}
}
function ProcessFiles($name = 'item',$target = '/uploads')
{
$target = $_SERVER['DOCUMENT_ROOT'].$target;
// Makes the folder if not already made.
if(!is_dir($target))
mkdir($target,0755,true);
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// You need to differentiate your type array names
$use_name = ($name == 'item')? 'photo':$name;
// To start at photo1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $target."/".$file_name)) {
// Format the key values for photo
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = ProcessRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
return $sql;
}
// Process files and post (or array in general)
$sql['post'] = ProcessRequest($_POST);
$sql['file'] = ProcessFiles('item');
$sql['BidIDFile'] = ProcessFiles('BidIDFile');
if(isset($sql['post']['cols']))
$cols[] = implode(",",$sql['post']['cols']);
if(isset($sql['file']['cols']))
$cols[] = implode(",",$sql['file']['cols']);
if(isset($sql['BidIDFile']['cols']))
$cols[] = implode(",",$sql['BidIDFile']['cols']);
if(isset($sql['post']['vals']))
$vals[] = implode(",",$sql['post']['vals']);
if(isset($sql['file']['vals']))
$vals[] = implode(",",$sql['file']['vals']);
if(isset($sql['BidIDFile']['vals']))
$vals[] = implode(",",$sql['BidIDFile']['vals']);
$cols = (isset($cols) && is_array($cols))? implode(",",$cols):"";
$vals = (isset($vals) && is_array($vals))? implode(",",$vals):"";
echo '<pre>';
print_r($sql);
print_r($cols);
print_r($vals);
echo '</pre>';
echo '<br />';
echo "insert into table ($cols) values ($vals)";
Will give you something like (I only put two post key/value pairs, that's why there is only two. In your case there would be a series of pairs):
Array
(
[post] => Array
(
[vals] => Array
(
[0] => 'asdfsda'
[1] => 'sdfsdfsdf'
)
[cols] => Array
(
[0] => `BidType`
[1] => `BidDate`
)
[update] => Array
(
[0] => `BidType` = 'asdfsda'
[1] => `BidDate` = 'sdfsdfsdf'
)
)
[file] => Array
(
[vals] => Array
(
[0] => '2015012203932.jpg'
[1] => 'a1400by1050.jpg'
)
[cols] => Array
(
[0] => `photo1`
[1] => `photo2`
)
[update] => Array
(
[0] => `photo1` = '2015012203932.jpg'
[1] => `photo2` = 'a1400by1050.jpg'
)
)
[BidIDFile] => Array
(
[vals] => Array
(
[0] => '87682315.jpg'
)
[cols] => Array
(
[0] => `BidIDFile`
)
[update] => Array
(
[0] => `BidIDFile` = '87682315.jpg'
)
)
)
insert into table (`BidType`,`BidDate`,`photo1`,`photo2`,`BidIDFile`) values ('','','2015012203932.jpg','a1400by1050.jpg','87682315.jpg')
upload file and save it with original name
try with $_FILES['file']['name']
if ( ($_SERVER['REQUEST_METHOD'] == 'POST') ) {
$tmpfile = $_FILES['file']['tmp_name'];
$filename = $_FILES['file']['name'];
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . $filename;
if(move_uploaded_file($tmpfile, $uploadfile)) {
echo $uploadfile;
}
}
Upload file name in database with rename in PHP
Use $_FILES["file"]["name"]
to get name of uploaded file.
$name = $_FILES["file"]["name"];
Then you can rename file name:
$filename = date('mdhms').$name;
To move the file to your folder:
move_uploaded_file($_FILES['file']['tmp_name'], $folder);
save() with Original name File
Whenever handling file uploads in Laravel Controller, below things can be helpful
public function store(Request $request)
{
//Validate request data if there are other fields as well
// do not include image fields in validation rules
$validatedData = $request->validate($rules, $request->except('image'));
//Check if $request has uploaded file and whether it's a valid file
if($request->hasFile('image') && $request->file('image')->isValid()) {
//Custom name pattern as per application preference
$filename = time() . '.' . $request->file('image')->extension();
//Or - Get the original name of the uploaded file
$filename = $request->file('image')->getClientOriginalName();
//Store the file in desired directory and assign the path to the image field in validated data
$validatedData['image'] = $request->file('image')->storeAs('images', $filename);
}
//Fill the values from validatedData and save the record
$model->fill($validatedData);
$model->save();
}
Unable to save the uploaded file into specific directory
You're almost there.
File file = upFile.getFile();
is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp)
.
Your problem in your code is that you're creating a bunch of files in memory ftemp
and f1
, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1
, also the block where you're doing the setWritable
's). This will make debugging a lot easier.
saving uploaded files in selected directory
The issue has been solved. Here is the solution:
/* upload photos to gallery */
if (isset($_POST['add_photos'])) {
include 'connect.php';
$album = (isset($_POST['album']) ? $_POST['album'] : null);
$errors= array();
foreach($_FILES['photos']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['photos']['name'][$key];
$file_size =$_FILES['photos']['size'][$key];
$file_tmp =$_FILES['photos']['tmp_name'][$key];
$file_type=$_FILES['photos']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
include 'connect.php';
$imageURL = "media/albums/".$file_name;
$stmt = $conn->prepare("INSERT into album_images(imageURL, AlbumID) VALUES (?, ?)");
$stmt->bind_param('ss', $imageURL ,$album);
$desired_dir="../media/albums";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir($desired_dir, 0700); // Create directory if it does not exist
}
if(is_dir($desired_dir."/".$file_name)==false){
move_uploaded_file($file_tmp,"../media/albums/".$file_name);
}else{ //rename the file if another one exist
$new_dir="media/albums/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
$stmt->execute();
$stmt->close();
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
The probme was that I had written user_data rather than media/albums in move_uploaded_file($file_tmp,"../media/albums/".$file_name);
}
Related Topics
Utf-8 Bom Signature in PHP Files
How to Overwrite a Function in PHP
Incorrect Integer (2147483647) Is Inserted into MySQL
Filter Multidimensional Array Based on Partial Match of Search Value
How to Only Allow Certain Filetypes on Upload in PHP
What Is the Best Collation to Use For MySQL With PHP
PHP $_Server['Http_Host'] Vs. $_Server['Server_Name'], Am I Understanding the Man Pages Correctly
Creating PHP Class Instance With a String
How to Prevent Code Injection Attacks in PHP
How to Require a Fork With Composer
PHP: How to Remove Specific Element from an Array
What Type of Hash Does Wordpress Use
Passing JavaScript Array to PHP Through Jquery $.Ajax
Continue PHP Execution After Sending Http Response
Warning: MySQL_Fetch_Array() Expects Parameter 1 to Be Resource, Boolean Given In