Can I add a base64 image to the $_FILES array? - php

Is there a way to add a base64 image string to the $_FILES array (the array that you get when you upload a file)? Basically, I want to fake a file upload from a base64 string. The base64 string comes from an email attachment. I don’t wish to use file_get_contents(), because I want to save the image in a database as a binary image. I don’t need to upload it, as such, but I do need it be a part of the $_FILES array.

Uploading is a way of sending the contents of a file from a client (usually a web browser) to a server. It sounds like you've already got the data you need on the server (in PHP), so you don't need to upload it.
You can use base64_decode() to convert it from base64 to the straight file contents.
If you need it as a file on your server, you can use something like file_put_contents() to save it as a new file.
If you're trying to do something else with the uploaded file in the $_FILE array, please provide more details. Whatever it is, you don't need to actually upload the file.
The $_FILES array doesn't actually contain the contents of the file - it contains a filename where the contents have been saved.
If you must use the $_FILES array (in order to re-use an existing class, for example), you'll need to use file_put_contents() to save a new temporary file, and then manually add an entry the the $_FILES array pointing to that temporary file (Just like modifying any other array). Don't forget to delete your temporary file when you're done - this is normally handled automatically by PHP, but if you create the file manually, you'll have to delete it manually too.
I'd highly recommend refactoring or providing an alternate interface to your class instead though. You shouldn't have to pretend that the file was uploaded just to save it to the database.

index.php
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
/* Simple */
function previewImage( image, preview, string )
{
var fileImage = image.files[0];
var preview = document.querySelector( preview );
var reader = new FileReader();
reader.addEventListener( "load", function() {
preview.style.height = "100";
preview.title = fileImage.name;
// convert image file to base64 string
preview.src = this.result;
/* --- */
document.querySelector( string ).value = this.result;
}, false );
if ( fileImage )
{
reader.readAsDataURL( fileImage );
}
}
document.querySelector( "#imageID" ).addEventListener( "change", function() {
previewImage( this, "#imagePreviewID", "#imageStringID" );
} )
/* Simple || */
<form method="post" action="process.php" >
Title: <input type="text" name="title" /><br />
File Upload: <input type="file" name="image" id="imageID" /><br />
Preview: <img src="#" id="imagePreviewID" /><br />
String base64: <textarea name="imageString" id="imageStringID" rows="10" cols="50" readonly="readonly" ></textarea>
<hr />
<input type="submit" name="submit" value="Submit" />
</form>
process.php
<?php
$data = array(
"post" => $_POST,
"files" => $_FILES
);
echo "<pre>";
// echo json_encode($data);
var_dump($data);
?>
<img src="<?= $_POST['imageString']; ?>" />
repl.it

Related

How to process multiple files separately

I have an idea and would like to try it out. I am using a cool tool called cropit. I need to upload multiple images, crop them automatically and save them on the server side. Unfortunately I can process only one image at a time and I have 12 separate fields for the upload and preview. The current code for the 5th image for example looks like this:
HTML:
<div id="image-cropper5">
<!-- This is where user selects new image -->
<label> Upload Photo <input type="file" class="cropit-image-input"/></label>
<!-- This is where the preview image is displayed -->
<label><div class="cropit-preview"></div></label>
<!-- This is the confirmation -->
<button type="button" id="image5pick" disabled>OK</button>
</div>
JQuery:
$('#image-cropper5').cropit();
$('#image5pick').click(function() {
var imageData5 = $('#image-cropper5').cropit('exportZoom', 3);
imageData5 = $('#image-cropper5').cropit('export');
$.post('php/upload.php', { imageData5: imageData5 }, function() { $('#image5pick').data('clicked', true) })
});
PHP:
$imageData5 = $_POST["imageData5"];
if ($_POST["imageData5"]){
$decoded = $imageData5;
$exp = explode(',', $decoded);
$base64 = array_pop($exp);
$data = base64_decode($base64);
$file = "data5.png";
file_put_contents($file, $data);
}
What I want to try out is to upload multiple images via <input name="photos[]" type="file" class="multiupload" multiple/>, take every image from the array and process every image automatically and separately through the codes (also without the "OK" confirmation, just process as soon as the preview comes on).
So the first question here: How do I take the files seperately to the jquery code?

File upload php, get only file name

Is it possible to get the filename of a file, without a complete upload
Meaning after the user chose a file, dont upload that file, just get the filename and save to database?
yes it is possible you can use the code as given below
$filename=$_FILES['nameofyourfileinput']['name'];
echo $filename;
you can echo the $filename;
OR You can use jquery to get this value like
$('#inputid').change(function(){
var value =$(this).val();
alert(value);
})
ya it is possible.You can also do this before uploading the file basename() is enough for extracting name.
$next=$pfet['f_name']; //fetched file from database
$next1 = basename($next);
The accepted answer doesn't prevent the file upload, it simply provides a way to get the file name independent of the file contents.
Preventing file upload, is best looked at the other way: what enables uploading a file. The answer to that is the enctype attribute on the form tag (multipart/form-data).
HTML:
<form action="upload.php" method="post" enctype="application/x-www-form-urlencoded">
Select:
<input name="upload[]" type="file" multiple="multiple" />
<input type="submit" value="Update" name="submit">
</form>
PHP:
$total = count($_POST['upload']);
// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {
$fileName = $_POST['upload'][$i];
}

How i can receive the name of an image searched in html file object

