How to access file from multipart/form-data [ PHP ] - php

I have a frontend of my application writen in angular which basicly pick the file and send backend file name and rest of the form information:
Frontend part looks like:
$scope.submit = function() {
if ($scope.file) {
$scope.upload($scope.file);
}
};
// upload on file select or drop
$scope.upload = function (file) {
Upload.upload({
url: 'sub.php',
data: {file: file, 'country': $scope.submodelCountry}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + ' uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
My backend is written in PHP:
I basicly access this 2 variabiles by:
$fileName = $_FILES['file']['name']; // value = fileName.csv
$country = $_POST['country']; // value = CZE
So looks my backend get all needed information however I am not able to fopen the file with $file = fopen($fileName,"r");
How can I access this file guys? Or how can I upload it on a server to use it after?

you have to upload the file to some folder, then you can access that,
Your file will be present in tmp directory, so
Use move_uploaded_files(), to move your file,
<?php
$uploads_dir = '/uploads';
if(move_uploaded_file($_FILES["file"]["tmp_name"],
"$uploads_dir/".$_FILES["file"]["file_name"])){
echo "file uploaded";
}
?>

Related

ionic cordovaFileTransfer with api php code error 3

I am developing an application for sharing photos, I used ionic for the mobile part and the php for the backend part. But I have a problem when I upload a file that exceeds 2M.
Thank you very much for your good day.
This is my code:
//PHP backend : upload.php
<?php
header('Access-Control-Allow-Origin: *');
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo "Upload and move success";
} else{
echo $target_path;
echo "There was an error uploading the file, please try again!";
}
header ("Connection: close");
?>
// Ionic js
$scope.selectPicture = function(sourceType) {
var options = {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: sourceType,
saveToPhotoAlbum: false//,
//targetWidth: 800,
//targetHeight: 800
};
$cordovaCamera.getPicture(options).then(function(imagePath) {
// Grab the file name of the photo in the temporary directory
var currentName = imagePath.replace(/^.*[\\\/]/, '');
//Create a new name for the photo
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
// If you are trying to load image from the gallery on Android we need special treatment!
if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) {
window.FilePath.resolveNativePath(imagePath, function(entry) {
window.resolveLocalFileSystemURL(entry, success, fail);
function fail(e) {
console.error('Error: ', e);
}
function success(fileEntry) {
var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1);
// Only copy because of access rights
$cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function(success){
$scope.image = newFileName;
}, function(error){
$scope.showAlert('Error', error.exception);
});
};
}
);
} else {
var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
// Move the file to permanent storage
$cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success){
$scope.image = newFileName;
}, function(error){
$scope.showAlert('Error', error.exception);
});
}
},
function(err){
// Not always an error, maybe cancel was pressed...
})
};
// Returns the local path inside the app for an image
$scope.pathForImage = function(image) {
if (image === null) {
return '';
} else {
return cordova.file.dataDirectory + image;
}
};
$scope.uploadImage = function() {
// Destination URL
var url = "http://myssite.com/upload.php";
// File for Upload
var targetPath = $scope.pathForImage($scope.image);
// File name only
var filename = $scope.image;;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename},
headers : { Connection: "close"}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function (err) {
console.log("ERROR: " + JSON.stringify(err));
}, function (progress) {
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
console.log("progress: " + progress + " dddd "+JSON.stringify(progress));
console.log("mytime "+$scope.downloadProgress);
$scope.progressval = $scope.downloadProgress;
});
});
My Config : upload max file size : 40M
post max size : 40M
this is my error : ERROR: {"code":3,"source":"file:///data/user/0/com.ionicframework.s‌​ample374926/files/14‌​93805852934.jpg","ta‌​rget":"xxxxxx/… end of stream on Connection{xxxx.:80, proxy=DIRECT# hostAddress=xxxxxx cipherSuite=none protocol=http/1.1} (recycle count=0)"}

Move uploaded file fails after ajax request

