Checking file props before upload - php

I am practicing with PHP and AJAX but I have some problems!
I'm trying to get the filename, type, size from a jQuery alert after select an image to upload, but I keep getting an empty string.
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="my_file" />
<input type="submit" name="submit" value="Submit" />
</form>
This form includes a JS file that has an ajax script that asks to a php page the filename of the posted file, but it doesn't work. Do I need to upload the file before I try to get this data?
The JS file:
$("input").change (function () {
$.post("preview_uploader.php", { action:"get_size" }, function (data) {
alert (data);
});
});
The PHP file preview_uploader.php:
<?php
if ($_POST["action"] == "get_test") print "text string test works!";
if ($_POST["action"] == "get_name") print $_FILES["my_file"]["name"];
if ($_POST["action"] == "get_size") print $_FILES["my_file"]["size"];
if ($_POST["action"] == "get_type") print $_FILES["my_file"]["type"];
?>
It works if i make a test with action:"get_test" with php page but it doesn't work with $_FILES["my_file"]["name"] or $_FILES["my_file"]["type"] etc...
Can someone help me find where I am wrong?
Thanks!

Your JS script is sending a separate request to the server and so your PHP is unaware of the file, and $_FILES["my_file"] is not a valid index.
You do not need to go to the server to get the file name, simply use this to get the file name:
$("input[type=file]").val();
I believe it brings back the path as well, so you will need to strip the path off to get the filename.
If you are trying to get all the additional details (filesize, etc) you will either need to upload the file first (which defeats what you are trying to do) or use a Flash + JavaScript combination like these solutions:
Uploadify for jQuery
SWF Upload

You can actually get the size with jQuery. See the answer to this questions:
How to check file input size with jQuery?
You can use the method given to get the name, size, and type. General belief is that its not possible. You can't always believe everything you hear...

Related

Let user upload an xml file and parse it (without PHP)? [duplicate]

This question already has answers here:
Reading file contents on the client-side in javascript in various browsers
(5 answers)
Closed 8 years ago.
I am quite knowledgeable in CSS(3) and HTML(5), but my current project allows me to take things further. However, this is completely unknown terrain for me. In my project I have a textarea in which users can submit some XML, which I then parse with jQuery's $.parseXML method. However, I want to add the ability to upload an XML file.
I suppose the upload button would look like this:
<form name="upload-form" action="???" method="???">
<input type="file" name="upload-field">
</form>
However, I do not know what the action and method ought to look like. Because I am staying on the same page and nothing spectacular is supposed to happen, I am guessing the action-attribute can be left out? The method-attribute might be get, rather than post? (1)
And then what? I don't know how I get the data from the uploaded XML document in my jQuery's parser. (2) Also, how to check for the correct file type? Does this have to happen server-side? (3)
action contains the name of the server side script that will receive the form data. when using post, the browser does not parse the content of the input field into the url.
the server side script, e.g. in php will receive the request, do security checks and save the data.
<form name="upload-form" action="serversidescript.php" method="post">
<input type="file" name="upload-field">
<input type="submit" value="Submit">
</form>
serversidescript.php
<pre>
<?php
print_r($_REQUEST); // shows the array containing the form data
leave the method empty and use the post method. Using post for files is important because it has security features and allows you to upload more data.
since it's uploading a file you need to add the enctype, enctype="multipart/form-data" or it won't work
<form name="upload-form" action="" method="post" enctype="multipart/form-data" >
<input type="file" name="upload-field">
<input type="submit" value="Submit">
</form>
ANd then to parse the file, you need to read the xml file using jquery and then write a parser function depending on what you need to do.
//write the custome parse function
function parse(data){
//code for your parse function goes here.
// to append the file to html, I need the actual structure of the file to show you
}
//this reads the xml file using jquery
$.ajax({
url: 'name.xml', // name of file you want to parse
dataType: "xml",
success: parse, //this calls the parse function
error: function(){alert("Error: Something went wrong");}
});

Specify upload path using swfupload

