Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

How to upload to $username folder using php?

The script I have written is able to upload to static folders ("uploads" for example). But I need users to be able to upload to their own folder based on their username. I am able to create the folder based on $username, so no issues there.

The problem is, that when I use $target = "uploads"; everything works fine, but when I modify to:

$username = $_POST['username'];

$target = "$username";

The file is not uploaded. I have a startsession file in the header and am able to echo out the username, so I am really at a loss as to what is causing the problem. It is the last step for my new business website and would really appreciate any help. It is becoming a tad frustrating digging through the any and all forums and recycling code to try and figure this out.

Muhammad Ehsan Hanif
Muhammad Ehsan Hanif
8,236 Points

I don't know the whole code but i think you should try $target = echo $_POST['username'];

1 Answer

Adding the "echo" created a syntax error.

Here is the code (I know it is sparse and needs some security and MIME types added, but I just want to make sure I am getting this part correct before moving on):

<?php

$username = $_POST['username'];

$target = "$username/";

$target = $target . basename( $_FILES['uploaded']['name']) ;

$ok=1;

if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{ echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } ?>

And, this is what I get after uploading to $username (again, if it is a static-named folder there is no issue and everything works fine):

Warning: move_uploaded_file(/bluecheck.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /home/content/14/6467414/html/upub/upload.php on line 5

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/home/content/14/6467414/tmp/phpzxjsBY' to '/bluecheck.jpg' in /home/content/14/6467414/html/upub/upload.php on line 5 Sorry, there was a problem uploading your file.