I know this issue has been tackled a few times but no solution works for me,
I have a javascript function which pulls a file referenced by an which is as follows
function imagePreload(str)
{
var timestamp = new Date().getTime();
str = str + "&timestamp=" + timestamp;
var key = [];
var value = [];
var queriesarray = str.split('&');
for(i = 0; i < queriesarray.length; i++)
{
var pair = queriesarray[i].split('=');
key[i]= pair[0];
value[i]= pair[1];
}
for(i = 0; i < queriesarray.length; i++)
{
if (key[i]=="menu_id") {var menuid = value[i];}
if (key[i]=="menucategories_id") {var catid = value[i];}
}
for(i = 0; i < queriesarray.length; i++)
{
if (value[i]=="business") {var fileurlfield = "uploadbizimageid";}
if (value[i]=="category") {var fileurlfield = "uploadcatimageid" + catid;}
if (value[i]=="item") {var fileurlfield = "uploaditemimageid" + menuid;}
}
var fileInput = document.getElementById(fileurlfield);
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = reader.result;
}
reader.readAsDataURL(file);
} else {
alert("File not supported!");
}
document.getElementById("maskid").style.display = "block";
document.getElementById("imageuploadcontainerid").style.display = "block";
var filetosend = new FormData();
filetosend.append( 'image', file);
$.ajax({
url: "index.php?option=com_jumi&fileid=13&format=raw&" + encodeURI(str),
type: "POST",
data: filetosend,
processData: false,
contentType: false,
error: function (jqXHR, textStatus, errorThrown) {
alert("AJAX error: " + textStatus + ' : ' + errorThrown);
},
success: function(html) {alert("Orwight!");
document.getElementById('imageuploadcontainerid').innerHTML = html;
}
});
}
As you can see it is designed to make an AJAX call to a php file which is supposed to save that image file to a directory on the same webserver running the above function.
The php in that file looks like this.
$rest_id = $_GET['rest_id'];
$menu_id = $_GET['menu_id'];
$menucategories_id = $_GET['menucategories_id'];
$imagetype = $_GET['imagetype'];
if($imagetype=="business")
{
$db = &JFactory::getDBO();
$db->setQuery("SELECT * FROM g56s_restaurants WHERE rest_id = '$rest_id'");
$det = $db->loadObject();
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$target_path = "/images/restaurants/".$rest_id."/";
$target_path = $target_path ."businesslogo.".$ext."";
echo $target_path;
if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
echo "The file ".basename( $_FILES['image']['name'])." has been uploaded";
} else {
echo "Not uploaded because of error #".$_FILES["file"]["error"];
}
}
Every time I call his script, the upload fails and no error is reported (i.e. no error number). A var dump shows that the the file error variable has a value of 0, and the file size is reported to be in the same order as that of the original file, and it has a tmp name. So in other words the file IS there in the TMP directory.
Directory permissions in the directory being written to are 777. There are no cross domain issues (and I guess no CORS issues) since the script is called from the same website (the PHP is actually in a JUMI application in a Joomla 3.4 website). However, the script ALWAYS fails to upload the file (the page returns "/images/restaurants/1/businesslogo.jpgNot uploaded because of error #." (since I also echoed the target_path before the error string echoed).
Does anyone know the reason for this and how to get the script to upload correctly ? I am completely stuck on this issue because as far as I can see, everything should work.
I solved the issue quicker than I thought, it turns out that I also have to specify the document root in the target path, so I amended
$target_path = "/images/restaurants/".$rest_id."/";
as
$target_path = $_SERVER['DOCUMENT_ROOT']."/images/restaurants/".$rest_id."/";
and it now works :-)

Why do I hit error in AJAX file upload with jQuery?

