move_uploaded_files() php is not moving the file - php

So I have a bit of a problem. I was looking at a tutorial for video uploads and I came across this tutorial.
https://www.youtube.com/watch?v=SibODOJle6Q
It seems that my move_uploaded_files is not working and it is trivial for me to see his code work which I copied and the result is completely different.
Could I get some help with this please?
my Code below
<html>
<head>
<title>Video Upoad</title>
<link rel='stylesheet' href='stylesheet.css'/>
</head>
<body>
<?php
require('connect.php');
?>
<div id='box'>
<form method ='post' enctype='multipart/form-data'>
<?php
if(isset($_FILES['video'])){
$name= $_FILES['video']['name'];
$type = explode('.',$name);
$type=end($type);
$size= $_FILES['video']['size'];
$random_name=rand();
$tmp = $_FILES['video']['tmp_name'];
if($type !='mp4' && $type != 'MP4' && $type!='flv'){
$message = "Video Format is not supported!";
}else{
move_uploaded_file($tmp, 'viddata/'.$random_name.'.'.$type);
$message ="The Upload was successful";
mysql_query("INSERT INTO video VALUES ('','$name','viddata/$random_name.$type')");
}
echo $message.'<br/><br/>';
//echo $type.'<br/>';
//echo $name.'<br/>';
}
?>
Select Video: <br/>
<input type='file' name='video' />
<br/><br/>
<input type='submit' value='Upload' />
</form>
</div>
<div id='box'>
</div>
</body>
</html>
It does insert into the database and everything except moving the file to the destination.

You should consider the following:
Make sure you have viddata folder.
Check the file size of the file you are trying to upload if it exceeds the upload_max_filesize.
If it does, you can configure your php.ini and set the upload_max_filesize to your preferred size, then reset your XAMPP Control Panel.
Check also the permission of the folder/directory you are trying to upload the file.
You should also set conditions on the files being uploaded by the user, like setting the condition for file type and size before you upload process it.

Start by checking the return value, errors and warnings. The documentation says:
Return Values
Returns TRUE on success.
If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some
reason, no action will occur, and move_uploaded_file() will return
FALSE. Additionally, a warning will be issued.
There are also some good examples with more comprehensive error checking.

Related

Store path to uploaded Image in database

I'm trying to add a path of an uploaded image to the database in order to use it to display it as a thumbnail for a post. I found a tutorial and I used this code to upload the image. However it gets to the else statement and I just get the exit("Error While uploading image on the server"); I have a form to collect the data:
<form action='' method='post' enctype="multipart/form-data">
<p><label>Title</label><br />
<input id="title-input" type='text' name='postTitle' value='<?php if(isset($error)){ echo $_POST['postTitle'];}?>'></p>
<p><label>Description</label><br />
<textarea id="textarea" name='postDesc' cols='20' rows='5'><?php if(isset($error)){ echo $_POST['postDesc'];}?></textarea></p>
<p><label>Content</label><br />
<textarea name='postCont' cols='20' rows='5'><?php if(isset($error)){ echo $_POST['postCont'];}?></textarea></p>
<p><label>Image</label><input type="file" name="uploadedimage">
</p>
<input type='submit' name='submit' value='Submit'>
<input type='reset' name='submit' value='Reset'>
</form>
<?php include 'add-post-handler.php' ?>
And here is the code I used to upload the image:
function GetImageExtension($imagetype)
{
if(empty($imagetype)) return false;
switch($imagetype)
{
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'image/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
}
}
if (!empty($_FILES["uploadedimage"]["name"])) {
$file_name=$_FILES["uploadedimage"]["name"];
$temp_name=$_FILES["uploadedimage"]["tmp_name"];
$imgtype=$_FILES["uploadedimage"]["type"];
$ext= GetImageExtension($imgtype);
$imagename=$_FILES["uploadedimage"]["name"];
$target_path = "../img/".$imagename;
if(move_uploaded_file($temp_name, $target_path)) {
$query_upload="INSERT INTO blog_images (imgPath) VALUES
('$target_path')";
mysqli_query($link, $query_upload) or die("error in $query_upload == ----> ".mysql_error());
}else{
exit("Error While uploading image on the server");
}
}
PS: I also have some doubts on how can I get the imageID to be related with the postID considering that are both submitted from the same form.(I made a relation between the two tables but it's on the primary keys so I'm not sure if it's correct)
Thanks for your help!
Looking at the Code:
move_uploaded_file returns FALSE on two premises (stated in the PHP Docs):
If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some
reason, no action will occur, and move_uploaded_file() will return
FALSE. Additionally, a warning will be issued.
My best guess is, with the information you provided:
Your path is not writeable by your application/webserver, so it won't be moved
Make sure the application (the webserver) can write in your path: '../img/' by issuing a chmod to give the directory the correct rights for the webserver user.
Security Advice (not related to question):
Your application has in this state a potential SQLi in $target_path. You should think about using prepared statements
https://dev.mysql.com/doc/apis-php/en/apis-php-mysqli.quickstart.prepared-statements.html
Your form writes POST Data directly to output. This leads to XSS. You should always encode special characters in your output.
https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
Make sure, only images can be uploaded and scripts can't be executed in this '../img' path. Somebody could exploit your upload to upload a script and execute it.
easiest way to prevent SQLi in this case would be hashing the imagename and setting the extension with the $ext variable:
[...]
$ext=GetImageExtension($imgtype);
if($ext === FALSE) {
exit("Couldn't determine the filetype correctly. Please upload pictures only.");
}
$imagename=md5($_FILES["uploadedimage"]["name"].time()).$ext;
$target_path = "../img/".$imagename;
[...]
The time() is only included, so somebody can upload pictures with the same name.
you could always give your images a specific class that you know directs to all images you want to thumbnail and apply a CSS rule/code that will automatically make them img-thumbnail.
<div class="imgT">
then set your CSS thumbnail
Thanks everyone for answering. In the end I got it. I found that the problem was with the php.ini settings. This is the link that helped me -> Why would $_FILES be empty when uploading files to PHP?. Thanks PaulF for posting it. The problem was that the limit for uploading files was just 2MB or something like that.
For everyone having the same issues make sure you check that link and check this settings in your php.ini file.
file_uploads = On
post_max_size = 100M
upload_max_filesize = 100M

Weird issue in Form

I am working in a simple form of html with php. I am adding some fields including file upload.
But I am facing a weird issue. When I upload image and submit form. It submits but when I do not upload image and submit the form. It says "Unsupported file format"
I checked that when I do not upload file and submit the form. It does not even post the form. Only "Unsupported file format" line come to the page and whole page blank.
This is my code:
<form action="" method="post" enctype="multipart/form-data">
<table class="form-table">
<tr>
<th>Title<font color="#ff0000">*</font></th>
<td><input name="title" type="text" value="<?=$_POST['title']?>" size="40" /></td>
</tr>
<tr>
<th>Image<font color="#ff0000">*</font></th>
<td><input type="file" name="file_name" /></td>
</tr>
<tr>
<th> </th>
<td> Dimensions: <?=$imgwidth?> x <?=$imgheight?> (Max: 2MB) <br />
JPG format is the one recommended.</td>
</tr>
<tr>
<th></th>
<td><input type="submit" name="btnAdd_cat" class="button" value="Add" /></td>
</tr>
</table>
</form>
Php code:
<?php
if(isset($_POST['btnAdd_cat'])){
$error = "";
$title = addslashes($_POST['title']);
if(empty($title)) $error .= "Please enter title.<br/>";
if(empty($error)){
$sql = "INSERT INTO ".CATEGORIES." (`title`, `status`) VALUES ('$title', '1')";
mysql_query($sql) or die(__LINE__.mysql_error());
$id = $insert_id = mysql_insert_id();
$success = "Successfuly added.<br/>";
$filename = $_FILES['file_name']['name'];
if(!empty($filename)){
$imgext = strtolower(substr($filename, -4));
$img = ereg_replace("[^a-z0-9._]", "",str_replace(" ", "-",str_replace("%20", "-", strtolower($title))));
$filename = "category-".$insert_id."-".$img.$imgext;
$savefile = "../pictures/".$filename;
//upload
if(copy($_FILES['file_name']['tmp_name'], $savefile)){
//echo "....Image uploaded ";
}else{$warning = "Failed to upload image!<br/>";}
chmod("$savefile",0777);
if(resize_picture("$savefile","$savefile","$imgwidth","$imgheight")){
//echo "....Image resized ";
}else{$warning = "Failed to resize image!<br/>";}
$image = $filename;
}
if(mysql_query("UPDATE ".CATEGORIES." SET image='".$image."' WHERE id='".$id."'")){
$success .= "Image added.<br/>";
unset($_GET);
} else {die(__LINE__.mysql_error());}
}
}
?>
This page comes when I submit without uploading file:
http://prntscr.com/706ght
Please help me in this.
Thanks
Put the file upload code block in if(isset($_FILES['file_name'])){} i.e. check whether the file is posted or not. because as you have said that the error occurred when you are not selecting any file so it better to check whether the file is posted before running the uploading code.
Hope this will help in solving your problem.
As you have said that when you don't select any file it's showing you an error then you need to update your if condition from
$filename = $_FILES['file_name']['name'];
if(!empty($filename))
to
$filename = $_FILES['file_name']['error'];
if($filename != 4) // Check no file is uploaded
There is a section in php documentation about file handling. You will find that you can check various errors and from file-upload-errors
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
<...>
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
I created a real instance of your code, suppressing what depends on your context (such as SQL-related, and so on): despite you have a number of points that should be enhanced (see below):
it never fired the error you mentioned
more interesting: POST was always done, while you report it was not the case for you
From this latter point I infer the issue should come from some control executed by your browser. So can you give more details about that: which browser are you using, with which plugins and under which OS?
Besides that, there are some points that don't matter for the issue you have pointed out, but should be more strictly coded:
as already mentioned, rather than using if(!empty(filename)), processing the uploaded file should be conditioned to something like if($_FILES['file_name']['error'] == UPLOAD_ERR_OK) before anything else
an important point is that ereg_replace() is deprecated as of PHP 5.3.0: you should use preg_replace() instead
when preparing to save title into database, use mysql_escape_string() rather than addslashes() (or turn using PDO, which takes care of that for you: look at http://php.net/manual/en/ref.pdo-mysql.php)
more generally, about your database processing, you had better to save data in a unique step when your image has been already processed; this way you optimize performance (with only one DB access), while you avoid getting incomplete records containing titles for which no image reference was finally registered

PHP move_uploaded_file function very picky

I having trouble with the move_uploaded_file function on my website.
The whole idea is that in a form, i insert the title, description and a screenshot of a project. Everything is working just fine. It saves the title and description with an id and the creation date in a mysql database and moves the file to a folder on the server.
The problem however is that some files are transferred to folder and some aren't. The problem seems to be in the files, but i can't seem to figure out what the problem is.
It is not the filesize; i have files of 5/6MB that are placed in the folder without any problems, and i have files that are around 3MB that arent. The extension isn't the problem either, they are both .jpg.
Are there any other requirements that a .jpg file should meet, in order to be uploaded?
I'm 99% certain the problem isn't in my code, as it uploads some files without a problem, but here is my code anyway.
The HTML part:
<form action="" method="post" enctype="multipart/form-data">
<h2>Title*</h2>
<input type="text" id="title" name="title">
<h2>Description*</h2>
<textarea id="descr" name="descr" cols="40" rows="4"></textarea>
<h2>Add file*</h2>
<input type="file" id="file" name="file">
<h2><input type="submit" id="submit" name="submit" value="Uploaden"></h2>
<p id="requirements">Fields marked with * are required.</p>
</form>
And this is the PHP part:
if (isset($_POST['submit'])) {
$destination = "../uploadedfiles/" . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $destination)) {
echo '<p id="succes">File has been uploaded</p>';
} else {
echo '<p id="error">File has not been uploaded</p>';
}
$title = $_POST['title'];
$descr = $_POST['descr'];
$name = ($_FILES['file']['name']);
include "../connect/connect.php";
if ($title == "" || $descr == "") {
echo '<p id="error">Fill in the required fields</p>';
} else {
$query = "INSERT INTO file(title, descr, name, created) VALUES ('{$title}', '{$descr}', '{$name}', NOW())";
$upload = $connect->query($query);
if ($upload) {
echo '<p id="succes">Info is stored in database</p>';
} else {
echo '<p id=error>Failed to store info in database</p>';
}
}
}
A bunch of stuff might be going wrong. move_uploaded_file is very pick and sometimes doesn't behave how it is documented. I had problems with it once and honestly, copy archive the same result in most cases if properly implemented.
There are reports of lone filenames causing trouble. 249 chars on $destination seems to be the limit.
not only upload_max_filesize must be set but also post_max_size
utf-8 names might be a problem
If you have problems where the uploaded file seems unaccessible, try to use copy() instead. There are reports of people not being able to find the file just after upload, move_uploaded_file just limits path over copy, the results are the same if you dont input any user var.

