I am trying to upload a file via a form and a php file. I have used the same method many times throughout my website with no problems, however this time I just can not get it to work. On my form I have this....
<span class="purple"><strong>Upload Your Image</strong></span>
<input name="userfile" type="file" id="userfile" class="textbox">
<br /><br />
<label>
<input name="submit" type="submit" class="createbutton" id="submit1" value="ADD TO BASKET">
</label>
In my php file I have this...
//upload image first
$uploaddir = '../images/';
$uploadfile = $uploaddir. $_FILES['userfile']['name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
$status = 1;//uploaded
$data["printfile"] = $_FILES['userfile']['name'];
} else {
$status = 0;//cant upload
echo "Upload Failed!\n";
$err = "";
}
Every time it just gives me the Upload Failed error message. Any ideas?
Ah right, I really feel like a fool now. I somehow managed to miss enctype="multipart/form-data" on my form tag. Thanks so much for your help, works perfectly now.
Related
I'm having trouble getting a simple php file upload script to work. What happens is I get the Thanks message on my browser, but the file isn't anywhere to be seen.
I've been watching the upload directory and /tmp with inotify to see if anything gets created all but nothing does. Here is the html div that allows selecting the file:
<div>
<p> Select a file </p>
<form id="support" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="file">Filename:</label>
<input type="file" name="logfile" id="file"><br/><br/>
<input type="submit" name="submit" value="Upload">
</form>
</div>
So then I try and upload the file:
$uploadDir = "/tmp/";
if(isset($_FILES['logfile']['name'])){
$uploadFile = $uploadDir . basename($_FILES['logfile']['name']);
print "<p>{$_FILES['logfile']['name']}</p>\n";
print "<p>{$uploadFile}</p>\n";
# Delete if already exists
if (file_exists($uploadFile)) {
unlink($uploadFile);
}
// Recieve the file
if (move_uploaded_file($_FILES['logfile']['tmp_name'], $uploadFile)) {
displayMessage("Thanks");
}
else {
# Couldnt move the file
displayMessage("Error moving file");
}
}
What happens is I get the message "Thanks" in my browser but no file. I've checked permissions, checked my nginx log - no errors at all. It looks like it is successful but nothing is being copied?
Edit:
Even this fails:
$myfile = fopen("/tmp/testfile.txt", "w") or die("Unable to open file!");
$current = "John Smith\n";
fwrite($myfile, $current);
fclose($myfile);
Basically I cant write to /tmp for some reason, even though nginx is not reporting any error. I've also tried the same script under apache, with the same results.
drwxrwxrwt 18 root root 460 Aug 20 10:56 /tmp/
It's working fine for me. can you check the upload directory? where you have kept your tmp folder? just use if the same place of the file $uploadDir="tmp/";
<?php
$uploadDir = "";
if(isset($_FILES['logfile']['name'])){
$uploadFile = $uploadDir . basename($_FILES['logfile']['name']);
print "<p>{$_FILES['logfile']['name']}</p>\n";
print "<p>{$uploadFile}</p>\n";
# Delete if already exists
if (file_exists($uploadFile)) {
unlink($uploadFile);
}
// Recieve the file
if (move_uploaded_file($_FILES['logfile']['tmp_name'], $uploadFile)) {
echo "Thanks";
}
else {
# Couldnt move the file
echo "Error moving file";
}
}
?>
<div>
<p> Select a file </p>
<form id="support" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="file">Filename:</label>
<input type="file" name="logfile" id="file"><br/><br/>
<input type="submit" name="submit" value="Upload">
</form>
</div>
htm code :
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
Movie :<br />
<input name="fileField" type="file" size="30" /><br />
<input name="submit" type="submit" class="submit" value="Send" />
</form>
php code :
if ($_FILES['fileField']['tmp_name'] !=""){
$fileName = $_FILES["fileField"]["name"];
$fileType = $_FILES["fileField"]["type"];
$fileTmpLoc = $_FILES["fileField"]["tmp_name"];
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName);
move_uploaded_file($fileTmpLoc, '../upload/video.flv');
}
this code not work for VIDEO file but work correct for other file ( jpeg , mp3 , png and ,,, )
Perhaps change your directory to
move_uploaded_file($fileTmpLoc, '../upload/ ');
this problem from php setting
php set to Max 2MB size for upload
You have absolutely no error handling on the code, meaning you have no way of telling when an upload failed. Add:
if ($_FILES['fileField']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['fileField']['error']);
}
as some bare-minimum error handling. The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php. Checking for the absence of a 'tmp_name' is NOT a proper check.
I'm trying to post form data through ajax
form1.php
I use request to get all URL parameter data
$_REQUEST["Ename"];
$_REQUEST["eImg"];
To upload the image,i use this code http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
In the above link,you can see the source code,in the place of $_FILES['photoimg']['name'];,i use $_FILES['image']['name']; but it is not uploading the file and giving success message.
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
I removed script that is marked with **
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
**if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{**
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) { // Image size max 1 Mb
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['image']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} **else {
echo "Please select image..!";
exit();
}**
you simply can't upload files via $.ajax().
you'll have to use some trycky iframe-stuff or something like that to make this work. luckily, there are ready-to-go plugins for jquery to handle this for you (like $.ajaxForm() for example wich seems to be the one that's used in the tutorial you're reading).
EDIT:
the plugin also allows to add extra data thats not present in the form itself. to quote the documentation:
data
An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }
For upload image by ajax you should use an iframe and set its id to form target.
Please have a look at
http://www.coursesweb.net/ajax/upload-images
It is very simple code to upload image
That won't work!
Images are handled differently from the text data in Ajax so you would have to do more than just post it using the $.ajax({}) method.
You can however use the jquery.form.js plugin it works perfect http://jquery.malsup.com/form/#download there is a tutorial on how to use it
here
Any ways I have used it my self so let me elaborate for you.
The JavaScript code is here
$('.uploadForm').live('click', function(evt){
$('#feedback').html(' ');
$('#feedback').html('<img src="images/loader_image.gif" alt="Uploading...."/>');
$("#formID").ajaxForm({
target: '#feedback'
}).submit();
evt.preventDefault();
});
If your PHP code is fine this should work .....
Just post the rest of the form fields in the normal way way
This should work for you. If the PHP code is fine
For example if you had other form fields like firstname and lastname in form like this one
<div class="form">
<fieldset class="ui-corner-all">
<h3 class="ui-widget-header ui-corner-top" align="center">Client information</h3>
<form action="save_new_client.php" enctype="multipart/form-data" id="clientForm" method="POST">
<label>First Name</label>
<input name="firstname" type="text" id="firstname" class="required" minlength="3"/>
<label>Lastname</label>
<input name="date_added" type="text" id="date_added" class="dateEst" />
<label>Image</label>
<input name="photo" type="file" id="photo" />
<input type="submit" name="button" id="button" value="Save" class="uploadForm"/>
<input type="reset" name="reset" id="button" value="Cancel" /></td>
</form>
</fieldset>
<div id="feedback"></div>
</div>
Below it you'll just need to add a div or paragraph to hold your feedback message ....
then the rest will be just fine (like I said if your PHP code is okay)I have not looked through it alot
I would like to have the user upload a pdf to a folder on my website. (note:this is for learning purposes, so security is not necessary) The code I have below does not do echo a response when submitted. The folder I would like to have the pdf uploaded to is in the same directory as the php script, is it possible I'm incorrectly referencing that folder? I appreciate it.
<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
Email:<br /> <input type = "text" name="email" value=""/><br />
Resume:<br /><input type = "file" name="resume" value=""/><br />
<p><input type="submit" name ="submit" value="Submit Resume" /></p>
</form>
if(isset($_POST['submit']))
{
define ("FILEREPOSITORY","./resume/");
if (is_uploaded_file($_FILES['resume']['tmp_name'])) {
if ($_FILES['resume']['type'] != "application/pdf") {
echo "<p>Resume must be in PDF Format.</p>";
}
}else {
$name = $_POST['email'];
$result = move_uploaded_file($_FILES['resume']['tmp_name'], FILEREPOSITORY."/$name.pdf");
if ($result == 1) {
echo "<p>File successfully uploaded.</p>";
}
else {
echo "<p>There was a problem uploading the file.</p>";
}
}
}
You have a logical error. Your else statement should be part of the inner if statement -- not the outer one.
would suggest you check the permissions for the upload folder and the max size for file uploading in your php.ini... its happened to me many times uploading a file exceeding the limits and not getting an error message.. also the logic of your if else doesn't match as suggested by your previous post..
IT would be of great help to give the error you receive.
move_uploaded_file()
only works if you have the rights to write to the destination folder.
I want to add simple image upload functionality to my WP plugin. So the simple form with upload button. I dont want to use standard thickbox included in WP for this.
When you press the button file selection dialog will appear, you select file from your drive and it'll be added to the input box.
Then when you press "save" button for plugin options it will send with form and handled on server side.
I wonder if there is ready to use WP functionality for the server part.
As I want to save the upload image path also to DB options table.
EDIT: added PHP tag as wordpress is a PHP language
You're in some luck-I'm currently working on a mod that would allow image uploads for MarketPress. Here's my skeleton, poorly indented script. This should help get you started methinks?
<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10240" />
Send this file: <input name="userfile" type="file" />
Send this file: <input name="userfile2" type="file" />
<input type="submit" value="Send File" />
</form>
<?php
if ($_POST['MAX_FILE_SIZE'] == '10240' ){
$uploaddir = 'public_html/uploads';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$validfiletype;
if ( preg_match('/\\.(exe|com|bat|zip|doc|txt)$/i', $_FILES['userfile']['name']) )
$validfiletype = 0;
elseif( preg_match('/\\.(jpg|jpeg|gif|png|pdf|psd)$/i', $_FILES['userfile']['name']) )
$validfiletype = 1;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "File upload unsuccessful.";
}}
?>