php : unable to upload file to the server - php

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++;
}
}
?>

Related

How to upload photos/file to server using PHP

Hi so I'm trying to allow users to upload a photo to a listing. I'm using dropzone.js and I have the form done, it works perfectly! except that photos don't actually upload to the folder "uploads/"
I have tried many many different ways spent days researching and I cannot for the life of me figure out what is wrong.
Kindly note that it is a multipage form so I cannot post the whole form on here but ill try to share the important scripts!
Dropzone code:
<head>
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
</head>
<div class="container" >
<div class='content'>
<form action="create.php" method="post" type="file" name="file" class="dropzone" id="dropzonewidget" enctype="multipart/form-data">
</div>
</div>
</div>
</div>
<div class="row form-block flex-column flex-sm-row">
<div class="col text-center text-sm-start"><a class="btn btn-link text-muted" href="user-add-2.php"> <i class="fa-chevron-left fa me-2"></i>Back</a>
</div>
<div class="col text-center text-sm-end"><button type="submit" name="save" class="btn btn-primary">save</button><i class="fa-chevron-right fa ms-2"></i></div>
</form>
Now for the PHP script: I have 2 attempts that got close, the first actually makes its way into the database and the second just echo's all error scripts
Script 1: (kinda works)
$uploadDir = 'var/www/uploads';
$tmpFile = $_FILES['file']['tmp_name'];
// upload file to directory
$fileName = $uploadDir.'/'.time().'-'. $_FILES['file']
['name'];
move_uploaded_file($tmpFile,$fileName); {
$sql = "INSERT INTO hosts(id, user_name, name, type,
country, city, state, zip, about, price, photo)
VALUES('$id', '$user_name', '$name',
'$type', '$country', '$city', '$state', '$zip',
'$about', '$price', '$fileName')";
Script 2:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]
["name"]);
$uploadOk = 1;
$imageFileType =
strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["file"]["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 file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 1000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png"
&& $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are
allowed.";
$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["file"]["tmp_name"],
$target_file)) {
echo "The file ". htmlspecialchars( basename(
$_FILES["file"]["name"])). " has been uploaded.";
//$pictureName = "uploads". basename(
$_FILES["fileToUpload"]["name"]);
} else {
echo "Sorry, there was an error uploading your
file.";
}
At the end of both of these attempts I have a simple insert query (p.s. I know about SQL injections, just trying to get it to work first.)
hope I didn't give you a headache
Just a heads up I am new to PHP and to SO so be kind and I hope a more experienced developer can help me out of these troubling times! Thanks in advance, and if you understand my issue please post some code not a vague response :) cheers
For dropzone uploads (multiple file uploads)
a. you do NOT need to specify enctype="multipart/form-data" and method="post" type="file" name="file"
b. No need to use submit button
c. As stated before, make sure there is a sub-folder known as uploads and it is write-permitted
d. To do further db maninpulation (e.g. insert), execute the insert query in the php , make sure using $_FILES['file']['name'] when constructing the insert query
Hence, please amend your code to:
HTML
<head>
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
</head>
<div class="container" >
<div class='content'>
<form action="create.php" class="dropzone" id="dropzonewidget">
</form>
</div>
</div>
create.php
<?php
$target_dir = "./uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
$status = 1;
// do further update in database
// please note that the file name is $_FILES['file']['name']
// make sure you use parametized prepared statement in your insert query
// to avoid SQL injection attacks
//
}
?>

Image not showing when URL is inputted

