upload images in php - php

ho everyone i am trying to upload images but i got a warning that i didn't understand
here is the code
// print out contents of $_FILES ARRAY
print "Print out of the array of files: FILES <br>";
print_r($_FILES);
print "<br><br>";
$F1 = $_FILES["fname"];
print_r($F1);
print "<br><br>";
// 0 means a successful transfer
if ($_FILES["fname"]["error"] > 0) {
print "An error occurred while uploading your file";
exit(0);
}
// only accept jpg images pjpeg is for Internet Explorer.. should be jpeg
if (!($_FILES["fname"]["type"] == "image/pjpeg")) {
print "I only accept jpg files!";
exit(0);
}
// divide size by 1024 to get it in KB
if ($_FILES["fname"]["size"] / 1024 > 50) {
print "Your gif file is too large! Less that 50KB please!";
exit(0);
}
// check that file is not already there in your uploads folder
if (file_exists("Uploads/" . $_FILES["fname"]["name"])) {
print "$F1[name] already exists. Choose another name for your file.";
exit(0);
}
// move file from temp location on server to your uploads folder
**move_uploaded_file($_FILES["fname"]["tmp_name"], "Uploads/".$_FILES["fname"]["name"]);**
print "Stored in:"." Uploads/".$_FILES["fname"]["name"];
// save location of upload to text file uploads.txt for later use
$datafile = fopen("uploads.txt","a");
flock($datafile,1);
fwrite($datafile, "Uploads/".$_FILES["fname"]["name"]."\n");
flock($datafile,3);
fclose($datafile);
and the warning is( refer to bold line)
Warning:
move_uploaded_file(Uploads/avatar3.jpg):
failed to open stream: No such file or
directory in
/home/www/mariam.awardspace.info/php/posts.php
on line 57
Warning: move_uploaded_file(): Unable
to move '/tmp/phprqcpQB' to
'Uploads/avatar3.jpg' in
/home/www/mariam.awardspace.info/php/posts.php
on line 57
thanks in advance

2 things come to mind.
Try using a path like
$_SERVER['DOCUMENT_ROOT'].'/path/to/file.jpg');
Then make sure the uploads folder exists in the root folder of your site

The directory "Uploads" does not exist or you don't have sufficient permissions to write to it.

Related

Warning: move_uploaded_file(): The second argument to copy() function cannot be a directory