I'm using SwfUpload and I want to be able to specify the destination folder. Right now I have hard coded the final destination, but I would like to be able to control it on the fly. Is there a way to get SwfUpload to submit it to my upload script? I tried adding it as a hidden variable to the form that displays the uploader, but it doesn't make it to my script:
Here's the form that shows the uploader. The rest of the page is pretty standard so I didn't include it. Look for the hidden field "destinationpath"
<form id="form1" action="nowhere.html" method="post" enctype="multipart/form-data">
<p>Select file to upload for program.
</p>
<div class="fieldset flash" id="fsUploadProgress">
<span class="legend">Upload Queue</span>
</div>
<div id="divStatus">0 Files Uploaded</div>
<div>
<span id="spanButtonPlaceHolder"></span>
<input id="btnCancel" type="button" value="Cancel All Uploads" onclick="swfu.cancelQueue();" disabled="disabled" style="margin-left: 2px; font-size: 8pt; height: 29px;" />
</div>
<input name="destinationpath" type="hidden" value="c:/DigitalMediaFiles/">
</form>
Then in upload.php I check for it:
if (isset($_REQUEST["destinationpath"]))
$save_path = $_REQUEST["destinationpath"];
but its not set. I suspect that swf upload does not submit the form.
The way to do it is to specify the parameter in post_params of the SWFSettings object
post_params:
{
"destinationpath" : "C:\DigitalMediaFiles"
},
I tried using addPostParam() but that did not work for me. putting it in post_params of the settings did.
If your destination folder is not related to the up-loader(client), you can do it in your php script, without getting that variables from client side scripts. That is save the file in your target directory by php script.
If the destination folder is different from each client, still you can save them in a same directory and use your .htaccess file to rewrite urls for each client(using client id). In this case you need to save your file that keeps client id in a portion of the file name. You can explode file name by using a delimiter.
If still you need to do it your own way that is you mentioned in your question,just use post_params: {} function in your configuration js file which is coded for the swfupload.js file. In that case post_params: {} function will look like the following:
post_poarams: { 'your-variable-name-in-php-goes-here': 'value of this variable at this time goes here' },

PHP: File upload always returning nothing

Hey guys I'm working on a file uploader and I have come across a problem. In my code I am checking to see if a file has been selected via the file upload form, here is the form code:
<form method="post" action="actions/save.php?id=<?print($id);?>" enctype="multipart/form-data">
Listing Photo: <input type="file" name="file"/>
<input class="add" type="submit" name="submit" value="Save"/>
</form>
The user selects the file to upload then clicks the "Save" button. Now in my uploading code i am trying to check if the file form has been set like this:
$file = $_POST['file'];
if(isset($file)) {
//Continue
} else {
//Go back
}
Now my problem is that even if the file input is set (File selected) it goes to the "Go back" part of the code.
Any suggestions or a different way of checking?
Any help is appreciate, Thanks.
When you upload files through form, you should have $_FILES superglobal array with that file, so try
print_r($_FILES['file'])
to see what it cointains (size, error code, path ...)
Uploaded files end up in $_FILES, not in $_POST
see: http://nl.php.net/manual/en/reserved.variables.files.php for documentation and examples
You should have access to uploaded files using the $_FILES array. See also the reference documentation.

Unset uploaded files in PHP

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.

Upload photos with php without reload

What I want
I want to upload a file without reloading the page, also I want to add the source link for the image to the textarea.
So when I push the upload_photo, the image uploads and a link is added to the textarea.
I want pure HTML, Javascript|AJAX and PHP.
What I have
<form action"index.php" method="post" enctype="multipart/form-data">
<textarea id="textarea" name="text"></textarea>
<input type="file" name="photo" />
<input type="submit" name="upload_photo"/>
<input type="submit" name="post"/>
</form>
Example sites:
http://www.friendfeed.com - the page don't reloads when you upload the files
What I don't want
Please avoid posting solutions with jQuery or any library, API.
That's easy.
Put an iframe, give it a name, for example "MyIframe".
Then in the form, add the TARGET attribute, with the value "MyIframe", and the action - the script that takes the upload (takeupload.php for example)
In the main page define a Javascript function that does something you need after the upload is done, which will be called, with parameters, from the page generated by takeupload.php.
in takeupload.php upload the image, then send as an output a normal blank HTML page that will execute a script which will call the method described above, with a set of parameters you need (image name, path, error, or plain HTML to insert somewhere, etc.).
use it like this:
<script type="text/javascript">
parent.YourJSMethod(parameters);
</script>
The page will be loaded in the iframe, and it will run a function defined outside the iframe. Upload is done, and the parent page receives data about the result.
This is fairly simple. No jQuery needed, no AJAX, no nothing, just a very simple Javascript code and a little HTML.
This can indeed be done with AJAX. I don't think that using AJAX is any more of a security risk than sending a vanilla HTML form; you will have to validate all user input on the server side all the same. Here's a simple example:
http://www.webtoolkit.info/ajax-file-upload.html

Categories