PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY This (Apache web server tutorial)
Friday, January 11th, 2008PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY This is just a simple example of how you can prevent files from being overwritten, which also demonstrates the principle of giving upload files names of your choice, rather than accepting whatever is input by the user. Choosing your own filename also adds an extra level of security, as long as you don t reveal the new name in a message displayed onscreen. PHP Solution 7-4 in the next chapter shows you how to rename files in a consecutive series by appending the next available number to its filename. Organizing uploads into specific folders You can take the categorization of upload files a step further by creating a new upload folder (directory) for each user. This assumes that you require users to log in using a user authentication process (see Chapters 9 and 15) and store the username in a session variable. There s no need to set up the folders in advance; PHP can handle it for you automatically, as long as the new folders are created inside the upload folder. Moving uploaded files to specific folders involves just three steps, as follows: 1. Getting the name of the specific folder 2. Creating the folder if it doesn t already exist 3. Adding the folder name to the upload path PHP Solution 6-6: Creating user-specific upload folders Continue working with the same file. Alternatively, use upload08.php from the download files. The completed script is in upload09.php. 1. In a real application, you would store the user s username in a session variable when logging in, and the upload form would be in a restricted area protected by a PHP session (see PHP Solution 9-4 in Chapter 9). However, for the purposes of this demonstration, the username is hard-coded into the script. Insert the following code at the beginning of the switch statement: switch($_FILES[’image’][’error’]) { case 0: // $username would normally come from a session variable $username = ‘davidp’; // if the subfolder doesn’t exist yet, create it if (!is_dir(UPLOAD_DIR.$username)) { mkdir(UPLOAD_DIR.$username); } This stores the username as $username and then uses it with the is_dir() function to see whether a subfolder of that name exists in the upload folder. If it doesn t exist, the new folder is created by the mkdir() function. 2. All you need to do now is to add $username to the pathname to the next part of the script, which moves the upload file to its new location. Change the code like this:
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.