PHP Image Upload Script Not Uploading But Not Failing - php

I am trying to enter some data into a database and upload an image to a specific directory. I am using the following script which is a modified version of the top voted answer to this question: How to store file name in database, with other info while uploading image to server using PHP?
require($_SERVER['DOCUMENT_ROOT']."/settings/functions.php");
// This is the directory where images will be saved
$target = $_SERVER['DOCUMENT_ROOT']."/safetyarticles/images/";
$target = $target . basename( $_FILES['article_img']['name']);
date_default_timezone_set("America/Chicago");
// This gets all the other information from the form
$article_name = $_POST['article_title'];
$article_date = date("m/d/Y");
$article_creator = $_POST['article_creator'];
$article_views = "0";
$article_content = $_POST['article_content'];
$article_content_2 = $_POST['article_content_2'];
$article_img = ($_FILES['article_img']['name']);
$article_credit = $_POST['article_credit'];
// Connect to database
$conn = getConnected("safetyArticles");
// moves the image
if(move_uploaded_file($_FILES['article_img']['tmp_name'], $target))
{
// if upload is a success query data into db
mysqli_query($conn, "INSERT INTO currentArticles (article_name, article_date, article_creator, article_content, article_content_2, article_img, article_credit)
VALUES ('$article_name', '$article_date', '$article_creator', '$article_views', '$article_content', '$article_content_2', '$article_img', '$article_credit')") ;
echo "The file ". basename( $_FILES['article_img']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
I have successfully connected to my database since my getConnected() function contains error handling for if the connection fails.
For some reason I keep getting the Sorry, there was a problem uploading your file. error from the bottom of the script.
Am I missing something? All I did was change some minor lines here and there such as how the database connects, and the variables. I also moved the query to only happen if the file uploads.
I'm not sure what I'm missing.
Is it also possible to modify this current script to rename the image to whatever the value of $article_name is? For example if the article name is "This Is The First Article" then the image would be this-is-the-first-article.jpg?
My HTML form is:
<form method="post" action="http://example.com/admin/articleCreate.php" enctype='multipart/form-data'>
<input type="text" name="article_title" placeholder="What Is The Name Of This Article?" id="article_title_input">
<textarea name="article_content" placeholder="Write The Top Half Of Your Article Here." id="article_content_input"></textarea>
<input type="file" name="article_img" placeholder="If The Article Has An Image, Upload It Here." id="article_img_input">
<textarea name="article_content_2" placeholder="Write The Bottom Half Of Your Article Here." id="article_content_2_input"></textarea>
<input type="text" name="article_creator" placeholder="Who Is Writing This Article?" id="article_creator_input">
<input type="text" name="article_credit" placeholder="If This Article Is Copied, What Website Was It Taken From?" id="article_credit_input">
<input type="submit" value="Submit">
</form>
And I did var_dump(is_uploaded_file($_FILES['article_img']['tmp_name'])); and it's returnign true.

Sidenote edit: This being before you edited your question with only one of them being renamed. https://stackoverflow.com/revisions/36367407/4
$_FILES['photo']
$_FILES['uploadedfile']
are two different file arrays and you're using name="article_img" as the name attribute.
You need to use the same one for all of them.
Error reporting http://php.net/manual/en/function.error-reporting.php would have told you about it.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional edit:
$target = $target . basename( $_FILES['photo']['name']);
if that's your real edit, still the wrong array name.

I think the problem is in this line:
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
Change it to this:
if(move_uploaded_file($_FILES['article_img']['tmp_name'], $target))

Your html has:
<input type="file" name="article_img" placeholder="If The Article Has An Image, Upload It Here." id="article_img_input">
And your php is waiting for $_FILES['photo']['tmp_name']
Change your html file input to:
<input type="file" name="photo" placeholder="If The Article Has An Image, Upload It Here." id="article_img_input">

Related

can't copy uploaded file (php)

I'm creating a site that displays news uploaded on it's admin panel.
Each post has an image and a title (and description, but i haven't implemented it yet).
My problem is, that when i try to post (and upload image with it) the post is created, but the image doesn't exist.
uploader (php):
if (isset($_FILES['image'])) {
//this script
//connects to mysql database
//declares an array that contains table names (array name is db)
require_once("db.php");
//move file to the img folder
move_uploaded_file($_FILES['image']['tmp_name'], "img/" . $_FILES['image']['tmp_name']);
//upload the post to the database
$sql = "INSERT INTO `{$db["posts"]}` (`img`, `text`) VALUES ('img/{$_FILES['image']['tmp_name']}', '{$_POST["text"]}')";
if (!mysql_query($sql)) {
//display error message
}
}
form (html):
<form action="post.php" method="POST" enctype="multipart/form-data">
<label>Image: </label><input type="file" name="image" />
<br />
<label>Text: </label><input type="text" name="text" />
<input type="submit" />
</form>
I check the files via ftp after posting, the image doesn't exist.
$_FILES['image']['tmp_name'] is an absolute pathname like /var/tmp/something. When you concatenate it to img/, you get a pathname that points into a subdirectory, img//var/tmp/something. Since the subdirectory doesn't exist, move_uploaded_file() fails.
You should use basename() to get just the filename portion.
$filename = 'img/' . basename($_FILES['image']['tmp_name']);
move_uploaded_file($_FILES['image']['tmp_name'], $filename);
$text = mysql_real_escape_string($_POST['text']);
$sql = "INSERT INTO `{$db["posts"]}` (`img`, `text`) VALUES ('$filename', '$text')";
I'm not really sure how safe using the name of the temp file this way is, though. I don't think there's any guarantee that it will never repeat the same name for different uploads.

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.

File upload php mysql

I am trying to upload a file onto the server using php but I need some help.
I have a html form to submit a book name and a book image. The book name will be stored in the database (see below) and the image will be stored on the server.
The id, book name, and date are being stored in the database however the image is not uploading. Please help me to sort it out.
Thanks.
Database table "books"
id int(11), book_name varchar(255), date_added date
add_book.php
<?php
$book_name = $_POST['book'];
// insert fields to database
$sql_query = mysql_query("INSERT INTO books (book_name, date_added) VALUES ('$book_name', now()");
// get id for that row
$id = mysql_insert_id();
// rename the book to that id followed by the format .jpg
$new_book_name = "$id.jpg";
// define upload path
$upload_path = "../book_images/";
// move the uploaded file to the upload path with the new name
move_uploaded_file($_FILES['upload']['tmp_name'], $upload_path . $new_book_name);
?>
<form action="add_book.php" method="post" enctype="multipart/form-data" name="bookform" id="bookform">
Book name: <input name="book" type="text" id="book" value=""/> <br />
Book image: <input type="file" name="upload" id="upload" />
<input name="submit" type="submit" value="Add book" />
</form>
Before any PHP developer begins to debug anything I always suggest in every question that do set error_reporting(E_ALL); and ini_set("display_errors", 1); at the very top of your script. This will tell you what went wrong on what line with respect to what statement/variable/constant
Anyways, you should check for validities whether the file uploads or not, its type and other such parameters. You should also store it by adding relative path with respect to your current working directory
if(isset($_FILES["upload"])&&$_SERVER["REQUEST_METHOD"]=="POST")
{
$name=$_FILES["upload"]["name"];
$tempName=$_FILES["upload"]["tmp_name"];
$size=$_FILES["upload"]["size"];
$type=$_FILES["upload"]["type"];
$realPath="bookName/Imagename/".$name;
if(($type=="image/jpg"||$type=="image/jpeg"||$type=="image/png"))
{
if(is_dir($fullDirectory)) //if directory exists, then simply move it
{
move_uploaded_file($tempName, $realPath);
}
else //if directory doesn't exist then make one and then move the file
{
mkdir($fullDirectory,0777,true);
move_uploaded_file($tempName, $realPath);
}
}
else
{
print $_FILES["upload"]["error"];
}
}
Spme thing is wrong here:
$new_book_name = "$id.jpg";
You should take file name from POST here $_FILES["upload"]["name"]. and add $id with this file name:
$new_book_name = $id."-".$_FILES["upload"]["name"];
Also check permission in your upload directory "../book_images/".

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