Solved

Move_Uploaded_File problems with upload paths

Posted on 2009-05-08
5
589 Views
Last Modified: 2013-12-12
I am having trouble uploading files to my website using HTTP uploads with PHP.  The code is below for the upload and here are the error messages that I get:

Warning: move_uploaded_file(/home/myusername/www.mydomain.com/includes/guidelines/) [function.move-uploaded-file]: failed to open stream: Is a directory in /home/.devlin/myusername/www.mydomain.com/includes/adminoptions.php on line 20

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpHEk2JO' to '/home/myusername/www.mydomain.com/includes/guidelines/' in /home/.devlin/myusername/www.mydomain.com/includes/adminoptions.php on line 20

Line 20 is the line with move_uploaded_file in the code snippet below.

The directory being uploaded to DOES exist on the server.  I didn't have any issues with this upload when I was doing it on another form that runs in a higher directory (instead of the php file being in /includes/ it was just in the root directory).  I'm pretty sure that the issue is something to do with absolute versus relative paths but I can't figure out how to fix it?

I even tried changing the working directory and using ../ in the references etc but nothing I can figure out works.

Thanks for any help!
Nathan
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT']."/includes/guidelines/".$_POST['userfile'])) 
	{	
		echo "after successful file move <br>";
		$message .= '<br><center><strong>New guidelines file uploaded successfully!</strong></center><br>';
		
	}

Open in new window

0
Comment
Question by:ironwill96
  • 2
  • 2
5 Comments
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 500 total points
ID: 24339414
You must provide a filename for the target, not just a directory name. Try this:
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT']."/includes/guidelines/".$_POST['userfile']['name'])) 
        {       
                echo "after successful file move <br>";
                $message .= '<br><center><strong>New guidelines file uploaded successfully!</strong></center><br>';
                
        }

Open in new window

0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24339423
Eh... sorry, it should be $_FILES['userfile']['name'], not $_POST['userfile']['name'].
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24339602
This is my standard demonstration script that shows how to upload and store files on the server.

I think in the code snippet of the OP the reference to $_POST['userfile'] might be causing some confusion.  Since we cannot see the form, I can't be sure.

Anyway, have a look at this and post back here with any questions.  Best to all, ~Ray
<?php // RAY_upload_example.php
error_reporting(E_ALL);
 
// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php
// http://docs.php.net/manual/en/function.getimagesize.php
 
// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'uploads';
 
// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT
$max_file_size = '8192000';  // EIGHT MEGABYTE LIMIT ON UPLOADS
 
// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array('jpg', 'gif', 'png', 'txt');
 
// ESTABLISH THE NUMBER OF FILES WE CAN UPLOAD
$nf = 3;
 
 
 
// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$errors	= array(
	0=>"Success!",
	1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
	2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
	3=>"The uploaded file was only partially uploaded",
	4=>"No file was uploaded",
	6=>"Missing a temporary folder",
	7=>"Cannot write file to disk"
);
 
 
 
// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
	?>
	<h2>Upload a file</h2>
 
	<!--
		SOME THINGS TO NOTE ABOUT THIS FORM...
		NOTE THE CHOICE OF ENCTYPE IN THE HTML FORM STATEMENT
		MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
		INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
	-->
 
	<form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
	<input type="hidden" name="p" value="1" />
	<input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
	<p>
	Find the file(s) you want to upload and click the "Upload" button below.
	</p>
 
	<?php for ($n = 0; $n < $nf; $n++)
		{
			echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
		}
	?>
	<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
	<input type="submit" name="_submit" value="Upload" />
	</form>
	<?php
	die();
}
 
 
 
else // WE HAVE GOT SOMETHING IN $_POST
{
 
// THERE IS POST DATA - PROCESS IT
	echo "<h2>Results: File Upload</h2>\n";
 
// ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
//	echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";
 
// ITERATE OVER THE CONTENTS OF $_FILES
	foreach ($_FILES as $my_uploaded_file)
	{
 
// SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
		$error_code	= $my_uploaded_file["error"];
		if ($error_code == 4) continue;
 
// SYNTHESIZE THE NEW FILE NAME
		$f_type	= trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
		$f_name	= trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
		$my_new_file	= getcwd() . '/' . $uploads . '/' . $f_name .'.'. $f_type;
		$my_file	= $uploads . '/' . $f_name .'.'. $f_type;
 
// OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
		if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");
 
// IF THERE ARE ERRORS
		if ($error_code != 0)
		{
			$error_message = $errors[$error_code];
			die("Sorry, Upload Error Code: $error_code: $error_message");
		}
 
// GET THE FILE SIZE
		$file_size	= number_format($my_uploaded_file["size"]);
 
// MOVE THE FILE INTO THE DIRECTORY
// IF THE FILE IS NEW
		if (!file_exists($my_new_file))
		{
			if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
			{
				$upload_success = 1;
			}
			else
			{
				$upload_success = -1;
			}
 
// IF THE FILE ALREADY EXISTS
		}
		else
		{
			echo "<br/><b><i>$my_file</i></b> already exists.\n";
 
// SHOULD WE OVERWRITE THE FILE? IF NOT
			if (empty($_POST["overwrite"]))
			{
				$upload_success = 0;
 
// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
			}
			else
			{
				$now	= date('Y-m-d');
				$my_bak = $my_new_file . '.' . $now . '.bak';
				if (!copy($my_new_file, $my_bak))
				{
					echo "<br/><b>Attempted Backup Failed!</b>\n";
				}
				if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
				{
					$upload_success = 2;
				}
				else
				{
					$upload_success = -1;
				}
			}
		}
 
// REPORT OUR SUCCESS OR FAILURE
		if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
		if ($upload_success == 1) { echo "<br/><b><i>$my_file</i></b> has been saved.\n"; }
		if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>\n"; }
		if ($upload_success < 0)  { echo "<br/><b>ERROR <i>$my_file</i> NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</b>\n"; }
		if ($upload_success > 0)
		{
			echo "$file_size bytes uploaded.\n";
			if (!chmod ($my_new_file, 0755))
			{
				echo "<br/>chmod(0755) FAILED: fileperms() = ";
				echo substr(sprintf('%o', fileperms($my_new_file)), -4);
			}
			echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
		}
// END ITERATOR
	}
}
?>

Open in new window

0
 
LVL 2

Author Comment

by:ironwill96
ID: 24339657
Thanks CXR, that was my problem I goofed on the file name part!  Duh!

Nathan
0
 
LVL 2

Author Closing Comment

by:ironwill96
ID: 31579601
Thanks a ton for this!
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question