I'm trying to set up some image handling for a webpage I'm creating, but I can't get move_uploaded_file() to work properly... I keep getting these errors:
Warning: move_uploaded_file(/htdocs/PHP/Pictures/picture.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /opt/lampp/htdocs/PHP/useredit.php on line 17
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpY0KKxH' to '/htdocs/PHP/Pictures/picture.jpg' in /opt/lampp/htdocs/PHP/useredit.php on line 17
My code looks like this:
if(isset($_FILES['image_file']))
{
$img_tmp_name = $_FILES['image_file']['name'];
$img_dir = "/htdocs/PHP/Pictures/";
$img_name = $img_dir . $img_tmp_name;
if(move_uploaded_file($_FILES['image_file']['tmp_name'],$img_name))
{
list($width,$height,$type,$attr) = getimagesize($img_name);
switch($type)
{
case 1:
$ext = ".gif";
break;
case 2:
$ext = ".jpg";
break;
case 3:
$ext = ".png";
break;
default:
echo "Image format not accepted";
}
$query = "UPDATE profile_pic SET img_path=$img_name WHERE uid='$uid'";
$img_id = mysql_insert_id();
$new_img_name = $img_dir . $img_id . $ext;
rename($img_name, $new_img_name);
}
}
if(mysql_query($query)or die('Error: ' . mysql_error()))
{
header("Refresh:0; url='control.php'");
}
The folder PHP/Pictures exist. How do I fix this?
You've got some major security and logistical problems with this code:
a) You don't check if the upload succeeded and proceed as if it has. There's exactly ONE way for an upload to succeed, and far too many reasons for it to fail.
if ($_FILES['image_file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code {$_FILES['image_file']['error']}");
}
b) You're using the filename provided by the user in the path to save on your server. A malicious user can embed pathing data in that filename and specify any location on your server they want. e.g.
$_FILES['image_file']['name'] = '../../../../../../etc/passwd';
$img_dir should contain a path relative to you current file and not from root folder.
if your current directory contains upload_file.php (ur code) and a folder hierarchy like PHP/Pictures/
then $img_dir="/PHP/Pictures/";
Related
I am making a form in which user can upload data + an image if he likes using jquery ajax and PHP . So far everything works well on the data side, but on the image upload PHP i am having a problem uploading the file to the right location. The query is working fine and submitting the right data to the table. Can you please help me with the image upload. I tried to debug by using a couple of things but so far everything looks right.
here is my php file script:
if(isset($_POST['discussion_title'], $_POST['discussion_subjects'], $_POST['discussion_textarea'])) {
$user_id = (int)$_SESSION['user_id'];
$title = mysql_prep($_POST['discussion_title']);
$link = mysql_prep($_POST['discussion_link']);
$subject = mysql_prep($_POST['discussion_subjects']);
$discussion = mysql_prep($_POST['discussion_textarea']);
$discussion_timestamp = time();
if ($_FILES["discussion_image"]["name"] != "") {
$test = explode(".", $_FILES["discussion_image"]["name"]);
$extension = end($test);
$name = rand(100, 9999999999);
$file_temp = $_FILES['discussion_image']['tmp_name'];
$file_path = 'uploaded_pictures/uploads/' . $user_id . '/'. $name .'.'.$extension;
$file_path = mysqli_real_escape_string($connection, $file_path);
move_uploaded_file($file_temp, $file_path); // move_uploaded_file() is a built in function of PHP
$query = "INSERT INTO discussions_table (user_id, title, link, image_link, subject, discussion, discussion_timestamp) VALUES ($user_id, '$title', '$link', '$file_path', '$subject', '$discussion', $discussion_timestamp)";
//$save_path = "uploaded_pictures/uploads/" . $user_id ."/$user_id.png";
$save_path = 'uploaded_pictures/uploads/' . $user_id . '/'. $name.'.'.$extension;
$save_path_small = "uploaded_pictures/uploads/" . $user_id . "/" . $name.'small.'.$extension;
create_thumbnail($file_path, $save_path, 250, 250); // creates thumbnail for profile picture
create_thumbnail($file_path, $save_path_small, 50, 50); // creates thumbnail for small user picture
var_dump($_FILES['discussion_image']['tmp_name']);
} else {
$query = "INSERT INTO discussions_table (user_id, title, link, subject, discussion, discussion_timestamp) VALUES ($user_id, '$title', '$link', '$subject', '$discussion', $discussion_timestamp)";
}
$result = mysqli_query($connection, $query);
}
and here is the error being given in the alert() because i used var_dump
Warning: move_uploaded_file(uploaded_pictures/uploads/20/499297822.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in D:\wamp\www\asserter\widgets\discussion_board_submit.php on line 22
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'D:\wamp\tmp\php260.tmp' to 'uploaded_pictures/uploads/20/499297822.jpg' in D:\wamp\www\asserter\widgets\discussion_board_submit.php on line 22
Warning: getimagesize(uploaded_pictures/uploads/20/499297822.jpg) [function.getimagesize]: failed to open stream: No such file or directory in D:\wamp\www\asserter\includes\create_thumbnail.php on line 4
Warning: getimagesize(uploaded_pictures/uploads/20/499297822.jpg) [function.getimagesize]: failed to open stream: No such file or directory in D:\wamp\www\asserter\includes\create_thumbnail.php on line 4
string(22) "D:\wamp\tmp\php260.tmp"
ok it worked. Thanks everyone for your help. The problem was with the directory, i should go back ../ to be able to upload the image
How to create directory in php? - Use this to create directories, I have answered over there. It will help you to create directories for multi-user. Later you can get which user has uploaded what all files.
for error Undefined offset : 1 in php you should set the values using isset() for
$src_pos[1] , $new_size[0], $new_size[1], $size[0], $size[1]
I am still having trouble hashing my pictures when I upload them . I have this code :
$target_dir = "images/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
hash_file('sha256', $target_file );
// Check if image file is a actual image or fake image
if(isset($_POST["change"])) {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$sql = "UPDATE users SET userPic = '".$_FILES['fileToUpload']['name']."' WHERE username = '" . $username . "'";
$check = $conn->query($sql);
if($check !== false) {
echo "<a href = profile.php> Profile pciture has been changed </a>" .
$check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
} else {
echo"did not change";
}
and I am getting this error :
Warning: hash_file(images/uploads/english_royal_family_tree.jpg): failed to open stream: No such file or directory
I have been trying for more than a week . No one is really helping and people just keep on voting down my question and aren't giving any help . Can someone please help me ?
Firstly, hash_file() is expecting a file to already exist and you're trying use that method before the file gets uploaded; that's why your code failed and threw you that error.
What you need to do is to see if that file exists and then hash it.
If this is really want you want to do, then you can base yourself on the following and remember to store the renamed file while retaining its original extension; there are links at the end of the answer.
Note: As I mentioned in comments, you need to hash the file and not the whole destination folder and the file. That would be impossible to retrieve.
Echo the variable for what was assigned to hash_file(). You will also get your hash name (only) shown minus its extension.
Check for errors and make sure the folder has been granted proper permissions.
<?php
// check for errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$file_name = $_FILES['fileToUpload']['name'];
$sent_file = move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
if (file_exists("images/uploads/" . $_FILES["fileToUpload"]["name"]))
{
echo $the_file = $_FILES["fileToUpload"]["name"] . " exists.";
// its new location and hashing the filename only.
$var = hash_file('sha256', $the_file );
echo $var;
// store your renamed file here in your database
// using the assigned $var variable.
}
Also check for errors on the query with mysqli_error($conn).
However, you're going to end up with problems here to show that image, since now and for example in using "file.jpg" will produce the following hash:
cf80cd8aed482d5d1527d7dc72fceff84e6326592848447d2dc0b0e87dfc9a90
I don't know how you plan on showing the image(s), but it will no longer keep the .jpg extension.
In order to retain the image's file extension, you basically need to rename the uploaded file(s).
Here are a few good references on Stack (that I've had success with in the past) that you can look at and implement it in your code. :
How to rename uploaded file before saving it into a directory?
Rename uploaded file (php)
There is indeed no better way to learn, IMHO.
Edit:
This is an excerpt from a script I wrote recently. Base yourself on the following.
Note: You shouldn't use hashing methods such as anything from the SHA family or MD5 as the file name, since those produce the same hash and has no uniqueness to them.
Important: If people upload from a mobile device, most of them have "image.jpg" as the default name, so it needs to be renamed and given a unique method.
Using the date and time is one way. You can also add uniqid() to it by assigning a variable to it and append to the new file name, or a combination of MD5 and uniqid() is a good bet.
You will need to do a few modifications to it of course. The $year variable is something I used but you can get rid of those instances and replace them with your own.
$year = date("Y");
$pdf_file = $_FILES['fileToUpload']["name"];
$uploaded_date = date("Y-m-d_h-i-s_A"); // this could be another unique method.
$target_dir = "../upload_folder/" . $year . "/";
$ext = explode('.',$_FILES['fileToUpload']['name']);
$extension = $ext[1];
$newname = $ext[0].'_'.$uploaded_date;
$full_local_path = $target_dir.$newname.'.'.$extension;
$new_full_name = $newname.'.'.$extension;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $full_local_path)) {
echo "The file ". $newname . " has been uploaded.";
echo "<hr>";
$file_link = "/upload_folder/$year/$new_full_name";
// other code such as saving to a database...
}
I'm having difficulty in copying an image from one folder to another, now i have seen many articles and questions regarding this, none of them makes sense or work, i have also used copy function but its giving me an error. " failed to open stream: No such file or directory" i think the copy function is only for files. The image i wanna copy is present in the root directory. Can anybody help me please. What i am doing wrong here or is there any other way???
<?php
$pic="somepic.jpg";
copy($pic,'test/Uploads');
?>
You should write your code same as below :
<?php
$imagePath = "/var/www/projectName/Images/somepic.jpg";
$newPath = "/test/Uploads/";
$ext = '.jpg';
$newName = $newPath."a".$ext;
$copied = copy($imagePath , $newName);
if ((!$copied))
{
echo "Error : Not Copied";
}
else
{
echo "Copied Successful";
}
?>
You should have file name in destination like:
copy($pic,'test/Uploads/'.$pic);
For your code, it must be like this:
$pic="somepic.jpg";
copy($pic,'test/Uploads/'.$pic);
Or use function, like this:
$pic="somepic.jpg";
copy_files($pic,'test/Uploads');
function copy_files($file_path, $dest_path){
if (strpos($file_path, '/') !== false) {
$pathinfo = pathinfo($file_path);
$dest_path = str_replace($pathinfo['dirname'], $dest_path, $file_path);
}else{
$dest_path = $dest_path.'/'.$file_path;
}
return copy($pic, $dest_path);
}
i have just come across what i think i need for my front end multi uploader script in joomla.
Mootools fancy upload looks great! but i am having trouble when i uncomment the script that uploads the images inside the uploads folder?
All i have done is uncommented the default script inside the test file and created a folder called uploads which i set to 757 and also tried 777
But for some reason the uploader now returns some strange error about md 5 hash stuff?
eastern_beach_jetty.jpgAn error occured:
Warning: md5_file(/tmp/phpUjHol4) [function.md5-file]: failed to open stream: No such file or directory in /home/user/www.mydomain.com.au/test/server/script.php on line 133
{"status":"1","name":"eastern_beach_jetty.jpg","hash":false}
The fancy uploader website from where i got the script is here http://digitarald.de/project/fancyupload/
Any help on this would be so greatly apprecited,
thank you.
John
Coincidentally, I did the same mistake as you, the reason is that the first move tmp file to the destination folder, and then referring to the tmp file, which no longer exists, because it is in the target folder. I know that the late response, but it was as if someone had the same problem.
Not:
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
Yes:
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];
I have this code I been working on but I'm having a hard time for it to work. I did one but it only works in php 5.3 and I realized my host only supports php 5.0! do I was trying to see if I could get it to work on my sever correctly, I'm just lost and tired lol
Ol, sorry stackoverflow is a new thing for me. Not sure how to think of it. As a forum or a place to post a question... hmmm, I'm sorry for being rude with my method of asking.
I was wondering i you could give me some guidance on how to properly insert directory structures with how i written this code. I wasn't sure how to tell the PHP where to upload my files and whatnot, I got some help from a friend who helped me sort out some of my bugs, but I'm still lost with dealing with the mkdir and link, unlink functions. Is this how I am suppose to refer to my diretories?
I know php 5.3 uses the _ DIR _ and php 5.0 use dirname(_ _ FILE_ _), I have tried both and I get the same errors. My files are set to 0777 for testing purposes. What could be the problem with it now wanting to write and move my uploaded file?
} elseif ( (file_exists("\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists("\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) {
$errors['img_fileexists'] = true;
}
if (! empty($errors)) {
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
// Create thumbnail
if (empty($errors)) {
// Make directory if it doesn't exist
if (!is_dir("\\uploads\\{$username}\\images\\banner\\thumbs\\")) {
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
$folders = explode("\\", $dir);
// Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec)
$dirTmp = '';
foreach ($folders as $fldr) {
if ($dirTmp != '') { $dirTmp .= "\\"; }
$dirTmp .= $fldr;
mkdir("\\".$dirTmp); //ignoring errors deliberately!
}
// Check again whether it exists
if (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
}
if (empty($errors)) {
// Move uploaded file to final destination
if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
} else {
// Create thumbnail in new dir
if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
$errors['thumb'] = true;
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
}
}
}
}
// Record in database
if (empty($errors)) {
// Find existing record and delete existing images
$sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
$numResults = mysql_num_rows($result);
if ($numResults == 1) {
$row = mysql_fetch_assoc($result);
// Delete old files
unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
}
// Update/create record with new images
if ($numResults == 1) {
$sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
} else {
$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
}
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
}
// Print success message and how the thumbnail image created
if (empty($errors)) {
echo "<p>Thumbnail created Successfully!</p>\n";
echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n";
echo "<br />\n";
}
}
I get the following errors:
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
One way is to check from within your code whether a certain command/function is available for use. You can use the function_exists function for that eg:
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set("GMT");
}
else
{
echo 'date_default_timezone_set is not supported....';
}
Ahh! I'm sorry, didn't mean to vent my frustration on you guys. But I have been at this for hours now it seems.
Like i mentioned this code works but since my server is picky I can't user the 5.3 syntax I coded. This is my attempt to make it work on the 5.0 php my server has.
In particular I think there is something wrong with the mkdir() and the unlink() functions.
if you go to www.helixagent.com log in with test/test then in the url go to /upload2.php then you will see the errors its throwing at me.
well, it works perfect if i use 5.3 and DIR but since I'm on 5.0 i tried a different method
the errors i get are
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
It looks like you don't have access to the folder (or file)
/uploads/$username/images/banner/$filename
which could be because of a basedir restriction on the host (e.g. you may not leve the parent directory /services/webdata/) or just a missing permission in the os.
Try to (temporary) set permission of /uploads/ to 777 or execute the script from console to see if you have a basedir restriction.
Take a closer look at the paths in the error messages:
./uploads/saiyanz2k/images/banner/azumanga-wall.jpg
/services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php
The destination is a relative path, most likely relative to upload2.php's directory. The one relative path I see is the line:
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
Which should probably be:
// Take directory and break it down into folders
$dir = "\\uploads\\{$username}\\images\\banner\\thumbs";
Actually, it should be
$dir = "/uploads/{$username}/images/banner/thumbs";
since PHP supports using a forward slash as directory separator on all platforms, while the backslash is only supported on MS platforms.