Html sample code:
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
Company Name:<input type="text" name="company"/><br />
ClientName: <input type="text" name="ClientName"/><br />
<br />
<input type="hidden" name="MAX_FILE_SIZE" value="5120000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
</body>
Sample Php code:
<?php
$file_name = $_POST['company'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$uploaddir = 'c:/temp/'.$new_file_name;
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
echo '['.$new_file_name.']';
print "</pre>";
?>
I am having problem with the rename. It renames the file but it keeps the original name too. So if I upload a file name joey.doc, it changes to random# = 4567, company name = whatever, file name = joey.doc output = 4567whateverjoey.doc. What I am looking for is for the file name to change to the random number append the company only = 4567whatever.doc. Later I will write code to create company name directory store all file from that company in their directory. Store the location tag in xml then pull up a table with to reference. the information. Plus I use the client name input box to decode what file go with what.
If writing xml is like asp.net C# I should have no problem
You are appending the old name again:
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
If you only want to append the extension have a look at pathinfo()
In the line:
$uploaddir = 'c:/temp/'.$new_file_name;
You add the new file name to the directory it's to be located in.
But in this line:
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
You also append the old name it was uploaded with to that string. You should do what #TimWolla suggested and find out about pathinfo() if you want to find just the extension.
change this line:
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
in particular just do some string manipulation on the basename(...) portion.
Basically, all you care about is the extension...and depending on your filename restrictions and desired robustness the answer could be easy, or a little bit tricky.
one example (so you get the idea):
$uploadfile = $uploaddir . '.' . split('.',basename($_FILES['userfile']['name']))[1];
or use built-in function Pathinfo
Related
I'm trying to upload a file in a server with PHP, but i have some problems. I have found this guide: http://www.sumedh.info/articles/store-upload-image-postgres-php-2.html.
My html is:
<form action="img_user.php" method="POST" enctype="multipart/form-data" >
<button id="buttonImgProf" class="btn" type="button" onclick="caricaImgProf()">Inserisci un immagine</button>
<div id="imgProfLoader" class="postContent" style="display:none;">
Name : <input type="text" name="name" size="25" length="25" value="">
<input type="file" name="userfile"></input>
<button class="btn" type="submit">Carica immagine</button>
</div>
</form>
(parts are not displays because i use javascript). The php code is:
$uploaddir = 'localhost'; //i have try lots of dir, maybe the error is here?
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$name = $_POST['name'];
echo $_FILES['userfile']['tmp_name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{ echo "File is valid, and was successfully uploaded.\n";
}
else { echo "File not uploaded"; }
the output is File not uploaded
your upload path($uploaddir = 'localhost'; ) should be physical path not should be url so change localhost to any path like ($uploaddir = "uploads/")
full demo code :
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
then your form page
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Make sure that the form uses method="post"
The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form
The "upload.php" file contains the code for uploading a file:(it is action page for file upload form)
<?php
$target_dir = "uploads/";
if (is_dir($upload_dir) && is_writable($upload_dir)) {
// you can write anything in this folder
} else {
die('Upload directory is not writable, or does not exist.');
}
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
PHP script explained:
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file
Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files will be saved there.
$uploaddir = 'localhost'; - localhost is for database connection purposes, not for a folder upload directive; use a folder that is writeable.
As per the manual http://php.net/manual/en/features.file-upload.post-method.php
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
I put your HTML and PHP code in a single file and wrapped your PHP code with a "not empty" $_FILES and it seems to work fine. Here's the full file.
I have also removed the display:none; style you had put on your div to make it useable, since you did not provide the contents of your caricaImgProf() function. Oh and the $uploaddir cannot be a domain such as localhost, it must be a valid directory, so I removed your localhost reference, so that the file uploads right next to where the script is (same directory) which you shouldn't do in a production server of course, but it's off topic :P
This single file should be named img_user.php :
<?php
if(!empty($_FILES)){
$uploadfile = basename($_FILES['userfile']['name']);
$name = $_POST['name'];
echo $_FILES['userfile']['tmp_name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{ echo " / File is valid, and was successfully uploaded.\n";
}
else { echo "File not uploaded"; }
exit();
}
?><html>
<body>
<form action="img_user.php" method="POST" enctype="multipart/form-data">
<button id="buttonImgProf" class="btn" type="button" onclick="caricaImgProf()">Inserisci un immagine</button>
<div id="imgProfLoader" class="postContent">
Name : <input type="text" name="name" size="25" length="25" value="">
<input type="file" name="userfile" />
<button class="btn" type="submit">Carica immagine</button>
</div>
</form>
</body>
</html>
It outputs this when I submit a picture file and the file correctly gets saved right next to the PHP script in the same folder with the original filename before the upload:
E:\wamp64\tmp\php38E6.tmp / File is valid, and was successfully
uploaded.
So I want to allow users to upload an image and want to store that image in my server. (Using Ubuntu and Apache) so server path is (/var/www/html/)
My HTML code is:
<!DOCTYPE html>
<html>
<body>
<form enctype="multipart/form-data" action="uploadimages.php" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="3000000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
</body>
</html>
and my uploadimages.php file code is:
<?php
$uploaddir = '/var/www/html/images';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
When I click the bottom send I get the following message:
File is valid, and was successfully uploaded.
Here is some more debugging info:Array
(
[userfile] => Array
(
[name] => thisisthepictureIupload.png
[type] => image/png
[tmp_name] => /tmp/phpIUEUjE
[error] => 0
[size] => 4596
)
)
But when I go to the folder: /var/www/html/images the image is not there.
Any help would be highly appreciated.
I think you might be missing the / in your file path:
$uploaddir = '/var/www/html/images';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
should probably be
$uploaddir = '/var/www/html/images';
$uploadfile = $uploaddir . '/' . basename($_FILES['userfile']['name']);
I am creating a very simple admin panel and I want to have posibility of uploading a file, but this is gonna be only one file with static name. I have this code:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename(uploadedfile.jpg);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
And this works, but file is being uploaded with name "uploadedfilejpg" so there is no extension. How to fix this to add extension? I only want to upload jpg files and overwrite old file.
You've got an error in your PHP script on line 4. You've got basename(uploadedfile.jpg), which is an error. I assume you meant to write basename('uploadedfile.jpg'), but since using basename on a file name just returns the file name (thanks to #CBroe for noticing this), you might as well just use 'uploadedfile.jpg'.
It should look like this:
<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . 'uploadedfile.jpg';
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
replace this line :
$uploadfile = $uploaddir . basename('uploadedfile.jpg');
with:
$uploadfile = $uploaddir . basename('uploadedfile.jpg'). '.jpg';
I've been trying to get my PHP upload script working, the HTML side seems to work but the PHP keeps returning a failed result. I am using iPage hosting. Here is my script:
<?php
if(isset($_FILES['userfile'])){
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
} else {
?>
<form enctype="multipart/form-data" action="" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
<?php
}
?>
Comment to answer to close the question, since that's what the issue was, both.
Check to see if the folder is writeable. If it is, then try a relative path instead of what you're using now.
I.e.: $uploaddir = 'uploads/';
Make sure the upload directory has the correct permissions - Writable and Proper Owner
You will run into issues when the file size is over 512000, you should check the size of the file using the $_FILE array and return an error message. Just a suggestion as you have already closed this.
// Error Checking Extended
if($_FILES['userfile']['error'] == 2) {
echo "You've exceeded the maximum file upload size of 512kb.";
return false;
}
This is the code I'm using for my website. You can see the HTML input:
<form action="upload_request.php" method="post">
<input type="file" name="userfile" id="file"/>
<i>Only Excel files (*.xls || *.xlsx)</i>
</form>
And here there's the PHP script:
<?php
$uploaddir = '/cdir/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "uploaded.\n";
} else {
echo "fail!!\n";
}
?>
I have to upload an excel file in my folder dir but this script is not doing that and he always "fail!!". Could you help me please?
Your <form> tag should have enctype="multipart/form-data" attribute. See the example #1 here.