There is no solution, as i have searched a lot on moving my uploaded image into directory here is my php code :
<?php
//Profile Image upload script
if (isset($_FILES['profilepic'])) {
if (((#$_FILES["profilepic"]["type"]=="image/jpeg") || (#$_FILES["profilepic"]["type"]=="image/png") || (#$_FILES["profilepic"]["type"]=="image/gif"))&&(#$_FILES["profilepic"]["size"] < 1048576)) //1 Megabyte
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name = substr(str_shuffle($chars), 0, 15);
$dir = "userdata/profile_pics/$rand_dir_name";
mkdir($dir);
move_uploaded_file($_FILES["profilepic"]["tmp_name"],"userdata/profile_pics/$rand_dir_name".$_FILES["profile‌​pic"]["name"]);
$profile_pic_name = $_FILES["profilepic"]["tmp_name"];
echo $profile_pic_name;
$profile_pic_query = mysqli_query($conn,"UPDATE users2 SET profile_pic='$rand_dir_name/$profile_pic_name' WHERE username='$user'");
}
else
{
$msg5 = "Invailid File! Your image must be no larger than 1MB and it must be either a .jpg, .jpeg, .png or .gif";
}
}
?>
but when I try to upload image,it creates the random folder in userdata/profile_pics but it doesn't move the file into random folder directory i have also created a custom php.ini file with file_uploads = On, but i recieve the following warning when i submit the form :-
Warning: move_uploaded_file(): The second argument to copy() function cannot be a directory in /home/rahulkapoor90/public_html/note.php on line 26
Warning: move_uploaded_file(): Unable to move '/tmp/phpO592dd' to 'userdata/profile_pics/zAGC9wOhVyoe3R5' in /home/rahulkapoor90/public_html/note.php on line 26
/tmp/phpO592dd
For anyone else who comes across this error, in my case it was a permissions issue. I re-factored some legacy code and checked the wrong directory for permissions and instead kept getting this misleading error message.
Wasted few hours to get the correct cause. You can try 2 things
Verify your destination folder
`$destdir="YOUR-COMPLETE-DESTINATION-FOLDER/uploads/";
if(is_dir($destdir) && is_writable($destdir))
{echo "<strong>UPLOAD DIRECTORY EXIST & WRITABLE</strong>";}
else
{echo "<strong>ISSUE WITH UPLOAD DIRECTORY</strong>";}`
Confirm 2nd parameter of move_uploaded_file is a file name NOT A DIRECTORY NAME
In my case this turned to be the issue
if(move_uploaded_file($tempname,"$destdir/".$_FILES['profilepic']['name']"))
{echo 'FILE UPLOADED SUCCESSFULLY';}
else
{echo "FAILED TO UPLOAD";}

Upload image to existing folder PHP

<?php
include('includes/db.php');
$drinks_cat = $_POST['drinks_cat'];
$drinks_name = $_POST['drinks_name'];
$drinks_shot = $_POST['drinks_shot'];
$drinks_bottle = $_POST['drinks_bottle'];
$drinks_availability = 'AVAILABLE';
$msg = "ERROR: ";
$itemimageload="true";
$itemimage_size=$_FILES['image']['size'];
$iname = $_FILES['image']['name'];
if ($_FILES['image']['size']>250000){$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload.<BR>";
$itemimageload="false";}
if (!($_FILES['image']['type'] =="image/jpeg" OR $_FILES['image']['type'] =="image/gif" OR $_FILES['image']['type'] =="image/png"))
{$msg=$msg."Your uploaded file must be of JPG , PNG or GIF. Other file types are not allowed<BR>";
$itemimageload="false";}
$file_name=$_FILES['image']['name'];
$add="images"; // the path with the file name where the file will be stored
if($itemimageload=="true")
{
if (file_exists($add) && is_writable($add))
{
if(move_uploaded_file ($_FILES['image']['tmp_name'], $add."/".$_FILES['image']['name']))
{
echo "Image successfully updated!";
}
else
{
echo "Failed to upload file Contact Site admin to fix the problem";
}
}
else
{
echo 'Upload directory is not writable, or does not exist.';
}
}
else
{
echo $msg;
}
$dir = $add."/".$iname;
echo "<BR>";
// Connects to your Database
mysql_query("INSERT INTO `product_drinks`(`drinks_id`, `drinks_cat`, `drinks_name`, `drinks_shot`, `drinks_bottle`, `drinks_image`, `drinks_availability`) VALUES (NULL,'".$drinks_cat."', '".$drinks_name."','".$drinks_shot."','".$drinks_bottle."','".$dir."','".$drinks_availability."')") or die("insert error");
Print "Your table has been populated";
?>
The code I'm working on works but i have to create a new "image" folder for my admin folder. Is there any way that I could upload the file outside the admin folder and move it to to the original "image" folder". I know it's quite confusing but my directory looks like this.
clubmaru
-admin
-images
-css
-images
-js
You may be looking for PHP's rename function. http://php.net/manual/en/function.rename.php
Set the oldname parameter to the file (with its path) and the newname parameter to where you want it to be (along with the new path, obviously)
Just ensure the "image folder" you want to move the file to has the correct permissions set ensure it's writable. You also may want to consider changing the parameter in your move_uploaded_file to put the file where you want it in the first place!
Yes there is a way, you need to change the path. Right now you have the path as images/$name which means that it will put the file in the images directory found in the local directory to the script that is running.
Using directory layout:
clubmaru
->admin
->script.php (the upload file)
->images
->css
->images
->js
You make the path relative (or find another alternative)
$add="../css/images";
This means, go up a directory, go into css then into images.

Warning: copy(..): failed to open stream: No such file or directory in

I'm fairly new to PHP and was trying to create a simple PHP file upload system.
I followed a tutorial from (http://www.phpeasystep.com/phptu/2.html). I only altered the $HTTP_POST_FILES, as it was giving me errors, and from what I read it's old in PHP.
I got less error messages but I am getting an error in the copy() function, with these given error messages:
Warning: copy(Task2/uploads/anonymous.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\Task2\upload.php on line 13
Warning: copy(Task2/uploads/DSCF4639.JPG): failed to open stream: No such file or directory in C:\xampp\htdocs\Task2\upload.php on line 14
Warning: copy(Task2/uploads/jien maroon.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\Task2\upload.php on line 15
I thought it was a problem with permission (read/write permissions in Windows 7), but from a quick google search it seems that XAMPP is set by default to deal with permission on Win 7.
This is the code:
<?php
//set where you want to store files
//in this example we keep file in folder upload
//$_FILES['ufile']['name']; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path1= "Task2/uploads/".$_FILES['ufile']['name'][0];
$path2= "Task2/uploads/".$_FILES['ufile']['name'][1];
$path3= "Task2/uploads/".$_FILES['ufile']['name'][2];
//copy file to where you want to store file
copy($_FILES['ufile']['tmp_name'][0], $path1);
copy($_FILES['ufile']['tmp_name'][1], $path2);
copy($_FILES['ufile']['tmp_name'][2], $path3);
//$_FILES['ufile']['name'] = file name
//$_FILES['ufile']['size'] = file size
//$_FILES['ufile']['type'] = type of file
echo "File Name :".$_FILES['ufile']['name'][0]."<BR/>";
echo "File Size :".$_FILES['ufile']['size'][0]."<BR/>";
echo "File Type :".$_FILES['ufile']['type'][0]."<BR/>";
echo "<img src=\"$path1\" width=\"150\" height=\"150\">";
echo "<P>";
echo "File Name :".$_FILES['ufile']['name'][1]."<BR/>";
echo "File Size :".$_FILES['ufile']['size'][1]."<BR/>";
echo "File Type :".$_FILES['ufile']['type'][1]."<BR/>";
echo "<img src=\"$path2\" width=\"150\" height=\"150\">";
echo "<P>";
echo "File Name :".$_FILES['ufile']['name'][2]."<BR/>";
echo "File Size :".$_FILES['ufile']['size'][2]."<BR/>";
echo "File Type :".$_FILES['ufile']['type'][2]."<BR/>";
echo "<img src=\"$path3\" width=\"150\" height=\"150\">";
///////////////////////////////////////////////////////
// Use this code to display the error or success.
$filesize1=$_FILES['ufile']['size'][0];
$filesize2=$_FILES['ufile']['size'][1];
$filesize3=$_FILES['ufile']['size'][2];
if($filesize1 && $filesize2 && $filesize3 != 0)
{
echo "We have recieved your files";
}
else {
echo "ERROR.....";
}
//////////////////////////////////////////////
// What files that have a problem? (if found)
if($filesize1==0) {
echo "There're something error in your first file";
echo "<BR />";
}
if($filesize2==0) {
echo "There're something error in your second file";
echo "<BR />";
}
if($filesize3==0) {
echo "There're something error in your third file";
echo "<BR />";
}
?>
Any help would be appreciated !
Thanks !
make sure that the destination directory exists, copy will not create directories for you.
The 2nd parameter is for file permissions and important for security, read more: https://wiki.archlinux.org/index.php/File_permissions_and_attributes
The 3rd parameter will also create recursive directories.
if (!is_dir($directory)) {
mkdir($directory, 0777, true);
}
Do not use copy, use move_uploaded_file(...)
Solved the problem !
The problem was with the Path.. instead of Task2/uploads/ I had to put ../Task2/uploads/.
Thanks!

Trouble uploaded multiple files and saving the paths to database

Ok Basically i am following this guide which is pretty straight forward but, I am at the point now where i am completely lost. I don't want to have to start all over again and I hope it's just a minor adjustment but anyhow heres the error:
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in /I don't want to publicize the path name/html/add.php on line 39
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpqd62Gk' to 'thumbnails/' in /I don't want to publicize the path name/add.php on line 39
Sorry, there was a problem uploading your cover. Please check it is the appropriate size and format.
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in /I don't want to publicize the path name/add.php on line 52
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpFVlGsv' to 'audio/' in /I don't want to publicize the path name/add.php on line 52
Sorry, there was a problem uploading your song. Please check it is the appropriate size and format.
And here is the "add.php" which is executed after submitting the form :
<?php
include "db_config.php";
//This is the directory where images will be saved
$targetp = "thumbnails/";
$targetp = $targetp . basename( $_FILES['cover']['artist']);
//This is our size condition
if ($uploaded_size > 100000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is the directory where songs will be saved
$targets = "audio/";
$targets = $targets . basename( $_FILES['song']['artist']);
//This is our size condition
if ($uploaded_size > 6000000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This gets all the other information from the form
$title=$_POST['title'];
$artist=$_POST['artist'];
$cover=($_FILES['cover']['artist']);
$song=($_FILES['song']['artist']);
$today = date("Ymd");
$ip = $_SERVER['REMOTE_ADDR'];
//Writes the information to the database
mysql_query("INSERT INTO `Thumbnails` VALUES ( '', '$artist - $title', '$cover', '', '$song', '$title', '$artist', '$today', '$ip')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['cover']['tmp_name'], $targetp))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['cover']['artist']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your cover. Please check it is the appropriate size and format.";
}
//Duplicate for song
if(move_uploaded_file($_FILES['song']['tmp_name'], $targets))
{
echo "The file ". basename( $_FILES['song']['artist']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your song. Please check it is the appropriate size and format.";
}
?>
Perhaps a step in the right direction would be greatly appreciated as it has gotten to the point where it all feels like scribble on a screen but, I'd hate to start all over again.
Try to
Change
basename( $_FILES['cover']['artist']);
To
basename( $_FILES['cover']['name']);
try
$targetp = "/thumbnails/;
$targets = "/audio/";
or specify full path name like c:/some/path/here

PHP can't upload files to server?

I have a php file that uploads images like jpegs and png onto a folder called uploads that is stored on the apache server and in the same location as the php file.
I have checked the code of both the HTML and the PHP and both seem to be perfectly fine, however whenever I try to upload a file I always get an error message and the file doesn't get uploaded.
It would be much appreciated if someone with more experience than me can look at my code and tell me why it is behaving in this manner.
Here is the HTML form:
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Your File</title>
</head>
<body>
<?php
// put your code here
?>
<form enctype="multipart/form-data" method="post" action="fileHandler.php">
Select File:
<input name="uploaded_file" type="file"/><br/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
and here is the PHP file that is executed when the form is submitted:
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* PHP file that uploads files and handles any errors that may occur
* when the file is being uploaded. Then places that file into the
* "uploads" directory. File cannot work is no "uploads" directory is created in the
* same directory as the function.
*/
$fileName = $_FILES["uploaded_file"]["name"];//the files name takes from the HTML form
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"];//file in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"];//the type of file
$fileSize = $_FILES["uploaded_file"]["size"];//file size in bytes
$fileErrorMsg = $FILES["uploaded_file"]["error"];//0 for false and 1 for true
$target_path = "uploads/" . basename( $_FILES["uploaded_file"]["name"]);
echo "file name: $fileName </br> temp file location: $fileTmpLoc<br/> file type: $fileType<br/> file size: $fileSize<br/> file upload target: $target_path<br/> file error msg: $fileErrorMsg<br/>";
//START PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------
if(!$fileTmpLoc)//no file was chosen ie file = null
{
echo "ERROR: Please select a file before clicking submit button.";
exit();
}
else
if(!$fileSize > 16777215)//if file is > 16MB (Max size of MEDIUMBLOB)
{
echo "ERROR: Your file was larger than 16 Megabytes";
unlink($fileTmpLoc);//remove the uploaded file from the PHP folder
exit();
}
else
if(!preg_match("/\.(gif|jpg|jpeg|png)$/i", $fileName))//this codition allows only the type of files listed to be uploaded
{
echo "ERROR: Your image was not .gif, .jpg, .jpeg or .png";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
exit();
}
else
if($fileErrorMsg == 1)//if file uploaded error key = 1 ie is true
{
echo "ERROR: An error occured while processing the file. Please try again.";
exit();
}
//END PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------------------------
//Place it into your "uploads" folder using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, $target_path);
//Check to make sure the result is true before continuing
if($moveResult != true)
{
echo "ERROR: File not uploaded. Please Try again.";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
}
else
{
//Display to the page so you see what is happening
echo "The file named <strong>$fileName</strong> uploaded successfully.<br/><br/>";
echo "It is <strong>$fileSize</strong> bytes.<br/><br/>";
echo "It is a <strong>$fileType</strong> type of file.<br/><br/>";
echo "The Error Message output for this upload is: $fileErrorMsg";
}
?>
make sure that the directory structure has write permissions. You can check within php by using is_writeable. By checking from within PHP you will also be making sure that the PHP user has write access.
Check the folder permissions on the server. If incorrect, you can modify your php.ini file.

Categories