PHP file upload Issues - Can't Move uploaded File - php

I am trying to upload image to database and getting this PHP error message:
Warning: move_uploaded_file(/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpA9E6.tmp' to '/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg' in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51
Upload Fail.
Here is my php script:
<?php
require("include/functions.php");
check_session();
$logged_user = $_SESSION['username'];
if(isset($_FILES['avator']['name']) && $_FILES['avator']['tmp_name'] !=""){
//setting file properties
$fileName = $_FILES['avator']['name'];
$filetmpLoc = $_FILES['avator']['tmp_name'];
$fileType = $_FILES['avator']['type'];
$filesize = $_FILES['avator']['size'];
$fileErrMsg = $_FILES['avator']['error'];
//explose the filename extention into an array
$kaboom = explode('.',$fileName);
$fileExt = end($kaboom);
list($width ,$height) = getimagesize($filetmpLoc);
if( $width <10 || $height <10 ){
//the image has not dimenssion
echo 'The Image has no dimension.Try again!';
exit();
}else{
// The image is has dimension so its OK
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
//check the size of the image
if($filesize > 1048576){
echo 'Your avator file size was larger than 1mb.';
exit();
}else if(!preg_match('/\.(gif|png|jpg)$/i',$fileName)){
echo"Your avator file was not JPG,PNG or GIF type.Try again.";
exit();
}else if($fileErrMsg == 1){
echo "Unknoan Error occured. Upload Fail.";
exit();
}
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");
if( $moveResult !=true){
echo 'Upload Fail.';
exit();
}else{
//resize the image
include_once("include/resizeimage.php");
$target_file = "user/$logged_user/$db_file_name";
$resize_file ="user/$logged_user/$db_file_name";
$wmax = 200;
$hmax = 230;
img_resize($target_file,$resize_file,$wmax,$hmax,$fileExt);
$sql = "UPDATE mygust SET avatar = '$db_file_name' WHERE username='$logged_user' LIMIT 1";
$query = mysqli_query($con,$sql);
mysqli_close($con);
exit();
}
}
}
?>
My HTML code is:
<form id="u_pro_pic" method="post" enctype="multipart/form-data" onSubmit="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<h2>Set your Profile Avator</h2><br>
<div id="av_wrap"><div id="avator_div"><img src="image/blank-profile.png" class="avator" title="Chose a file to upload" onClick="triggerUpload(event,'avator')"></div>
<div id="ad_clarleft">
<input type="button" class="add" title="Choose a file to upload" onClick="triggerUpload(event,'avator')" value="Add Avator"><br>
<hr>
<p>These brethren have uploaded their's and you should too. </p>
</div>
</div>
<input name="avator" type="file" id="avator" form="u_pro_pic" onChange="readURL(this)">
<input type="submit" name="u_avator" id="sumit" class="avt" value="Upload">
</form>
Please any help would be much appreciating.

PHP tries to move your uploaded file to a folder that does not exist:
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");
The path "/upload" does not look like a correct windows path. Change it to something like "C:\xampp\htdocs\learnphp\upload". Create this folder manually if it does not exist.
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"C:/xampp/htdocs/learnphp/upload/$logged_user/$db_file_name");

