Why is my PHP file upload code not working? - php

I am trying to make a simple file upload form using PHP. Here's my code:
<?php
$uploads_dir = '/uploads';
if(isset($_FILES['thefile'])){
$errors= array();
$file_name = $_FILES['thefile']['name'];
$file_size =$_FILES['thefile']['size'];
$file_tmp =$_FILES['thefile']['tmp_name'];
$file_type=$_FILES['thefile']['type'];
$tmp_name = $_FILES['thefile']["tmp_name"];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($tmp_name, "$uploads_dir/$file_name");
echo "Success";
}
else{
print_r($errors);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="thefile" />
<input type="submit"/>
</form>
</body>
</html>
I realize that I'm not limiting file types, but I'll worry about that once I can get a simple .jpg or .zip file uploaded. Using the above code, I go to the page on my local server located at
C:\wamp\www\simpleupload (this contains index.php, the file posted above)
When I select a small image file and click submit, I'm presented with the following errors:
Warning: move_uploaded_file(/uploads/session_timeout_formatting_bug.png): failed to open stream: No such file or directory in C:\wamp\www\project_fileshare\index.php on line 18
and
Warning: move_uploaded_file(): Unable to move 'C:\wamp\tmp\phpEFDE.tmp' to '/uploads/session_timeout_formatting_bug.png' in C:\wamp\www\project_fileshare\index.php on line 18
Line 18 is the line that calls the move_uploaded_file() function.
How do I fix this error? I have an 'uploads_dir' folder located in the same folder as my index.php file. (reference the file path above). What am I doing wrong here? I must be misunderstanding some small part of this process and have put my directory in the wrong place, or I'm doing something wrong in the code.
Can someone spot my mistake and tell me what I need to do to fix it?

You are working on windows and you've told PHP a location that is inaccessible (i.e. /uploads linux path).
Since you are working in windows and your document root is C:\wamp\www\simpleupload
Which means, your files are located like this:
C:\wamp\www\simpleupload\index.php (your upload script)
C:\wamp\www\simpleupload\uploads (where the files should be uploaded)
Why don't you use absolute path like this:
$uploads_dir = getcwd() . DIRECTORY_SEPARATOR . 'uploads';
The getcwd() function will return the current working directory for the executing PHP script (in your case index.php), so the $uploads_dir will now look like this: C:\wamp\www\simpleupload\uploads
Try this.

If your upload directory is in the same location as your index.php remove the "/" in your $uploads_dir variable. This, or add a "." before the slash because now it refers to the root which might be something else then your current working directory. Speaking of the devil; http://php.net/manual/en/function.getcwd.php
$uploads_dir = getcwd() . '\uploads';
$uploads_dir = __DIR__ . '\uploads'; #php > 5.6
Also, check if your directory is writeable for php:
http://php.net/manual/en/function.is-writable.php
Also what Latheesan said, better to go cross platform as I made the same mistake seen in my edit.
<?php
function buildPath(...$segments){
return join(DIRECTORY_SEPARATOR, $segments);
}
echo buildPath(__DIR__, 'uploads');
?>

And i would change
if(isset($_FILES['thefile'])){
for this
if($_FILE['thefile']['error'] === UPLOAD_ERR_OK){
Because I think that this is the best way to know if the user upload a file or the input is blank.
Or
if (isset($_FILE["thefile"]["name"])){

Related

Issue with uploading file from local file system to php server

I am trying on upload file from local file system to a remote server using php.
I am using move_uploaded_file function but when i select a file on my local file system, it tries to find the file on remote server and hence fails. maybe i am missing something. Let's say if i am trying to upload a file from C:\Data\abc.txt. It tries to find the file on /server/abc.txt and hence fails to upload the file. Please let me know if i am missing something.
<?
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$original = $root_path .$file_name;
echo $_FILES['image']['tmp_name'];
if($file_size > 100097152){
$errors[]='File size must be less than 100 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp, '/uploads');
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
I dont know if I have understood you correctly, but you means with remote server your webserver?
This server doesnt access your file system directly because of your browser's sandbox mode. It gets only the submitted file, the origin path doesnt matter.
The second parameter of the function move_uploaded_file has to be the target file, not the target dictionary.
Example:
move_uploaded_file($file_tmp, '/uploads/' . $file_name);
diffcult to answer pls tell me the php version and as a hint: have you checked is_uploaded_file() php.net/manual/function.is-uploaded-file.php
could help to use the error/status-reporting in $_FILES['image']['error'] - gives feedback on error/status code of your file upload, so you can better understand what the source of the problem possibly is:
0 = success
1 = file too big (php.ini set)
2 = file too big (max file size directive)
4 = no file was uploaded
6 = no access to temp folder on server
7 = file could not be written to server
8 = upload stopped by a php extension
hope that helps

How to Get Uploaded File Name with glob() Function?

I have a form for users to upload files into the folder.
HTML and PHP codes are as below:
<form enctype="multipart/form-data" method="post" action="test.php">
<input type="text" name="name"/><br/>
<input type="file" name="photo" /><br/>
<input type="submit"/>
</form>
<?php //test.php
move_uploaded_file($_FILES["photo"]["tmp_name"], "testFolder/".$_POST["name"]);
?>
The upload form works well, and uploaded files are in the folder testFolder/ .
Now I want to use glob() function to get all file names in the folder.
<?php
foreach(glob("testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
However, it doesn't echo anything.
The glob() function works well on other folders, which contains existing files, not uploaded files.
But why doesn't it work on this folder with uploaded files ?
Possbile wildcard extension could be the issue.
It may be that glob does not allow wildcard extensions, i dont see any mention of this in the docs. Have you tried a directory iterator?
$dir = new DirectoryIterator(__DIR__.'/testFolder);
foreach ($dir as $file) {
echo $file->getFilename();
}
UPDATE: THE PATH IS NOT THE ISSUE
You are using a relative file path, therefore glob probably isn't finding the directory you are trying to search for.
Either the script calling the function needs to sit inside the parent directory of 'testFolder' or you need to use an absolute path like so.
<?php
foreach(glob("/absolute/path/to/testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
If you do want to use a relative path you could do the following:
<?php
//__DIR__ is a PHP super constant that will get the absolute directory path of the script being ran
// .. = relative, go up a folder level
foreach(glob(__DIR__."/../testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
Obviously the paths above are examples but should get you on the right track.
Hope this helps
Because I didn't give the extension for the uploaded file, that's why glob("testFolder/*.*") doesn't get anything.
Two solutions:
Give uploaded files an extension.
$ext = strrchr($_FILES["photo"]["name"], ".");
move_uploaded_file($_FILES["photo"]["tmp_name"],
"testFolder/".$_POST["name"].$ext);
Then, glob("testFolder/*.*") will be able to get these uploaded files with an extension.
Just change glob("testFolder/*.*") to be glob("testFolder/*")

Getting file name and file directory in PHP application by selecting file

I'm currently making a PHP application, where I want to insert data from a excel sheet in a MySQL database. I've done that so far, but the problem now is, that the excel file needs to be in the root directory. What I'm looking for is a button where I can browse the file, and from which i get the name and the directory. Any suggestions?
currently I just use $fileName="gefertigt.xlsx";
I tried it with JavaScript (from this tutorial), but since I'm a beginner it's to difficult for me.
The PHP filesystem has two functions, basename() and dirname(), which give the filename and directory, respectively. Thus your answer is:
function get_name_and_directory($file) {
return array(
'name' => basename($file),
'directory' => dirname($file)
);
}
So I found a good solution for my problem, which is quiet easier than I thought. Instead of getting the directory of the file, I uploaded the file to a folder called "uploads" in my root directory. Since i knew that the file(which will always be an .xlsx file) will always be the same, but always with new content, it replaces the current file in the folder uploads with the upladed file.
code in html:
<form action="dbconnection.php" method="post" enctype="multipart/form-data">
Datei auswaehlen
<input type="file" name="dateiHochladen" id="dateiHochladen">
<input type="submit" value="Hochladen" name="submit">
</form>
code in php:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["dateiHochladen"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["dateiHochladen"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["dateiHochladen"]["name"]). " wurde hochgeladen.";
} else {
echo "Fehler beim hochladen.";
}

move_uploaded_file() permission denied, unable to move PHP [duplicate]

This question already has answers here:
PHP - Failed to open stream : No such file or directory
(10 answers)
Closed 6 years ago.
I am creating a profile picture upload function for my site, but for some reason, move_uploaded_file() does not want to function.
I have tried multiple forums and tested out all the possible different approaches, but with no luck.
Here is my PHP & HTML:
<?php
if(isset($_FILES['avatar'])){
if(empty($_FILES['avatar']['name'])){
$errors[] = 'Please select an avatar.';
} else {
$ext = array('jpg', 'jpeg', 'png');
$file = $_FILES['avatar']['name'];
$fileext = strtolower(end(explode('.', $file)));
$filetmp = $_FILES['avatar']['tmp_name'];
if(in_array($fileext, $ext)){
$file = md5(microtime() . $filetmp) . '.' . $fileext;
$filepth = './data/user_data/img/udid/prof/' . $file;
move_uploaded_file($filetmp, $filepth);
} else {
$errors[] = 'Please select a valid file type. (JPG, JPEG or PNG)';
}
}
}
?>
<form action="" method="post" class="avatar-form-form" enctype="multipart/form-data">
<input type="file" name="avatar"><br>
<input type="submit" value="Upload">
</form>
So first off, I am checking that the selected file has a valid extension, if so, it will hash the file temporary name with the microtime (for security). I am then concatenating the extension onto the end with a full stop between it, i.e the output will be md5hash.png.
I am then creating a file path variable by concatenating the file variable onto the end of my directory.
I then proceed with the file upload function by passing through the $filetmp and $filepth variables (like you're supposed to do).
However, when I go to test this function out on my page, I get these errors:
Warning: move_uploaded_file(./data/user_data/img/udid/prof/e4d0cde3c9330222ef3ab651fe797bed.jpg):
failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/test/settings.php
on line 40
Warning: move_uploaded_file(): Unable to move '/Applications/XAMPP/xamppfiles/temp/phpkWSGLy'
to './data/user_data/img/udid/prof/e4d0cde3c9330222ef3ab651fe797bed.jpg'
in /Applications/XAMPP/xamppfiles/htdocs/test/settings.php
on line 40
This is my current layout:
The settings page (the one where the user uploads there picture) is in the root directory.
The location in which I want to put the avatar is inside of a folder (also in the root directory.
I am currently testing all of this on my MacBook running XAMPP and have made sure that file_uploads is set to "on" in my php.ini file.
All help is appreciated. Not sure If I have done this incorrectly, but I am almost certain that I haven't.
EDIT:
So, It turns out, that by default on a MacBook (when running XAMPP), all files inside of XAMPP/htdocs are set to read only and you must manually set them to "read & write" to allow move_uploaded_file to work.
Check that you have set the proper write permissions for your uploaded images folder in your MacBook.

PHP Upload File - right code but can't find the file/path

First question for quite a while. Essentially, I've got some code that (1) works perfectly in the live environment, (2) used to work in my home OSX environment but (3) doesn't work now.
The HTML:
<form id="upload_form" action="php/upload_class_list.php" method="post" accept-charset="UTF-8" enctype="multipart/form-data" target="upload_target" >
<label>File:</label>
<input name="myfile" type="file" size="35" />
<input id="upload_submit" type="submit" value="Upload" />
<iframe id="upload_target" name="upload_target" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
The PHP file:
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
...
}
sleep(1);
?>
<script language="javascript" type="text/javascript">top.upload_class_list(<?php echo $result; ?>);</script>
The script fires at the end, but the PHP code doesn't enter the if (in the local development environment) and so $result remains at 0.
It seems it's not picking up the path of the file to be uploaded; $destination_path points to the folder where the PHP file is located, and not where the file is found.
I think my local environment may have stopped working when I changed to Mountain Lion and rebuilt the PHP setup.
What is missing to stop the file being found?
Let me emphasise: exactly the same code works fine in my live Hostmonster setup, so it's an environment problem, I guess :)
Thanks.
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
...
}
What is missing to stop the file being found?
What makes you think the problem is the file being found? Maybe the file is found, but what fails is the move... for example because the Web server has no permissions to write into the target_path.
You can check:
$src = $_FILES['myfile']['tmp_name'];
$dst = $target_path;
if (!file_exists($src))
die("Okay, the file is actually not found");
if (!is_readable($src))
die("Very bad hosting juju. The file was uploaded but I can't read it?!?");
if (!is_writeable($destination_path))
die("As expected, you can't upload a file here. This is a good thing.");
#touch($dst);
if (!file_exists($dst))
die("So call me a Marine, the file SHOULD be writeable (which is not so good), and yet I could not write it! Perhaps disk full? User overquota? Some weird security setup?");
The reason why it's a good thing is because that directory holds executable PHP files, and if anyone could upload a PHP file in there, well, that would be a major security hole.
You can set aside another directory and make it writeable (remember to put in there a .htaccess or other system to prohibit read/execute access from the outside).
may be this
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>

Categories