Why is my $_FILES empty given the following code? - javascript

In my frontend PHP page I have a simple upload file input object:
<input type="file" v-on:change="fileAdded">
My fileAdded function within my JS file simply takes the event object (e) and grabs the file in order to obtain other information regarding the file itself:
if (e.target.files !== undefined) {
v.data_file = e.target.files[0]
}
I then put the data file and a request code into a fetch statement to my backend:
fetch("pages/gp/gpBackend.php", {
method: "POST",
body: v.form_data_obj
})
Within my backend php page I use the $_FILES array to grab information like the filename and extension of the file to then pass along to a python script that I have which will unpack the data in the file itself.
During this phase of operation of my webpage, everything works fine, I send the response back to my frontend, handle the data accordingly and move on.
The rest of my frontend requires the user to input certain data before submitting a second post back to my backend with a different request code.
In that instance I send another FormObject with all the needed data to my backend in the same manner I did with my file upload POST. However this time my $_FILES is now empty and I cannot access the file name or extension of the file I uploaded earlier.
I cannot seem to find out why this is the case? I have a near identical set up on another frontend/backend php page I have for the same site that through both POSTS maintains the files in $_FILES to be used however often it is needed. But for this page, without me being able to tell the difference, when I POST another request to my backend the second time $_FILES is empty.
I can provide any additional details that would be needed to answer this question so please let me know. I do know it is not a file size issue as not only do I have the .ini configured for an admin (me) set file size limit, but the file I'm currently using as an example during development is significantly smaller than the max file size on my web server.
Thank you for any help anyone can provide!

PHP $_FILE must serve with a with enctype as this way.
<form action="upload.php" method="post" enctype="multipart/form-data">
Hope this help: https://www.w3schools.com/php/php_file_upload.asp

Related

Adding a string(content) as a file to a html form using JavaScript

I'm looking for a way to add a string as a file inside a html form using JavaScript.
Now I know about the security issues the browsers have when it comes to files, but I'm not looking for adding a file path (as happens when you click the browse of a file input)!!
I want to add a string as a file (The server I'm hitting expects the post to include a file and not a simple form entry).
I know how to perform the action using the FormData object, but I don't want to generate a xhr(ajax) post. I need the post to be a simple form post since the server responds with a redirection.
Does anyone have an idea about this?

Set image uploader field using php

I am trying to save user data while on later i give the option to user to see his unsaved work.I got all the data but image upload file is missing.I i am trying to save file field like this in DB :
$files = $_FILES;
$__fields['file'] = json_encode($files);
Then i save this field to DB.I tried to set the file field like this but no luck.
$files = json_decode($row['file']);
jQuery('#myimg'). val('<?php echo $files->name;?>');
what i am doing wrong ? I want that when customer see his unsaved data the file field is filled like he leaved it.Only file field is creating issue for me.Thanks
When a user unsaved a file means he doesn't uploaded to your server. the file is being in his local computer.
And Its not possible to take that it from php side. unless you upload the file.
Do one thing when the user select file then upload it to your server and keep it in a temporary place and then do your job.
hope this helps
As per the documentation, $_FILES is an associative array of items uploaded to the current script via the HTTP POST method. See manual
What you need to do;
Grab the contents of $_FILES on the initial HTTP POST.
Validate the image
Save the image to your server
Store the location of the saved image in the database, to be read later
OR
Use a 3rd party API
http://api.imgur.com/
See http://www.w3schools.com/php/php_file_upload.asp
(sorry for a w3schools link)

File Reading in PHP

I want to access url of file which user select through pop up file directory navigation window. My browse button tag is:
<input type="file" id="loadFile"/>
On the back end, i can access the file url in javascript, but not sure how to do it in PHP.
You have to have the correct enctype for the form.
Otherwise, you utilize the $_FILES super global.
This is covered extensively in the PHP Manual regarding uploads.
The original filename is available in $_FILES['load file']['name']
Since it seems that you actually want a way to have the user provide a url to a file, the way to handle that is to simply implement a text input and accept the url there, and process the url on the server, using an HTTP client that fetches and stores the file on the user's behalf.
For years people have been using the curl extension, which is fast and highly functional. There are also a number of client libraries written in php like Guzzle.

Creating a smart remote upload script with jQuery AJAX and PHP

I'm currently creating an image hosting script and so far so good. I've used several plugins to create the local uploading process with drag & drog + AJAX which works totally fine. Now I've moved to the part where I need to create the remote uploading process with jQuery AJAX and a PHP script to handle the whole thing.
How it's gonna work
My thought are like this: There is a big box in the middle of the page that accepts the URLs to be remote uploaded. Once valid URL(s) are passed into the text area, they will be immediately sent to the server side script via jQuery AJAX. It's bound with a keyup event.
This is how it looks like: http://i.imgur.com/NhkLKii.png.
The "HERE COME THE URLS" part is already a text area - So that part's already done.
Where I need help
The issue with this whole situation is: Once there are valid URLs pasted into the text area, those must be immediately be converted to some sort of box which also includes an uploading progress. Something that looks like this (copied from the local uploading part): http://i.imgur.com/q7RyDmb.png
It was easy implement the progress indicator for the local uploading, since it was a feature offered by the plugin I've used, but I don't know how to indicate the progress of remote uploading, which is totally being made from scratch.
So this is how I've imagined the logic to flow:
User pastes some URLs into the text area
There is a client-side check to validate the pasted URLs
Validated URLs are send to upload.php on keyup (?)
URLs are being processed
While the upload goes on, we show the users the progress in the knob (?)
PHP script finishes the process and returns back the uploaded URLs
I update the page in the AJAX success callback to display the uploaded files
So, the two process flows marked with (?) are unclear to me - I don't know how to achieve those...
What I have tried
Well, I didn't just come here and ask you to do everything for me, but I've come across a dead end and I don't know how to continue. What I've done so far is collect the URLs from the text area, and if there are multiple URLs separated by a line break (\n), I simply use split to get an array of pasted text and then use another function inside the loop to validate if they are URLs. If there is no line break detected inside the text area value, then I simply check the one line that was provided. On each case, I send the whole text area to the PHP script, because I don't know how to get rid of the invalid URLs in jQuery. I've created a function called debug() in PHP which stores anything into a debug.log file and this is what I'm getting (in one try) when I paste something into the text area:
https://www.google.com/https://www.google.com/
I paste https://www.google.com/ once in the text area, but it gets logged twice in the PHP side and I can't determine why.
This is how my jQuery looks like:
// Remote upload
var char_start = 10;
var index = 0;
var urls = $('.remote-area');
var val_ary = [];
urls.keyup(function(){
if (urls.val().length >= char_start)
{
var has_lbrs = /\r|\n/i.test(urls.val());
val_ary = urls.val().split('\n');
if (has_lbrs)
{
for (var i = 0; i < val_ary.length; i++)
{
if (!validate_url(val_ary[i]))
{
val_ary.splice(i, 1);
continue;
}
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote', // Used to determine the upload type in PHP
urls: val_ary, // Sending the whole array here
},
});
}
else
{
if (!validate_url(urls.val()))
{
// Display an error here
return;
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote', // Used to determine the upload type in PHP
urls: urls.val(), // Sending what's in the text area
},
});
}
}
});
The questions
So the final questions are:
How do I send my information correctly to the PHP script, only valid URLs and have them kind of "process-able" in my PHP script.
How do I indicate the progress of the upload?
If I was somewhere unclear during my question, please let me know, I'll try to reexplain.
Thank you.
Updates
09/12/2013
I think I have managed to solve the double-sending issue where my AJAX would send the same information twice to the PHP script. What I did was code in a delay anonymous function that sends the text area content to the PHP script after an user stops typing for 2 seconds. Once the user stops typing again, the timer resets and a new AJAX request will be made. So, I'm assuming that this issue has been solved. I'll come back to it if anything strange occurs.
Now I'm still left with the progress indicators part. I'd appreciate your thoughts on that one.
My new code: http://pastebin.com/SaFSLeE9
What you're looking for in terms of communicating progress back and forth is "pushing". That refers to the technique of server sending data to the client, rather than the other way around, which is the standard HTTP way of doing things.
You've got plenty of options available, as described in the explanatory Wikipedia article, though perhaps more relevant to this topic would be Comet. What happens is you trigger and $.ajax call just like the one you have now, but you set a very long timeout. That essentially gives the server a "channel" to send data back to the page whenever it's available.
So what you need is a .php on the server that is capable of handling long polling and will send data back to the page as the upload progress changes (probably in array form for multiple uploads). This article should get you started with some jQuery code. Just remember that this request doesn't go to upload.php. This request goes to a different script that deals solely with upload percentages and only returns data when that is available, it doesn't return immediately as all others scripts - the Ajax will happily wait for the data.
Also, don't separate your code like that with has_lbrs. One line or many are not distinct cases, one line is just an edge case of many lines. You're duplicating the code unnecessarily. What does the else case do that would break in the general case? Further, the "error handling" in the else case is misleading. The only error reporting you do is if there is only one line and it's wrong. What if you have two lines and they're both wrong? Your code will happily send an empty array to upload.php.
This is why I think you shouldn't separate your code like that, because then you'll split logic and not even notice it.
In my opinoin, the best way is to call your cURL script with ajax and use it to upload your files on remote server. You need ajax.js, curl.php, index.php (whatever name you want) on your app server. And image.php, class.image.php (whatever name you want) on your remote server.
Steps that I did for my app
1) I am going to upload an image from my index.php file. It will call curl.php file using ajax.js and the cURL file will check file's extension and all (for your app's security, make sure what you want to allow users to upload).
2) Now the curl file will upload the file to your pre defined temporary folder with the default file name.
3) Now if move_uploaded_file function (which I used in my script) run successfully, you can call your cURL function to send your data as post on your remote server, where image file will receive posts and will process further. You can keep your class in image.php or you can create two PHP files on your remote server, as you want.
4) Now in your class file, you should check file once again that it is image file (and whatever you want to allow) or not for better security. If file is good, process to rename it and add file into folder if you want to.
5) Add file's new name and folder name into your database by using remote database connection. So, cURL will show you result on the same page.
Now, why cURL? I prefer cURL because, you can add secret key or API for your communication to make it more secure, with if else conditions. Your remote server file which is going to receive all posts, will check if API == 'yourKey' then will process other wise it wont process and nobody will be able to send images on your server with bots and all.
I don't know that my answer is going to help you or not, probably my method is lengthy or not good for your app, but try to Google about cURL and you will understand what I am trying to say. Hope you like it and understood it. If any doubt, you can ask me any time.

