Let's say I want to upload a csv file to PHP. I noticed in Chrome if I select, for example, "test.csv" in the file selection box,
if I rename the file locally to "test1.csv",
then upon submitting the form to PHP, I see an error page:
ERR_FILE_NOT_FOUND
I want to catch this error and show a friendly error message instead.
The issue you described has nothing to do with PHP or jQuery. I have isolated the issue you have described down to:
<form action="http://www.google.com" method="POST" enctype="multipart/form-data">
<p>Select a file, for example z.txt, then before clicking submit,
rename the file locally so the file picked is invalid, such as zz.txt,
then submit to get an error in chrome.</p>
<input type="file" name="myFile">
<input type="submit" />
</form>
Yes, it doesn't even matter where the form sends to. Chrome will error if the file doesn't exist before it tries to send. Firefox, however, will submit the form as usual. This is an issue with chrome. You can, however, adjust chrome to hide network messages:
Suppress "Failed to load resource: net::ERR_FILE_NOT_FOUND" in Chrome Packaged App
Related
My form with the method of POST for uploading a file only makes the receiving script hang (or it doesn't load properly), when enctype is set to multipart/form-data. In Safari it takes a couple of minutes before the script collapses (gives up), but in Chrome it goes down right away. By down I mean that the user ist taken to the root of the site (/).
No errors to be found in the error log.
I've managed to make the form function without enctype and/or a file input, but then naturally, no file is posted.
It is a WAMP server with PHP7. Ini settings have all been carefully checked to be big enough.
The scripts worked until a couple of weeks ago, but the IT department cannot point to any specific updates that might be the cause.
<form name="fileupload" action="fileReceive.php" enctype="multipart/form-data" method="POST">
<input type="text" name="ahiddenvalue" value="The hidden value">
<input type="file" name="upfile" id="fileToUpload" accept=".pdf, application/pdf">
<input type="submit" name="Upload" value="Upload file">
</form>
File receiving script, fileReceive.php:
exit("<pre>".print_r($_REQUEST)."\n".print_r($_FILES)."</pre>");
The loading bar in the address field of the browser just gets started, and hangs in Safari till about two minutes. No message about max-execution_time in the error log.
I found the reason: An url rewrite was set up un Apache with only lowercase file suffixes. When trying to fetch a file with uppercase file suffix, the script that was 'url rewritten' to, did not catch the file and just stopped everything by displaying the top page of the site.
Running PhpStorm 2016.3.2, Ubuntu 16.04 with PHP7 and LAMP stack installed and tested.
I seem to have an error in PhpStorm (or somewhere else down the line), whereby clicking 'Submit' in an html form will result in a '404 not found' error, even if the form action path is valid.
I built a very simple application to demonstrate this, however it should be noted that this error has occurred every time I use an html form in PhpStorm so far, even example applications that I know have no errors in code.
The code for my form is as follows
var $form = <<< FORM
<form action='?' method="post">
<p>Enter your number </p>
<input type="text" name="formInput"
maxlength="10">
<input type="submit" name="formSubmit"
value="Submit">
</form>
FORM;
Once 'Submit' is clicked, the 404 error happens. I have tried multiple permeations of form action such as "" and even a variable set to APP_ROOT_PATH, and then just manually typing out the correct path (even a different php file) also with single and double quotes.
The reason I believe these paths to be valid is that simply by clicking in the address window from the 404 error page and hitting enter (thereby going to the path it was trying to get to) the form loads again fine.
I can't get my head around why this might be, if it was a permissions or path error surely I would not be able to access the path from the browser either?
EDIT: Looking at the source code reveals that the action is what I intended it to be. Even copying the url from there and pasting it into the browser will open the correct form. It is just when clicking 'submit' that the 404 error happens. The correct url is also in the address bar on the 404 page.
EDIT 2 : For note, the '?' action in the above code is irrelevant to the issue as the error occurs no matter what correct link I put there, be it "" or the full path.
I´ve a multipart form with a mixture of default inputs (text, select etc.) and a file upload (<input type="file">).
I´m using a combination of form validation class and upload library of Codeigniter for form submission. That works great.
I´ve only one problem for what I haven´t found a solution yet: If the user selects an image but misses to fill another required field (like "name"), then the form validation class blocks the request and shows an error message to the customer.
But now I´ve the problem, that the image was already submitted successfully and I don´t want to let the user add the file again. So I want to pre-fill the file input with this data.
I´ve tried different things like:
<input type="file" name="image" value="<?php echo set_value('image','');?>" />
and also spent time on finding a solution on the web but without success.
On the server side, you do not get any information about where the file is located on the client's computer, so in the scenario of a user uploading an image successfully but the user hasn't filled out the rest of the fields properly, you have to simply omit the input type="file" field entirely but keep a store of where the file is located on your server. There's a few ways to go about this, but it all involves taking the absolute location of the uploaded file and:
Inserting it back as a hidden value using <input type="hidden" name="uploadedFile" value="<?php echo $absPath; ?>" /> then checking for the existence of $_POST['uploadedFile'] and utilizing it appropriately. But this isn't a solid idea as you're now exposing server paths to the end-user (opens yourself up to malicious attack.)
Starting a session and saving the absolute path in the $_SESSION variable while presenting the user with a simple token in their re-attempt form.
I'd stick with method 2, so assuming you've done all the work to validate the form and upload the file and your file is located in $absFilePath, you could do the following:
session_start(); // This needs to be at the very top of you PHP file
// ...
$formToken = md5(time());
$_SESSION['uploadedFile'][$formToken] = $absFilePath;
Then render the token as a hidden variable using:
if (!empty($_SESSION['uploadedFile'][$formToken]))
echo '<input type="hidden" name="formToken" value="'.$formToken.'" />';
and hide the file upload portion using
if (empty($_SESSION['uploadedFile'][$formToken]))
echo // <input type="file" output here...
finally inside of your form submission code check for the existence of a formToken value before attempting to load $_FILES['image'] using isset($_POST['formToken']), and handle it using:
$absFilePath = $_SESSION['uploadedFile'][$_POST['formToken']];
Bam! Now you have your absolute file path as if the file had been uploaded just like before.
Since you haven't given enough code, I can only given you enough instruction to get you started, but this should be more than enough.
I have a Form that I am using to receive an uploaded .csv file, parse it and insert the data into my MySQL db on an Apache server. The page first checks to see if there is an uploaded file. If there is, it processes the data, if not the form (below) is displayed.
<form enctype="multipart/form-data" action="uploadfaculty.php" method="POST" id="UploadForm">
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
My problem is that currently the user can simply F5 the browser over and over again and because the file is still on the server and in the $_FILES array, it processes it every time.
I've tried:
unlink($_FILES['uploadedfile']['tmp_name']),
unlink($_FILES['uploadedfile']),
unset($_FILES['uploadedfile']['tmp_name']), and
unset($_FILES['uploadedfile'])`
I've even reset the form via Javascript (which I knew would not work, but did it just to eliminate all doubt). All to no avail. I'm sure it's something simple I'm missing...it almost always is. Any thoughts?
It's not unsetting because the post action is stored on the browser's end and being re-uploaded (in a small amount of time as it's only a csv) when they hit F5. Which is essentially the same as them using the form to upload another csv.
You can do this:
if (isset($_POST['csv'])){
$DataProcessed = DataProcessingFunction();
}
if (isset($DataProcessed) && $DataProcessed){
header("Location: /path/to/form/page.php");
exit();
}
This will clear the post data sent in the earlier request. Refreshing will not resubmit the form.
You can header redirect them to that upload page after processing to prevent the post data from continually going in via a refresh. But the temporary file should be cleared once the processing is done. PHP does not keep the file unless you use the move_uploaded_file function.
My PHP book gives a template HTML form for uploading a file:
<form action="upload.php" method="post" enctype="multipart/form-data"/>
<div>
<input type="hidden" name="MAX_FILE_SIZE" value="10000000"/>
<label for="userfile">Upload a file:</label>
<input type="file" name="userfile" id="userfile"/>
<input type="submit" value="Send File"/>
</div>
</form>
The book displays it as "Upload a file:" [textbox] [Browse...] [Send File]
I copied it verbatim, and the result I'm getting is "Upload a file:" [Choose File] "no file chosen" [Send File]
I'm wondering why the discrepancy exists. Is there a way around it? I'm using XHTML Transitional. No doctype is given in the book. But I doubt that's the issue.
The script I'm writing aims to take the file the user chooses, process it, and write the result into another file that doesn't exist yet. I'm asking this question because it would be useful to let the user more easily copy the initial file path/name, paste it into the other field, and just change a part of it.
(Also: why the difference between "Browse..." and "Choose File"? I tried manually setting the value of the "userfile" field to "Browse..." but nothing happened. This is less important but I'm curious nonetheless.)
It is probably showing a different browser and/or version.
It sounds like you are looking at it under Safari and the book has screenshots of IE, for example.
There are a few ways to get complete control of file uploading and the <input type="file" /> element. You can use Flash, or you can set the input to opacity: 0 and then position what you want beneath it.
Some time ago the browser engines took almost complete control over the input type="file" - fields, since it nowadays is regarded as a security issue. For example the days before that you could easily prefill the file input filed with some path and filename (e.g. something like /etc/passwd) and hide the field, so sending the form you would not remark that you're also sending the file...
That's why for example you could not preset the filename of such a field and that's also why browsers now all do their own thing with these special input fields.
As Alex said above, you could get around this, but it will be some hassle, because it would mean to "fake" the file input field.