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.
Related
I need to create a simple web page via which you can upload a image file that goes to a directory on the server that is previously created.
Here's the code for the index.php file:
<!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>
Here's the code for the upload.php:
<?php
$target_dir = "uploads/";
$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;
}
}
?>
The code is hosted on a free hosting server (not a paid one) and I created a dir called 'uploads' in the same subdirectory where both scripts are located.
In the php settings uploading seems to be on.
The index.php displays fine, I select an image and click upload, it loads for a second and then displays 'File is an image - image/gif.'
However when I got to the upload dir, there isn't a single file there.
What could be the issue? Thank you in advance.
You aren't moving the file to your server after uploading the temp file so it gets deleted
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.";
}
}
A weird problem when i am trying to make a banner art upload system for user profiles.
I have searched for answers, but none have solved it.
It is not a permissions problem, my chmod is 755 on uploads folder and in the upload.php file.
code below:
if ($_POST && !empty($_FILES)) {
$formOk = true;
//Assign Variables
$path = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
$formOk = false;
echo "Error: Error in uploading file. Please try again.";
}
//check file extension
if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/gif'))) {
$formOk = false;
echo "Error: Unsupported file extension. Supported extensions are JPG / PNG.";
}
// check for file size.
if ($formOk && filesize($path) > 500000) {
$formOk = false;
echo "Error: File size must be less than 3 MB.";
}
if ($formOk) {
// read file contents
$content = file_get_contents($path);
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'hidden', 'hidden', 'hidden')) {
$user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$content = mysqli_real_escape_string($conn, $content);
$sql = "insert into banners (user_id, username, name, size, type, content) values ('{$user_id}','{$username}','{$name}', '{$size}', '{$type}', '{$content}')";
if (mysqli_query($conn, $sql)) {
$uploadOk = true;
$imageId = mysqli_insert_id($conn);
} else {
echo "Error: Could not save the data to mysql database. Please try again.";
}
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
}
And the form is:
<form method="post" enctype="multipart/form-data" action="<?=$_SERVER['PHP_SELF']?>" >
<div>
<h3>Image Upload:</h3>
</div>
<div>
<label>Image</label>
<img src="<?php print_r($path); ?>"/>
<?php print_r($_FILES); ?>
<input type="text" name="user_id" value="<?php echo $user->data["user_id"]; ?>" readonly/>
<br />
<input type="text" name="username" value="<?php echo $user->data["username"]; ?>" readonly/>
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<input type="file" name="image" />
<input name="submit" type="submit" value="Upload">
</div>
</form>
I have the form in the same file upload.php along with my include header and footer.
So basically it stores the data into the database, but just will not upload what so ever, i also checked the phpinfo and so on, and all is ok, it is turned on, and file limit in phpinfo is 64mb, so i don't get why it wont upload?
any help would be appreciated, thanks
Simple: You didn't move that file anywhere, as in move_uploaded_file().
http://php.net/manual/en/features.file-upload.post-method.php
Base yourself on the following example taken from the manual:
<?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>";
and check for errors too.
http://php.net/manual/en/function.error-reporting.php
I just wanted to post how i did it, thanks to Fred and some other comments others made :)
//Assign Variables
$username = $user->data['username'];
#mkdir("uploads/".$username,0755);
$target_dir = "../uploads/$username-";
$path = $target_dir . basename($_FILES['image']['tmp_name']);
$name = $target_dir . basename($_FILES['image']['name'].$user_id);
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
if (move_uploaded_file($_FILES['image']['tmp_name'], $name)) {
echo "<h2>Thank you for uploading your banner art - File is valid, and was successfully uploaded.\n</h2>";
} else {
echo "Possible file upload attack!\n";
}
so I also made it so it now puts a username in front of the uploaded images name too.
The form is pretty much the same, I now also made it so that the upload and update open in a nice fancy box :)
https://gyazo.com/e12a03ce01d8f503b8fa2e79f5605809
Thanks again everyone :)
I have been back forward about this, can't find a solution. My file that I am trying to upload is not moving. I'm using WAMP and my root folder is C:\wamp\www
I've checked that the directory exists in php and put in a script that if it does not exist it should be created, which works, but still it is not moving the file. What am I doing wrong?
The Form:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
Upload.php
$target_path = "uploads/" ;
if(!file_exists($target_path)) {
mkdir($target_path, 0755, true);
echo "The directory was created";
}
$tmp_name = $_FILES['file']['tmp_name'];
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
echo $target_path;
if(move_uploaded_file($tmp_name, $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
try to change,
$tmp_name = $_FILES['file']['tmp_name'];
to
$tmp_name = $_FILES['uploadedfile']['tmp_name'];
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;
}
hey I am not much of a PHP coder
I am using following to upload file to server acn any body help me whats wrong with this code
<?php
$uploaddir = './uploads/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://iphone.zcentric.com/uploads/{$file}";
}
?>
Thanx in advance
I don't see anything wrong with the PHP code, though without an error it is difficult to tell what is happening.
Somethings which could cause uploads not to work, and which may not return errors:
Ensure you have enctype="multipart/form-data in the form tag:
<form enctype="multipart/form-data" action="__URL__" method="POST">
Make sure PHP is accepting the input, by adjusting the following PHP ini variables:
http://us.php.net/manual/en/ini.core.php#ini.post-max-size
http://us.php.net/manual/en/info.configuration.php#ini.max-input-time
http://us.php.net/manual/en/ini.core.php#ini.upload-max-filesize
Finally, ensure that permissions are properly set for both the temp upload folder (http://us.php.net/manual/en/ini.core.php#ini.upload-tmp-dir) and the folder you are moving files to. If it is a Windows server you might also run into an inheritance issue which will require you to change the default upload directory.
iF YOU WANT TO UPLOAD .pdf FILE TO LOCAL SERVER THEN USE THIS SIMPLE METHOD, Lets we are doing code here under Button Click Event...
if (isset($_POST['submit']))
{
if ( ($_FILES["file"]["type"] =="application/pdf"))
{
if (file_exists("C:/xampplite/htdocs/site/upload/" . $_FILES["file"]["name"]))
echo " This File is already exists in folder";
else
{
move_uploaded_file ($_FILES["file"]["tmp_name"],"C:/xampplite/htdocs/site/upload/" . $_FILES["file"]["name"]);
echo "File have been Stored in:-C:/xampplite/htdocs/site/upload/ " . $_FILES["file"]["name"];
}
}
}//end of click_event
could u pls publish what the error u get?Your code looks ok.Here the upload folder must he stay in the upper of the directory where you run the code.Then it should to work.if your script folder like this /test/script/abc.php then your uploads directory should be /test/uploads.
index.php
<!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" multiple="">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php
<?php
//$target_dir = "uploads/";
/*$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
*/
if(count($_FILES['fileToUpload']['name']) > 0)
{
$i=0;
while($i<count($_FILES['fileToUpload']['name']))
{
$filen = $_FILES["fileToUpload"]['name']["$i"];
$path = 'uploads/'.$filen;
$imageFileType = pathinfo($path,PATHINFO_EXTENSION);
if (file_exists($path)) {
echo "Sorry, file already exists.";
}else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
else if(move_uploaded_file($_FILES["fileToUpload"]['tmp_name']["$i"],$path))
{
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]["$i"]). " has been uploaded.";
$files=$_FILES["fileToUpload"]["name"]["$i"];
echo $files;?><img src="<?php echo $path;?>" style="width:200px;height:200px" alt="" >
<?php
}
$i++;
}
}
?>