I am working on a multiple file uploader using HTML5's FormData and jQuery. I have the following code:
$(function() {
$('#file').bind("change", function() {
var formData = new FormData();
//loop for add $_FILES["upload"+i] to formData
for (var i = 0, len = document.getElementById('file').files.length; i < len; i++) {
formData.append("file" + i, document.getElementById('file').files[i]);
}
//send formData to server-side
$.ajax({
url : "file-upload.php",
type : 'post',
data : formData,
dataType : 'json',
async : true,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
error : function(request) {
alert('error!!');
console.log(request.responseText);
},
success : function(json) {
alert('success!!');
$('#upload-result')[0].append(json);
}
});
});
});
I can see that my file-upload.php works fine because the files are uploaded! But why does my jQuery hit the error function and not the success function? I get an alert of Error.
In the console window, I see the result of my PHP echo call! Which I want to append to #upload-result as shown in my success function.
PHP code
foreach($_FILES as $index => $file)
{
$fileName = $file['name'];
// echo '[ file name: ' . $fileName . ' - ';
$fileTempName = $file['tmp_name'];
// echo 'file temp name: ' . $fileTempName . ' ]';
if(!empty($file['error'][$index]))
{
// some error occured with the file in index $index
// yield an error here
return false; // return false also immediately perhaps??
}
// check whether it's not empty, and whether it indeed is an uploaded file
if(!empty($fileTempName) && is_uploaded_file($fileTempName))
{
// the path to the actual uploaded file is in $_FILES[ 'file' ][ 'tmp_name' ][ $index ]
// do something with it:
move_uploaded_file($fileTempName, "uploads/" . $fileName);
echo json_encode('<p>Click here to download file!</p>');
}
}
I figured it out. I was getting the jQuery AJAX error even though my status code was 200 for the php file because I had my dataType as JSON, whilst I was returning simple HTML.
dataType: 'html',
Fixed it!
Thanks all.

uploading file using ajax - echo from PHP tells that file is uploaded, but file is not there