The reason why you're getting an error on the upload, is that the folder itself does not exist; least that's the impression I am getting from it and to be honest, we don't know if efc5ad334bca9f31b19d85a6cc2ada57 exists or not.
Sidenote: Use file_exists() which is referenced further down in this answer.
Since you are using sessions for $logged_user as the username session array, make sure the session was started inside all files using sessions. session_start(); must reside inside all files, and at the top of your code.
It is good practice to check if the session is also set using isset() or !empty().
References:
http://php.net/manual/en/function.session-start.php
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
If not (which am pretty sure it doesn't), you would first need to create it using the mkdir() function.
http://php.net/manual/en/function.mkdir.php
The syntax is: mkdir("/path/to/my/dir", 0700); - 0700 can be changed to 0755 which is the usual setting for folders and it must be set so that the folder can be written to, using chmod.
http://php.net/manual/en/function.chmod.php
The syntax being, one of the 3 listed from the manual:
chmod("/somedir/somefile", 755); // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755); // octal; correct value of mode
So, you will need to use the mkdir() function after the session file and before "moving" it to the folder created by $logged_user and its associated name.
I.e.:
mkdir("/path/to/your/dir", 0700); // you can use variables here
$moveResult = move_uploaded_file(...);
This part of your code /upload/ suggests using a full server path syntax.
move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name")
Either you use what your full server path is, for example:
/var/usr/public/upload/
or as referenced in another answer given C:/xampp/htdocs/learnphp/upload/
or a relative path:
I.e.:
upload/ or ../upload/ depending on the execution location of your script. The former being if executed from the root of the public area.
Nota: I am unsure if -416649605.jpg is the actual filename being uploaded, or if there is anything missing before the hyphen, or the hyphen is being added somewhere. You will need to look into that.
Pulled from my comment:
Now, if you're going to use a BLOB, that may not be big enough and may have to use a LONGBLOB https://dev.mysql.com/doc/refman/5.0/en/blob.html.
However, when using a BLOB to insert into the db directly, you will have to use mysqli_real_escape_string() for that, otherwise it won't work; you will get a syntax error thrown back.
Reference:
http://php.net/manual/en/mysqli.real-escape-string.php
So, keep on using error reporting until you can figure out where the problems may be occuring.
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);
// if using MySQL
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Also add or die(mysqli_error($con)) to $query = mysqli_query($con,$sql); to check for database errors.
Reference:
http://php.net/manual/en/mysqli.error.php
Additional reference:
http://php.net/manual/en/function.file-exists.php (check if a file/folder exists)
Footnotes:
Your code in its present state is open to an SQL injection. Use a prepared statement
References:
https://en.wikipedia.org/wiki/Prepared_statement
How can I prevent SQL injection in PHP?
I believe I have given you enough information in order to point you in the right direction that will and hope will lead you to success, cheers!

Replace your $moveResult statement with the following two statement as you have to store the file in folder with a specific name.
$destination = "./".$_FILES['avator']['name'];
$moveResult = move_uploaded_file( $_FILES['avator']['tmp_name'],$destination);

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

Trying to display images from a filesystem in php

Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end

Not able to upload and save image in PHP