So, you know how you make a image uploading system with InfinityFree PHP hosting?
Well, I made one but it has a problem. When I get the image and paste the link in like example Discord Chat, it does not show as a Image, it just shows the link. I saw somebody use InfinityFree and pasted the link, but it works! I don't know how to make happen. Please Help
Coding: HTML CODE
<!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>
PHP code:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . uniqid("", false));
$uploadOk = 1;
$imageFileType = strtolower(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 file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$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 ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Anyone know how to help?

Uploaded image using php doesn't fully work

The problem is this one:
I have a code that uploads a picture to phpmyadmin, the code... doesn't fully work for some reason, it doesn't upload the image fully and the image ends up having a very small size, and it won't show up either. If I upload them directly to the database, they can be shown, but the ones uploaded using the code below have that problem.
This is the code I have:
Code for the button:
<div id="content">
<form method="POST" action =""/>
<table>
<tr>
<td>
Upload a picture
</td>
<td>
<input type="file" name="image"/>
</td>
</tr>
</table>
<input type="submit" name="submit" value="Registrarme"/> <input type="reset"/>
</form>
<?php
if(isset($_POST['submit'])){
require("iniciar.php");
}
?>
</div>
Code for the uploading: (iniciar.php)
<?php
$image = $_POST['image'];
$reqlen = strlen($image);
if($reqlen > 0){
$conn = mysqli_connect('localhost','root','','image');
$sql = "INSERT INTO `images` VALUES ('', '$image', '')";
mysqli_query($conn, $sql);
echo 'Upload successful';
}else{
echo 'Please insert an image';
}
?>
This is the structure of the table:
The table I have
you're assigning like input data instead of
$_FILES["image"]["name"];
//remove thisline
$image=$_POST['evidence'];
// you have to use it like this
$image= $_FILES["image"]["name"];
you have to assign image like this
$target_file = $target_dir . '/' . basename($_FILES["image"]["name"]);
$image=$target_file;
now evidence hold address of image so dir. of image is now on evidence too.now it will be uploaded to data base you aren't passing data. that's the mistake. any questions comment .if it solves your problem mark it as solved :)
for reference ,this is the php script used to upload profile picture,
<?php
if(isset($_POST["submit"]))
{
$target_dir = "profilepic/";
$targetfile=$target_dir.basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($targetfile,PATHINFO_EXTENSION);
if($imageFileType != "jpg" &&$imageFileType != "JPG" && $imageFileType != "png" && $imageFileType != "PNG" && $imageFileType != "jpeg" && $imageFileType != "JPEG" && $imageFileType != "gif" && $imageFileType != "GIF" )
{
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0)
{
echo "<small>Sorry, your file was not uploaded.</small>";
}
else
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetfile))
{
echo "<small>upload successful</small>";
$imgdir="UPDATE user SET profilepic='$targetfile' WHERE username='$uname';";
$con->query($imgdir);
header("location:profile.php");
}
else
echo "not uploaded";
}
}
?>
make changes according to your data base & operations.

How to upload img file in php

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.

move_uploaded_file does not work [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have tried different metods for file upload system. None of them worked so far, I know that there are lots of similar questions, I checked and tried nearly all of them yet they did not work.
It gives the last echo if I try to upload files. If the files is more than the max size than it gives the wrong echo "Sorry, this filetype is not allowed"
Here is my php code
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($FileType == "exe" && $FileType == "dll" && $FileType == "zip" ) {
echo "Sorry, this filetype is not allowed";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo " <br>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.";
}
}
?>
Here is the HTML Code
<html>
<head> <link rel="stylesheet" href="table.css"></head>
<title>Dosya Yükleme</title>
<body>
<form action="fileupload.php" method="post" enctype="multipart/form-data">
Bir dosya seçiniz:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload" name="Yükle">
</form>
</body>
</html>
I simplified code, putting both php and html in same php file and erasing the checking process.
New PHP file which still doesn't work
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (isset($_POST['upload'])) {
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.";
}
}
?>
<html>
<head> <link rel="stylesheet" href="table.css"></head>
<title>Dosya Yükleme</title>
<body>
<form action="fileupload.php" method="post" enctype="multipart/form-data">
Bir dosya seçiniz:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload" name="upload">
</form>
</body>
</html>
Solution chmod -R 777
Change && to || in the type conditional branch:
if($FileType == "exe" || $FileType == "dll" || $FileType == "zip" ) {
I found the solution on ubuntu forum. The problem was file permission. Once there was a post about file permission but the code was wrong. On that topic the terminal code was chmod 0751 -R folder but the working code is
chmod -R 777 folder
I think an issue is with the submit button and trying to check its value with if (isset($_POST['upload'])) {. It seems that the name of the button needs to be submit.
Have a look at Send value of submit button when form gets posted.

Categories