Hello I am trying to get to work this piece of code:
I am trying to build intelligent images uploader, that will care about the html 5 multiple selection bug (or feature as someone can say) which will delete "previous files" when I decide to select few extra. Also it has some primitive approach to permit user selecting file that was selected previously.
This part works fine, I am seeing images previews and also echoing "file" into console corresponds to number of files.
What is strange is return (echo) from PHP script which says that file is in /tmp directory and also size is correct, but file don't get moved.
I checked permissions and set uploaded folder to "lucky" 777.
I checked /tmp folder and file is no there but PHP script is saying taht is here.
I know about that you can't set , it is logical why you can't, but should echo from PHP script shows size and tmp location of this file then if this is a issue ?
code here:
var noveSub = [];
var noveSubMeno = [];
var noveSubVelkost = [];
function samotnyUpload() {
var fd = new FormData();
fd.append('upload', noveSub[0]);
// trying just first file for testing
$.ajax({
url: '/upload/upload.php',
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
}
function pridatSubory() {
$("li.pridaj").click(function() {
$("input").trigger("click");
});
function pushniNovy(subor) {
noveSub.push(subor);
noveSubMeno.push(subor.name);
noveSubVelkost.push(subor.size);
previewNovy(subor);
}
function previewNovy(subor) {
var li = document.createElement("li");
var img = document.createElement("img");
img.file = subor;
li.appendChild(img);
$(li).insertBefore("li.pridaj");
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(subor);
}
var inputElement = document.getElementById("vyberSubor");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
var sub = this.files;
for (i=0; i<sub.length; i++) {
pos = noveSubMeno.indexOf(sub[i].name);
if (pos !== -1) {
if (noveSubVelkost[pos] !== sub[i].size) {
pushniNovy(sub[i]);
}
} else {
pushniNovy(sub[i]);
}
}
}
PHP FILE :
<?php
if ($_FILES["upload"]["error"] > 0)
{
echo "Error: " . $_FILES["upload"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["upload"]["name"] . "<br>";
echo "Type: " . $_FILES["upload"]["type"] . "<br>";
echo "Size: " . ($_FILES["upload"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["upload"]["tmp_name"];
echo "<br><br>";
echo move_uploaded_file($_FILES["upload"]["tmp_name"], "upload/".$_FILES["file"]["name"]);
}
?>
OUTPUT FROM PHP FILE in console:
Upload: erb128.png<br>Type: image/png<br>Size: 4.734375 kB<br>Stored in: /tmp/phpdTy053<br><br>
It may actually be a syntax problem. You're mixing strings and variables in your move_uploaded_file call. Try this instead:
$destination = "upload/".$_FILES["file"]["name"];
$result = move_uploaded_file($_FILES["upload"]["tmp_name"], $destination);
echo $result;
I rethink this approach. to use PUT for upload. I have read that some benefits are:
small memory footprint even if You are uploading very big files
and also saw scripts that are able to pause upload.
changes to code (only draft):
var xhr = new XMLHttpRequest();
function samotnyUpload() {
xhr.open("put", "http://pingpong.local/upload/upload.php", true);
xhr.setRequestHeader("X-File-Name", noveSubMeno[0]);
xhr.setRequestHeader("X-File-Size", noveSubVelkost[0]);
xhr.send(noveSub[0]);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
}
and PHP script:
<?php
$filename = $_SERVER['HTTP_X_FILE_NAME'];
echo $filename;
$filesize = $_SERVER['HTTP_X_FILE_SIZE'];
echo $filesize;
$in = fopen('php://input','r');
$tmp = fopen('tempfile.ext','w');
while($data = fread($in, 1024)) fwrite($tmp, $data);
fclose($in);
fclose($tmp);
?>

PHP can't pick up file

I've been trying to create a registration form that requires students to upload documents at the very end. However, after picking up the form values via jQuery, the PHP document can't seem to pick up my uploaded form. Any ideas?
Form:
<form id="joinUs" enctype="multipart/form-data" method="post">
<!--various form fields-->
<input type="file" name="transcript" id="transcript">
<div class="button" id="submit">Submit!</div>
</form>
jQuery:
$("#submit").click(function(){
//firstName, lastName, grade, studentID, email, phone are all form values
var data = "firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;
$.ajax({
type: "POST",
url: "join_submit.php",
data: data,
success: function() {
location.href="http://mvcsf.com/new/success.php";
}
});
join_submit.php
$allowedExtensions = array("pdf");
$max_filesize = 20000;
$upload_path = "docs/transcripts";
$filename = $_FILES["transcript"]["name"];
$filesize = $_FILES["transcript"]["size"];
$extension = $_FILES["transcript"]["type"];
if ($_FILES["transcript"]["error"] > 0) {
echo "Error: " . $_FILES["transcript"]["error"] . "<br />";
}
else if((in_array($extension, $allowedExtensions)) && ($filesize < $max_filesize)) {
move_uploaded_file($_FILES["transcript"]["tmp_name"], $upload_path . $filename);
}
I ran this, and I got no errors. I also tried to print out the file name, except nothing printed out.
This should do it for you :
$("#submit").click(function () {
var transcript = $("#transcript").val();
var data = "firstName=" + firstName + "&lastName=" + lastName + "&grade=" + grade + "&studentID=" + studentID + "&email=" + email + "&phone=" + phone;
var formData = new FormData();
formData.append("file", transcript);
formData.append("data", data);
$.ajax({
type: "POST",
url: "join_submit.php",
enctype: 'multipart/form-data',//optional
cache: false,
contentType: false,
processData: false,
data: {
file: file
data: data
},
success: function () {
location.href = "http://mvcsf.com/new/success.php";
}
});
});
Cheers
First, In your code, you are posting data with $.ajax({...}) and the data sent is
"firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;
There is no transcript at all.
Secondly, and most important, you cannot post file with $.ajax({...}) like that, it will not working like that. As #Roy M J says, you should take a look at FormData (for recent browser only), or take a look on the web for an upload jQuery plugin (don't re-invent the whell, some good plugin already exists :))
Take a look here
You cannot send a file like you do the values of HTML elements. There are two methods to file upload, the one I've used successfully is the AJAX method using a third-party feature called 'AjaxUploader'.You can download it here via GitHub. Once you've done it, add the ajaxuploader.js file in your 'js' folder (or wherever you've put all of your script files), include the file in the HTML page where you've to use the uploader. Now, uploading is as simple as follows.
HTML:
<input type="file" name="transcriptUploader" id="transcriptUploader" value="Upload" />
jQuery (you need to have the jQuery file included in your page):
new AjaxUpload('transcriptUploader', {
action: "page_to_handle_upload.php", // You need to have either a separate PHP page to handle upload or a separate function. Link to either one of them here
name: 'file',
onSubmit: function(file, extension) {
// This function will execute once a user has submitted the uploaded file. You can use it to display a loader or a message that the file is being uploaded.
},
onComplete: function(file, response) {
// This function will execute once your file has been uploaded successfully.
var data = $.parseJSON(response); // Parsing the returning response from JSON.
if(data.error == 0)
{
// If the file uploaded successfully.
}
else if(data.error == "size"){
// If the response object sent 'size' as the error. It means the file size exceeds the size specified in the code.
}
else if(data.error == "type"){
// If the response object sent 'type' as the error. It means the file type is not of that specified in the code (in your case, pdf).
}
else{
// In case the file didn't upload successfully or the code didn't return a usual error code. It is still an error so you need to deal with it appropriately.
}
}
});
Your back-end PHP code that will be doing all the heavy lifting (uploading the file, checking extensions, moving it etc):
if(isset($_FILES)) // Checking if a file is posted.
{
if ($_FILES['file']['error'] == 0) //Checking if file array contain 0 as an error. It means AJAX had no error posting the file.
{
$response = array(); // Initializing a new array.
$allowedExts = array("pdf"); // Allowable file format.
$filename = stripslashes($_FILES['file']['name']); // Storing file name.
//$extension = strtolower(self::_getExtension($filename)); // Fetching file extension.
// Code block to extract file extension and storing it in a variable called $extraction.
$i = strrpos($str, ".");
if (!$i)
{
$extension = "";
}
$l = strlen($str) - $i;
$extension = strlower(substr($str, $i + 1, $l));
$size = $_FILES['file']['size']; // Storing file size (in bytes).
$fileNameAfterUpload = md5((time() + microtime())) . '.' . $extension; // Concatinating file name and extension.
$baseSystemPath = "/var/www/<your_folder_name>/uploaded_transcripts/" // Path on which the file will be uploaded. Need to be relative web path.
$maxSize = 10*10*1024; // Storing file size. Be advised the file size is in bytes, so this calculation means max file size will be 10 MB.
$webPath = "uploaded_transcripts/". $filename; // Creating web path by concatinating base web path (the folder in which you'd be uploading the pdf files to) with file name.
if (in_array($extension, $allowedExts)) // Checking if file contains allowabale extensions.
{
if($size <= $maxSize) // Checking if the size of file is less than and equal to the maximum allowable upload size.
{
$moved = move_uploaded_file($_FILES['file']['tmp_name'], $webPath); // Moving the file to the path specified in $webPath variable.
if($moved == true)
{
$response['error'] = 0; // If moved successfully, storing 0 in the response array.
$response['path'] = $webPath; // Storing web path as path in the response array.
$response['filename'] = $filename; // Storing file name in the response array.
}
else
{
$response['error'] = 'internal'; // If move isn't successfull, return 'internal' to AJAX.
}
}
else
{
$response['error'] = 'size'; // If file size is too small or large, return 'size' to AJAX.
}
}
else
{
$response['error'] = 'type'; // If file type is not that of defined, return 'type' to AJAX.
}
echo json_encode($response); // Returning the response in JSON format to AJAX.
}
}
Do let me know if you need further assistance.
P.S: Don't forget to mark it as an answer if it worked.

Categories