Image of File Object: http://imgur.com/8USsHud
HTML of File Object:
<input type="file" name="file" id="file">
I want to receive the name of the image that i search in file object. In that image i want to receive Practidose.fw.png
I try to do this:
$imagem = mysql_escape_string($_POST['file']);
And i receive this error:
Undefined index on line 113
And i dont receive the name of the image
You should use $_FILE to get your file instead of $_POST. Check this link for more information.
$filename = $_FILE['file']['name'];
// name of the image is now in the variable $filename
use the correct file array of php.
Use this
$imagem = mysql_escape_string($_POST['file']['name'); instead of
$imagem = mysql_escape_string($_POST['file']);

PHP: multiple files upload without ajax

I want any php script which can demonstrate me how to upload multiple files in PHP. In my application I have given a link "Add Image" & 'Remove Image', on click of "Add Image" I am adding a new upload field on the page using javascript, using which user can upload more and more images, no limit on number of images for now. On click of delete i am removing that element.
I am just not getting the concept on how to process them in the POST request in PHP. I know in HTML if we give the name of field like myimages[] then it will create a PHP array, but how to process this.
I don't want to use AJAX/JavaScript for uploading, want to do it with traditional POST request in PHP.
If anyone have any link or code which shows such functionality, then pleas provide it will be really helpful.
Thanks!
combine this uploading multiple files & move_uploaded_file
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
$uploads_dir = '/uploads';
foreach ($_FILES["userfile"]["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["userfile"]["tmp_name"][$key];
$name = $_FILES["userfile"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Uploaded files are not in the POST array, they are in the FILES array.
http://www.php.net/manual/en/features.file-upload.multiple.php
The files are uploaded to a temp area with "safe" names. The array will contain the name of the file and the tmp file. You can then move them to where you want.
Name file input fields as file[] in HTML, then just run a loop from 0 do count($_FILES) in PHP...
for($i = 0; $i < count($_FILES['file']['tmp_name']); $i++){
$tmp = $_FILES['file']['tmp_name'][$i];
$name = md5(microtime());
if(move_uploaded_file($tmp, "dir/$name.jpg")){
echo "File '$tmp' uploaded successfully";
}else{
echo "Uploading '$tmp' failed";
}
}
I've implemented something similar in the past as follows:
Have a hidden JavaScript form variable (e.g.: "numuploads") that stores the number of file inputs currently in the form. This will need to be incremented/decremented when you add/remove an input on the front end.
Name each of the inputs on the front end using a pattern such as "upload_X", where X is the next in the sequence. (Effectively the same as the counter above -1.)
On the PHP landing page, simply scan the $_FILES superglobal, looking for each "upload_X" where X is zero thru numuploads - 1.
You can then carry out the required logic for each of the uploaded files, other form elements, etc.

How to upload multiple files in PHP

All the scripts I have found via Google search rely on some sort of screen that first asks the user how many files they need to upload and the upload script works based on that number.
But what if I don't want any limits, but want to allow the user to upload as many or as few as they want. How to go about this?
All I have for now is the form:
<form enctype="multipart/form-data" method="post" action="script.php">
<input id="my_file_element" type="file" name="myFile[]" >
<input type="submit" value="Upload!" name="submit">
</form>
EDIT
I think the way I phrased my question is causing some misunderstanding. I am not in need of some way to add more "input type = file" field elements. I am already using a javascript that enables the user to add more form fields by clicking a button, those other fields are identical to the 1st one posted above.
What I am asking this question for, is to know how to handle the actual upload of files to the server using a php script.
EDIT
Let's say your form is like this
<form enctype="multipart/form-data" method="post" action="script.php">
<input id="my_file_element" type="file" name="myFile[]" >
<input id="my_file_element" type="file" name="myFile[]" >
<input id="my_file_element" type="file" name="myFile[]" >
etc...
<input type="submit" value="Upload!" name="submit">
</form>
What you want to do is get all the files called myFile[]. Here's what you do in PHP:
foreach ($_FILES["myFile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["myFile"]["tmp_name"][$key];
$name = $_FILES["myFile"]["name"][$key];
// here we move it to a directory called data
// you can move it wherever you want
move_uploaded_file($tmp_name, "data/$name");
} else {
// an error occurred, handle it here
}
}
ORIGINAL
Using HTML and JavaScript alone, there isn't any easy way to upload multiple files at the same time.
I would use a Flash library, such as SWFUpload, to do the upload instead. Using this plugin, you can show a standard multi-file upload window, as shown in this demo. This will allow users to easily select multiple files in the same file browser.
If you don't want to use Flash for some reason, you could use JavaScript to dynamically swap input elements, as in this example.
EDIT
That depends on how you called the file input elements. If you followed my approach below, you can get the number of files with:
if (empty($_FILES['attach']['name']))
$count_files = 0;
else
$count_files = count($_FILES['attach']['name']);
Try var_dump($_FILES) to see the complete $_FILES array, in case you have any doubts on its structure.
ORIGINAL
Something like this, with Javascript:
<script type="text/javascript">
var j = 2; //default two files
function novoa() {
j = j+1;
var elem = document.createElement("input");
var par = document.getElementById("filed");
elem.setAttribute("type", "file");
elem.name = "attach[]";
elem.id = "file_" + j;
par.appendChild(elem);
}
function delult() {
if (j == 0) return;
var elem = document.getElementById("file_" + j);
var par = document.getElementById("filed");
j = j-1;
par.removeChild(elem);
}
</script>
...
<p id="addupl">More files |
Less files</p>
<p id="filed">
<input type="file" name="attach[]" id="file_1" />
<input type="file" name="attach[]" id="file_2" />
</p>
OMG you're asking how to handle this form?
there is an example right on the manual page:
http://www.php.net/manual/en/features.file-upload.post-method.php
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
?>
In your PHP script, do a var_dump($_FILES). The output should help you move further into the direction you wish. Take a look at PHP's filesystem functions for more info on what you can do with the files, after using the move_uploaded_file function.
In order to really answer your question How to handle the upload, you'd need to tell us what you want to accomplish/do with the files.
Just use JavaScript to append another input element to the form.

Categories