Processing a file upload with javascript before saving to database in Cakephp

I have a form that includes a file upload.
I need to extract some meta information using javascript from the file before saving the contents of the form to my database.
What would be the best way, if any, of achieving this?
To clarify: The issue isn't the with extracting the file meta but rather how to access the $_FILES array and execute a js file with this data before finally allowing the form to submit to the server.
How I am achieving this currently:
I submit the form to the controller action
It saves the data and then it sets a view variable with the location of
the uploaded file before re-rendering the initial view upon successful form submission
The view checks if the variable is set, and if it is, executes the
javascript which basically extracts the meta now that it can access where the file is, and updates the db
with an ajax call.
The above method is not ideal in that the meta belongs to the same row of data that is saved when the form first submits so ideally I would like to include it initial form submission and not when the page is rendered again after the form has been submitted. Seems like a bit of a dirty hack to me but I can't as of yet see another way this can be achieved.
I would suggest uploading using ajax (SWFUpload/Uploadify) and then sending data back to the view with the processed file data.
You can upload the file, issue a number of callbacks, and finally return the rendered filedata back to the waiting javascript function that issued the request.
Just my two cents
What sort of metadata? To answer your question, yes, this is possible, but only if the browser supports the File API. This excludes IE9 and older. For more information, see this MDN article on FileReader. There are various libraries that will extract specific types of metadata from files. For example, if you are interested in parsing EXIF metadata from an image file, you should look into something like jQuery-fileExif.

Categories