File Reading in PHP - javascript

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.

Related

Why is my $_FILES empty given the following code?

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

Edit file on server from a webpage

What I want to do is to have a set of editable Excel files on my webpage:
I give links to what for the user represents an Excel file
With a click, the user's default program for editing Excel files (say, MS Excel) should open
After finishing editing, the file should be uploaded to my server transparently for the user, and next time the user visits my page, they should see their edited file and be able to edit it again
What I have considered:
JavaScript Excel-like grid. However, I did not find a JavaScript library with sufficient features, such as easily moving rows (any advice of a good JavaScript Excel component?)
Saving to DropBox / Google Docs /... using their APIs. However, it requires the user to have an account, and it will probably require me to manage user's DropBox passwords (and not all users will want to share passwords with me). Also, I will need to have interfaces to Google Drive, Miscrosoft OneDrive, and who knows how many other services.
Allow the user to download the file and rely on the user to upload it back again. However, this is too complicated for the user, and the users will forget to upload the files, which means losing their edits. Any way or uploading the file automatically upon closing?
A macro in my Excel files that would contact my server before exiting. However, this requires the user to enable macros (security alarm) and may be unreliable if the connection breaks. I did not evaluate whether this is technically possible.
Or what is the best / simplest way to achieve this?
(I know how to generate Excel files and how to open them from the webpage; my problem is how to get the user's edits back to the server transparently for the user.)
I think the easiest way to do this ("get the user's edits back to the server transparently for the user") is to use AJAX (JS) requests to PHP scripts.
AJAX is great for doing things in the background (asynchronously), but it can't edit the server. Just add an event listener in JS (an onchange or onblur, perhaps) and send an AJAX request every time the user edits the file.
PHP is a great server-side scripting language, and you can edit files with it.
EDIT: Example (on request)
Assuming that the Excel file is stored in a string in a <textarea> for simplicity (for now), you can set a listener to get the data from it (in jQuery), and send an AJAX request:
HTML:
<textarea id="excel"></textarea>
JS:
$("#excel").change(function() {
var excelFile = $(this).val();
$.ajax({
url: "updateFile.php",
method: "post",
data: { data: excelFile }
});
});
PHP (updateFile.php):
<?php
$data = $_POST["data"];
$file = fopen("FILENAME.xlsx", "w+");
fwrite($file, $data);
fclose($file);
?>

Canvas Image to an Image file

So i have a canvas on which the user signs, now instead of converting it to a base 64 string i simply want to save it as an image itslef. whats the easiest way to do it html5??
You can easily do that this way (specifying the format as png in this case):
var img = canvas.toDataURL("image/png");
You can specify different image formats.
Take a look at this answer.
I've answered a similar question here:
Simulating user event
Assuming you are saving locally
You can go the route of creating an image from a Data URL, but then saving it is the trickier part that currently isn't very nice using HTML5. It's hopefully going to get better soon, if browsers incorporate the download attribute of the a tag.
Obviously if you have higher permissions than a standard webpage... i.e. you are designing a browser plugin - then there are other options...
If I were to implement something like this myself, at the moment, I would conceed to using a flash plugin to handle the save to the local computer.
Assuming you are saving remotely
By the sounds of it you aren't saving to a server, but if so this is quite easy by just POSTing the base64 information to a script written in a server-side scripting language (i.e. like PHP) and getting that to write the data directly as binary to a file. Obviously you have to make certain you do this securely however, you don't want just any binary data written to your server's filesystem.
Best of both worlds
If you've got the development time, the best method to get a canvas image saved locally - without Flash - is to create a server-side script that instead of saving the data to your server actually writes the Base64 information you send it directly back as a realised binary image file. That way you can create a form that posts your Base64 data to a new tab, this request is evaluated by the server-side, and the binary image is returned... at which point the browser asks the user where they wish to save their image.
You'll need to define the correct headers to force an image to download (rather than display in-browser). A simple change to force this is to set the server-side script's Content-type header to 'image/octect-stream'... there are other header options to set which would be best researched (i.e. headers that control the filename and so forth).
reflect.php
<?php
/// a simple example..
if ( array_key_exists('data', $_POST) && ($data = $_POST['data']) ) {
header('Content-type: image/octet-stream');
echo base64_decode( $data );
exit;
}
and the form...
<form action="reflect.php" method="post" target="_blank">
<input name="data" type="hidden" value=" ... Base64 put here with JS ... ">
</form>
(The whole form should be created dynamically and submitted automatically with JavaScript)
Improving the user experience
There are ways to avoid a new tab being created, but you'd have to research to make sure these other methods don't cause cross-browser problems... for example you could post your form data as part of an iframe (which would keep the process hidden), or just post the data directly on the current window (..and hope that all the browsers receive the correct request and open a download rather than replace your page content - most modern browsers should handle this).
Improving security
With regards to a PHP script that automatically returns binary data, you should keep the access to this script secured by one time use key / authentication token or something similar, and keep a limit on how much Base64 data you are willing to accept. It might not seem like it poses a secutiry risk - as you are not modifying your server in any way with what the user sends - but the dodgy people of this world could take your script and use it to send download request to other users... which if downloaded (and turned out to be unwanted trojans or viruses) would make your server implicit in providing the dodgy file.
All in all
Due to the effort required to get a simple thing like an image saved to the desktop, I wouldn't blame you for doing the following:
Embed the image in the page (after taking your snapshot from canvas) and ask the user to right click and Save as...
Hopefully future things will make this situation better...

Upload a string as file using form post in javascript

I want to fake a file upload without using a file input. The file's content is generated from a string. i.e. I want to post some string to a server with content-type "multipart/form-data".
But the server is with different domain and doesn't support CORS, therefore I could not use XMLHttpRequest. Is it possible to do this using only normal form post?
That is actually a nice question. In my humble opinion, what you are looking for is not possible for various reasons as listed below:
You can surely have an HTML form something like this:
<form ....>
<input id="blah" type="input" name="nameblah" ..>
...
</form>
But as you would know, you really cant access/modify the "contents" of the file selected. Immediate solution will be to use a hidden field as an alternative and set the enctype=multipart/form-data, but for hidden field the browser will not set proper Content-Disposition Headers.
You could have an AJAX call in which you manually build up the entire request body, but that would be a cross domain call, as you have already noted. The usual bypassing techniques apply.
Solution would be to let the server, which serves out the HTML, fulfill the skydrive request for you. In that case you would be uploading the file using HTML form, or javascript. The file will then be "forwarded" to the skydrive server.
In case you are trying via Javascript, be sure to get the multipart/form-data format correctly. Here is the RFC

With JS, jQuery, how do I save an AJAX response to a (text) file?

It seems like this question is asked periodically and the common response is "You shouldn't do that with AJAX anyway. Just set the window location to the file."
But I'm trying to request a file that doesn't actually exist out on the server anywhere. It's dynamically generated (by a Django view) given the GET/POST context parameters. The file I want to retrieve via AJAX, and then save to the client machine, is a text file (csv).
I can currently get the text to the client machine (and can verify this by seeing it in logging or an alert) but cannot then figure out how to save this text to a file inside of the AJAX success callback fn.
Essentially, is this possible, is it something JS can do? That is, to open file save dialogs for "files" that are actually AJAX response text?
From the browser's point of view, it doesn't matter if the file exists or not, it's just a resource on a server that it's requesting. I think you're going to need to do some version of "Just set the window location to the file". If you set the content type in the header to something that the browser doesn't recognize, I believe it will ask the user if they want to save it.
As others mentioned, you can't do it only with JavaScript.
IMO the best option would be the Flash 10+ FileReference API.
There are some good JavaScript wrapper libraries like Downloadify that provide a JavaScript API to access those methods.
Give a look to this demo.
This isn't something JavaScript (and therefore jQuery or anything other JS framework) is allowed to do, for security reasons. You may be able to do what you want to flash or another route, but not JavaScript. Bear in mind Flash has it's own slew of security restrictions for this as well.
(Yes, IE can do this via an ActiveX object, but I'm not counting that as a "solution" here)
Basically, no. Javascript cant save anything to the local machine due to security restrictions. Your best bet may be to have a signed applet that the user can trust to write the file, or put it in a textarea that they can then easily copy and paste into a new file.
Could you not use the PHP rename() function for this, instead of just Javascript? Call to a PHP file and pass the name of the file you want to copy along with where as parameters?
I have the same problem. You can try this
<button id="Save">Save</button>
<img src="MakeThumbnail.ashx?Image=1.jpg" id="imgCrop">
$("#Save").click(function (e) {
url = $("#imgCrop").attr("src")+"&Action=Save"
e.preventDefault(); //stop the browser from following
window.location.href = url;
});

Categories