How do I allow a user to choose where to upload a file to?

I have a basic upload form
<html>
<head>
<title>Upload a File</title>
</head>
<body>
<font face=verdana size=2>
<form enctype="multipart/form-data" method="post" action="upload_file.php">
<input type="hidden" name="MAX_FILE_SIZE" value="25000">
<p><strong>File to Upload:</strong><br>
<input type="file" name="our_file" size="30"></p>
<P><input type="submit" name="submit" value="Upload File"></p>
</form>
</font></body>
</html>
And the php file
<?
if ($our_file != "") {
copy($our_file, "upload/$our_file_name") or die("Couldn't Upload the file!");
} else {
die("No input file specified");
}
?>
<html>
<head>
<title>Successful File Upload!</title>
<body><font face=verdana size=2>
<B>Success!</B>
<P>You sent: <? echo "$our_file_name"; ?>, a <? echo "$our_file_size"; ?>
byte file with a mime type of <? echo "$our_file_type"; ?>.</p>
</font></body>
</html>
I would like the user to be able to choose what directory he uploads the file to. I assume I would need a form for the HTML side of it but I don't know what to add in the PHP. Any help?
Assuming you only have a fixed number of directories, include a select in your HTML.
#thephpdeveloper, As long as your permissions are set right for your directories, I don't think selecting where you upload is going to be anymore dangerous than any other upload. I am by no means a security expert. Just make sure you're preventing injection, etc.
<select name="selectDir">
<option value="1">This Directory</option>
<option value="2">That Directory</option>
</select>
// on your submit
if( $_POST['selectDir'] === '1' ){
$dir = './thisdir/';
}elseif( $_POST['selectDir'] === '2' ){
$dir = './thatdir/';
}else{
die('You did not enter a valid value');
}
if ($our_file != "") {
copy($our_file, $dir."".$our_file_name) or die("Couldn't Upload the file!");
}else{
die("No input file specified");
}
In your call to copy() you need to modify "upload/$our_file_name" to be the directory where you want the file to end up.
This is probably a very bad idea unless you know how to restrict what can end up in there. If you don't care at all about security, you can do something like this:
/* THIS NEXT LINE IS A BAD IDEA. DO NOT DO THIS. */
copy($our_file, $_POST['path_from_user'] . '/' . $our_file_name) /* BAD IDEA. DON'T DO IT THIS WAY */
/* DID I MENTION THAT THIS IS A BAD IDEA AND YOU SHOULD NOT DO IT THIS WAY? */
Of course, as you guessed, you'd need to set up the HTML form properly for that to work.
There are a number of ways one might try to make this more secure. One would be to use realpath() to check that the file will end up somewhere you expect. Another would be to provide the user with a small number of choices where the file can end up and, on the PHP side, make sure that no matter what is sent by the form (since users can mess with it) that you only send the file to one of those small number of choices. Actually, if you can do both of those, even better.

