So, I recently looked up how to upload files onto a database using Blob. This is the tutorial I found http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx
I followed this tutorial and came up with this code -
HTML FORM -
<form action='memberPage.php' method='post' enctype='multipart/form-data'>
<input type='text' name='programName' placeholder='Program Name'></input>
<input type='text' name='programPrice' placeholder='Price'></input>
<div id='uploadFiles'>
<input name='userfile1' type='file' onchange='addAnother()'>
</div>
<input type='submit' value='Create program' style='cursor:pointer;'></input>
</form>
PHP UPLOAD ($programName is specified outside code it looks something like $programName=$_POST["programName"];)
for($i = 1; $i < 999;$i++){
if(isset($_POST["userfile" . $i]) && $_FILES["userfile" . $i]['size'] > 0){
$Filename = $_FILES["userfile" . $i]['name'];
$finfo = new finfo();
$Filetype = $finfo->file($_FILES["userfile" . $i]['tmp_name'], FILEINFO_MIME);
$Filesize = $_FILES["userfile" . $i]['size'];
$Filetmpname = $_FILES["userfile" . $i]['tmp_name'];
$Fileerror = $_FILES["userfile" . $i]['error'];
$fp = fopen($Filetmpname, 'r');
$content = fread($fp, filesize($Filetmpname));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$Filename = addslashes($Filename);
}
mysqli_query($conn, "INSERT INTO upload(name,type,size,content,program) VALUES('
'" . $Filename. "','" . $Filetype. "','" . $Filesize . "','" . $content . "','" . $programName . "')");
}else{
$i=999;
header("location:memberPage.php");
}
}
But when I submit the forum, the files return with nothing in them, no name, and the size is zero.
I have also checked out the other question things on here and did not find the answer, so my guess is that it is in my code.
Let me also specify that the onchange='addAnother()' adds another input, but has the next end number on it (Example - userfile1, it would then add userfile2)
you are using input name "programName" and try to get "Programname" the same with $_POST.
PHP is case sensitive you should use same case in PHP "$_POST['programName']"
We need to check file element istead of post element.
Try changing this
if(isset($_POST["userfile" . $i]) && $_FILES["userfile" . $i]['size'] > 0){
to this
if(isset($_FILES["userfile" . $i]) && $_FILES["userfile" . $i]['size'] > 0){
It would be better to create the input names as arrays.
<input name='userfile[]' type='file' onchange='addAnother()'>
and iterate through it in php like:
if (isset($_FILES["userfile"]) && is_array($_FILES["userfile"])) {
for ($i=0;$i<count($_FILES["userfile"]);$i++) {
echo $_FILES["userfile"]["name"][$i];
}
}
Related
I tried to store the image in DB along with some other data in another table ,but I get
"message": "Undefined variable $filenameA"
//for picture refrences
if (!empty($request->picture_a)) {
$fileA = $request->file('picture_a');
$extensionA = $fileA->getClientOriginalExtension();
$filenameA = 'picture_a' . '_' . time() . '.' . $extensionA;
$fileA->storeAs('uploads/picture_refrences', $filenameA);
$data['picture_a'] = 'public/uploads/' . $filenameA;
}
if (!empty($request->picture_b)) {
$fileB = $request->file('picture_b');
$extensionB = $fileB->getClientOriginalExtension();
$filenameB = 'picture_b' . '_' . time() . '.' . $extensionB;
$fileB->storeAs('uploads/picture_refrences', $filenameB);
$data['picture_b'] = 'public/uploads/' . $filenameB;
}
if (!empty($request->picture_c)) {
$fileC = $request->file('picture_c');
$extensionC = $fileC->getClientOriginalExtension();
$filenameC = 'picture_c' . '_' . time() . '.' . $extensionC;
$fileC->storeAs('uploads/picture_refrences', $filenameC);
$data['picture_c'] = 'public/uploads/' . $filenameC;
}
This is what I used and it was working when I used it to store in public directory now since I tried to store in storage it does not upload images
enter image description here
you can use this code, it is working and tested
$image = $request->file('picture_a');
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imageName = $currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
if (!file_exists('uploads/photos')){
mkdir('uploads/photos',0777,true);
}
$image->move('uploads/photos',$imageName);
}
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 ..... ";
}
}
}
So I'm currently working on a php script which should be able to download a file and log the command in an xml file called "log.xml".
I'm using the command "fwrite()" but the message being logged is a double of the message I want logged.
Please take a look:
function executeCommand($v, $m) {
if($v == "fetchResult") {
$filename = "../userFiles/accounts/" . $m . "/log.xml";
$msg = "<retrieve command='fetchResult' date='" . date("d") . "." . date("m") . "." . date("y") . "' />";
$file = fopen( $filename, "a+" );
if( $file == false ) {
echo ( "Error in opening new file" );
exit();
}
else {
fwrite($file,$msg . "\n");
}
fclose($file);
$path01 = "../userFiles/accounts/" . $m . "/result.xml";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;'.'filename="result.xml"');
echo file_get_contents($path01);
}
}
Instead of writing :
<retrieve command='fetchResult' date='27.07.2016' />
for instance,
It's writing :
<retrieve command='fetchResult' date='27.07.2016' />
<retrieve command='fetchResult' date='27.07.2016' />
This would lead to a set of errors if I launch my work so please I'll appreciate a lot if you can help.
Thanks :)
When a user submits the form they enter a ref number and can upload up to 3 documents.
When they submit, i want the document to be saved in the folder structure like so:
docs/
12345/1/file.jpg
12345/2/file.jpg
anotherfile.jpg
27635/1/afile.png
anotherfile.png
thirdfile.jpg
34827/1/onefile.jpg
Okay so you get the idea, when a user uploads a file, it makes a new folder inside docs/ with their reference number then makes another folder called 1/with the files. if the user then uploads again with the same reference it will create a folder inside their reference with the next number up containing their files.
HTML:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="text" name="reference"/><br/>
<input type="file" name="pictures[]" /><br/>
<input type="file" name="pictures[]" /><br/>
<input type="file" name="pictures[]" /><br/>
<input type="submit" value="Send" />
</form>
PHP:
<?php
$target_dir = "docs/";
$ref = $_POST['reference'];
if(!file_exists($target_dir . $ref . '/')){
mkdir($target_dir . $ref . "/1/");
$count = 0;
}else{
//count the amount of folders inside docs/$ref/
$find_folders = glob($target_dir . $ref . "/*",GLOB_ONLYDIR);
$count = count($find_folders);
//create new folder inside $ref/ using count+1 to make the folder increase by 1
$new_folder = $count +1;
mkdir($target_dir . $ref . "/" . $new_folder . "/");
}
//If count exists then the $target_file changes to the new folder
if($count > 0){
$target_file = $target_dir . $ref . $new_folder . "/";
}else{//else use first directory
$target_file = $target_dir . $ref ."/1/";
}
foreach ($_FILES["pictures"]["name"] as $key => $Name)
{
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, $target_file . "$name");
}
?>
When i try all i get is the error:
Warning: mkdir(): No such file or directory in C:\wamp\www\test\upload.php on line 8
arning: move_uploaded_file(docs/123/1/1.png): failed to open stream: No such file or directory in C:\wamp\www\test\upload.php on line 32
Warning: move_uploaded_file(): Unable to move 'C:\wamp\tmp\php2E4E.tmp' to 'docs/123/1/1.png' in C:\wamp\www\test\upload.php on line 32
Any ideas on this? i'm just scratching my head over this one
I see 2 problems.
First, as you are working with windows you need to use \ instead of / as directory separator. Best if you use the php constant DIRECTORY_SEPARATOR.
Second, in order to recursively create directories, you need the third parameter of mkdir like so
mkdir($mypath,0777,TRUE);
Putting that together you should get something like this:
$target_dir = "docs".DIRECTORY_SEPARATOR;
$ref = $_POST['reference'];
if(!file_exists($target_dir . $ref . DIRECTORY_SEPARATOR)){
mkdir($target_dir . $ref . DIRECTORY_SEPARATOR . "1" . DIRECTORY_SEPARATOR, 0777, true);
$count = 0;
}else{
//count the amount of folders inside docs/$ref/
$find_folders = glob($target_dir . $ref . DIRECTORY_SEPARATOR . "*",GLOB_ONLYDIR);
$count = count($find_folders);
//create new folder inside $ref/ using count+1 to make the folder increase by 1
$new_folder = $count +1;
mkdir($target_dir . $ref . DIRECTORY_SEPARATOR . $new_folder . DIRECTORY_SEPARATOR, 0777, true);
}
//If count exists then the $target_file changes to the new folder
if($count > 0){
$target_file = $target_dir . $ref . DIRECTORY_SEPARATOR . $new_folder . DIRECTORY_SEPARATOR;
}else{//else use first directory
$target_file = $target_dir . $ref . DIRECTORY_SEPARATOR . "1" . DIRECTORY_SEPARATOR;
}
I want to find out what the filessize of this file is filesize().
With an echo it works:
$Data[textfile]; = Complete Filename with ending in Database
echo 'http://myurl.com/files/'.$Data[id].'/'.$Data[textFile].'';
But it doesn´t work like this:
$file = "http://myurl.com/files/" . $Data[id] . "/" . $Data[textFile] . "";
The link looks/should look like this:
http://myurl.com/files/123/textfile.docx
edit: sorry for my weird english...i hope the point is clear
Edit 2: I want to get the filesize of a pdf or docx
The rest of the code:
$size = filesize($file);
$size = $size/1048576;
$size = round($size,2);
echo $size." Mb";
try $file = 'http://myurl.com/files/' . $Data['id'] . '/' . $Data['textFile'];
Try:
$file = 'http://myurl.com/files/' . $Data[id] . '/' . $Data[textFile];
try $file = 'http://myurl.com/files/'.$Data[id].'/'.$Data[textFile];