I'm trying to upload a image in PHP but the image is not getting saved in the directory on the server. However I'm able to save the path of the image in the database. Please help. Here is the piece of code. I'm not getting any error in the web page.
<?php
error_reporting(E_ALL);ini_set('display_errors', 'On');
session_start();
$logged_user_name = $_SESSION['user_name'];
$logged_user_type = $_SESSION['user_type'];
$logged_user_team_id = $_SESSION['team_id'];
$logged_user_team_name = $_SESSION['team_name'];
$uploaded_profile_image = $_POST['propic'];
//$uploaded_profile_image = $_FILES['propic']['name'];
include_once("classes/doEverything_framework.php");
function upload_image()
{
$db_connection_obj = new database_connection;
$db_connection = ($db_connection_obj -> open_database_connection());
global $logged_user_name;
global $uploaded_profile_image;
$profile_image_upload_dir = 'images/uploaded_profile_pics/';
if ($uploaded_profile_image != null || $uploaded_profile_image != "")
{
//file_put_contents($uploaded_profile_image);
move_uploaded_file($uploaded_profile_image, $profile_image_upload_dir);
//file_put_contents($uploaded_profile_image,$profile_image_upload_dir);
$uploaded_profile_image_link = $profile_image_upload_dir.$uploaded_profile_image;
$sql = "UPDATE user_login_table SET user_profile_image = '$uploaded_profile_image_link' WHERE user_name = '$logged_user_name'";
mysql_query($sql, $db_connection);
}
$db_connection_obj -> close_database_connection($db_connection);
}
?>
HTML Code:
<form enctype="multipart/form-data" name="uploadprofileimage" onsubmit="" action="" method="post">
<input type="file" name="propic" id="propic" onclick="" >
<input type="submit" value="Upload" name="upload" id="submit" >
<br>
<label for="propic" id="picerrorlabel"></label>
</form>
<?php
if(isset($_POST['upload'])) //This ensures the function runs only when the submit button is clicked.
{
upload_image();
}
The correct way to access selected File is as follows
$uploaded_profile_image = $_FILES['propic']['name'];
Make sure you are uploading file within limit of configured file size in php.ini (upload_max_filesize). rest all should work.
Correction 1:-
Your are passing only directory name in move_uploaded_dir. I think you should pass complete image path. and $uploaded_profile_image should be your image tmp_name.
move_uploaded_file($_FILES['propic']['tmp_name'], $profile_image_upload_dir.$uploaded_profile_image);
Correction 2:- You can't get image name in $_POST. so it should be
$uploaded_profile_image = $_FILES['propic']['name'];
You cannot get image or any file in $_POST['propic']; the correct way to access file or image is by using $_FILES
so you should use $uploaded_profile_image = $_FILES['propic']['name'] in move_uploaded_file function. Make sure to check upload_max_filesize limit in php.ini.
To upload a file in php use move_uploaded_file()
$path="upload/".$_FILES["file"]["name"]; // This specifies the path to save file
move_uploaded_file($_FILES["file"]["tmp_name"],$path);
First You cant get file value in POST method so you need to user $_FILE to get file. So you need to replace line no 5 with this :
$uploaded_profile_image = $_FILES['propic'];
Another mistake in your code is while moving uploaded file where source params is expected to be temporary location of file :
move_uploaded_file($uploaded_profile_image['tmp_name'], $profile_image_upload_dir.$uploaded_profile_image['name']);
Now in line no 27 you can get file name to store in database this way :
$uploaded_profile_image_link = $profile_image_upload_dir.$uploaded_profile_image['name'];

White empty images after PHP upload and MySQL insertion

I have created a PHP and MySQL script which successfully uploads submitted images via PHP to a folder on my server, and then adds the filename with extension to my MySQL database.
With an FTP program I can see the submitted image inside the correct folder on my server with its correct file size. However, when I type the file path of the newly uploaded image (http://xxxxxx.com/images/image.jpg) into my browser, I get a blank page. Also when I try to import the image onto a website, nothing shows up.
However, when I re-download the image via the FTP program onto my computer, I can see that the image is TOTALLY OK. What am I missing?
Excerpts of my code are below:
<?php
// getting current post id and slug
$pid = $_POST['pid'];
$slug = $_POST['slug'];
//This is the directory where images will be saved
$target = '../company/'.$slug.'/images/';
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$pic = ($_FILES['image']['name']);
$fileTmpLoc = ($_FILES["image"]["tmp_name"]);
$extract = explode(".", $pic);
$fileExt = end($extract);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$rename = rand(100000000000,999999999999).".".$fileExt;
// check for correct filetype
if (!preg_match("/\.(gif|jpg|png)$/i", $pic) ) {
header("location: ../message.php?msg=ERROR: incorrect filetype");
exit();
}
include_once "../database-connect.php";
//Writes the information to the database
mysqli_query($dbconnection,"UPDATE companies SET picture='$rename' WHERE ID='$pid'") ;
//Writes the photo to the server
if(move_uploaded_file($fileTmpLoc, "../company/'.$slug.'/images/$rename"))
{
.... etc
What am I missing that it does not show up in the browser?
Maybe the path is not what you think it is when you try to link to the image or when you try to open it.
Note that this looks very wrong:
if(move_uploaded_file($fileTmpLoc, "../company/'.$slug.'/images/$rename"))
This will add two quotes and two dots to your path, so if $slug is some_company, the path will be:
/company/'.some_company.'/images/123456789.jpg
Perhaps you don't see or didn't notice that in your ftp program.
Also note that you have an sql injection problem, you should switch to prepared statements with bound variables.
Problem was indeed the URL output structure. Have changed it, like jeroen suggested:
if(move_uploaded_file($fileTmpLoc, "../images/$rename"))
Works fine now

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