PHP File Upload Failing

For some reason my PDF upload form is failing consistently, I have this code:
<?php
if($_POST["submit"] == "Add PDF to Comm and Special Projects")
{
$addsubp = $_POST["addsubp"];
$addsubp_name = $_POST["addsubp_name"];
$commuploadedfile = $_FILES['uploadedfile']['name'];
$sqldoc = "INSERT INTO projects_links (pid, display_name, link) VALUES ('".$addsubp."','".$addsubp_name."','".$commuploadedfile."')";
mysql_query($sqldoc) or die(mysql_error());
echo "<BR>";
$target_path = "D:\\Hosting\\69903\\html\\pdfs\\comm\\";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<br>The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded<br>";
} else{
echo "<br>There was an error uploading the file, please try again.<br>";
}
}
?>
<form method="post">
Add PDF to Project for Committees and Special Projects <br>Choose Project<select name="addsubp"><?php
$query = "SELECT
projects.*
FROM
projects";
$showresult = mysql_query($query);
$csp_c = 1;
while($buyarray = mysql_fetch_assoc($showresult))
{
echo "<option value=".$buyarray['id'].">".$buyarray["pname"]."</option>";
}
?></select><br>
Choose Display Name for PDF <input type="text" name="addsubp_name" /> <Br>
Choose PDF: <input name="uploadedfile" type="file" /> <Br>
<input type="submit" value="Add PDF to Comm and Special Projects" name="submit" />
</form>
I have made sure that the application has write privileges to the "comm" directory. I have godaddy and used the file manager to make sure of that. I have had problems with permissions in this project before, so I know this isn't case. It keeps printing
There was an error uploading the file, please try again.
It doesn't attempt to upload any PDF at all, what am I doing wrong?
thanks!
You may have permissions issues, but for file uploads your form tag should contain the proper enctype attribute.
<form enctype="multipart/form-data" method="POST">
and defining a file size limit is also a good idea:
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
try checking the Upload error message: http://php.net/manual/en/features.file-upload.errors.php
Your code is blindly assuming the file upload succeeded. At bare minimum you should have something like
if ($_FILES['uploadedfile']['error'] === UPLOAD_ERR_OK) {
... handle the upload
}
Your code is vulnerable to SQL injection. You do not escape any of the 3 values you're inserting into the database
You're creating the database record before making sure the file was successfully moved into the target directory. What happens if the file can't be written for any reason (as it is now with your problem)? The database will say it's there, file system will say it isn't
You're not checking for file collisions. If two seperate uploads send "file.txt", the second upload will overwrite the first one.
You're storing the files with the user-supplied name, which is under user control. If this file is web-accessible, anyone with access to your upload form can upload anything they want (e.g. a php file) and the server will happily execute it for them.

Categories