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.