I am using a CMS, and I can restrict access to pages of my website etc quite easily. But I also want to restrict access to folders. I know this can be done using .htaccess, but is it the best solution? And if I want to link something from one of these folders, does the code need the password? If so how would that work?
If you are unable to create the folder above the folder where your CMS exists, the .htaccess is a good method. You will need the password to access anyting in these folders, which the web broswer will prompt you for.
If what you're trying to do is keep sensitive scripts from prying eyes that you want to use within your site, then this isn't a good method, as you'll need that password in order to access the script. The best solution for this is what Psyche said: place the files in a folder that is outside of your web folder.
You include them into your page using the include_once() function. You have to also be sure you provide PHP with the path to your hidden folder. This can be done in the public folder's .htaccess file like this:
php_value include_path /home/mysite.com/inc
Then in your HTML page, you add at the top...
myscript.php would be located in the /home/mysite.com/inc/ folder on your server.
Oh, yes, that's a whole different kettle of fish, and a lot more involved. I recommend you check some of the user notes for the header() function in the php.net site, which has some posts on doing exactly what you want: