uploading an image using PHP - php

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]

Related

Failed to upload the image in mysql server

I have uploaded the project on the server every thing is working fine except for the few things.
I am not able to uplaod the file images on the server please check the errors.
I have even set the permission to 777.
Warning: move_uploaded_file(../images/fail to upload.jpg): failed to open stream: No such file or directory in /srv/disk14/2293074/www/cms.mohsinyounas.info/admin/includes/add_posts.php on line 15
Warning: move_uploaded_file(): Unable to move '/tmp/phpx2WZ8c' to '../images/fail to upload.jpg' in /srv/disk14/2293074/www/cms.mohsinyounas.info/admin/includes/add_posts.php on line 15
Thank you.
<?php
include "./function.php";
global $con;
if(isset($_POST['create_post'])) {
$post_image = $_FILES['post_image']['name'];
$post_image_temp = $_FILES['post_image']['tmp_name'];
move_uploaded_file("$post_image_temp","../images/$post_image");
$sql = "INSERT INTO posts (post_image) VALUES ('$post_image')";
$result = mysqli_query($con,$sql);
confirm($result);
}
?>
Change this code you have to remove "" from variable in move_uploaded_file()
<?php
include "./function.php";
global $con;
if(isset($_POST['create_post'])) {
$post_image =$_FILES['post_image']['name'];
$post_image_temp =$_FILES['post_image']['tmp_name'];
$path = "../images/".$post_image;
move_uploaded_file($post_image_temp,$path);
$sql = "INSERT INTO posts (post_image)
VALUES ('$post_image')";
$result=mysqli_query($con,$sql);
confirm($result);
}
?>

PHP permission Denied using unlink and rmdir

i've been trying to figure out why my Php code is giving me a annoying error. I've tried countless functions from previous post but the error its been giving is "Permission Denied". From my understanding either i have to have special privledges to delete files, etc.. I've tried multiple solutions but I'm still getting this error. If anyone can point me in the right direction, that'll be great. Ive post a snippet of my code below.. Thanksss
$first_sub = "my_dir";
if(is_dir($first_sub)){
$read_sub1 = opendir($first_sub);
while(false !== ($files = readdir($read_sub1))){
if($files!="." && $files!=".."){
unlink($first_sub ."/". $files);
}
}
closedir($read_sub1);
You should set proper permission to your server directories:
Visit: http://bd1.php.net/chmod
<?php
// Read and write for owner, nothing for everybody else
chmod($first_sub ."/". $files, 0600);
// Read and write for owner, read for everybody else
chmod($first_sub ."/". $files, 0644);
// Everything for owner, read and execute for others
chmod($first_sub ."/". $files, 0755);
// Everything for owner, read and execute for owner's group
chmod($first_sub ."/". $files, 0750);
?>
just before unlink you can call this function.
I got that an error from unlink permission denied.
But I fix it. The error displays like this unlink(../foldername/) Permission denied.
My wrong code is like this:
$image = select_table('webpage', 'wp_name', '$id');
$update = "UPDATE webpage SET wp_image = NULL, wp_modifiedby = '{$position}', wp_datemodified = '{$date_now}' WHERE wp_name = '{$id}'";
if ( unlink('../webpage/'.$image_dir) && $qry_update = mysqli_query($connection, $update) ) {
// success
} else {
// failed
}
now i fix it
my correct code is like this:
$image = select_table('webpage', 'wp_name', $id);
$update = "UPDATE webpage SET wp_image = NULL, wp_modifiedby = '{$position}', wp_datemodified = '{$date_now}' WHERE wp_name = '{$id}'";
if ( unlink('../webpage/'.$image['wp_image']) && $qry_update = mysqli_query($connection, $update) ) {
// success
} else {
// failed
}
For those who land on this page, it may be as simple as not setting $files to an existing file.
It is unfortunate, but I found that the message: Warning: move_uploaded_file(): Unable to move can also mean file not found.
Not likely the cause of this OP's problem, but certainly worth verifying the file represented by the variable you pass actually exists in the directory.

Trouble moving picture with move_uploaded_file()

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/";

MootoolsFancy Upload

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'];

can someone help me fix my code?

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.

Categories