Archive for January, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY This (Apache web server tutorial)

Friday, January 11th, 2008

PHP 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.

UPLOADING FILES Figure 6-5. Prefixing (Web design programs) a filename with

Thursday, January 10th, 2008

UPLOADING FILES Figure 6-5. Prefixing a filename with a timestamp prevents existing files from being overwritten. 4. If you find the timestamps difficult to understand, you can use the date() function instead to create a more readable date and time. (The date() function and its formatting options are described in detail in Chapter 14.) Change the else statement in the previous step like this: else { // get the date and time ini_set(’date.timezone’, ‘Europe/London’); $now = date(’Y-m-d-His’); $success = move_uploaded_file($_FILES[’image’][’tmp_name’], . UPLOAD_DIR.$now.$file); } As explained in Chapter 4, PHP 5.1.0 and above requires a valid time zone when using date(), so it s a good idea to future-proof your code by setting the time zone for your server (see www.php.net/manual/en/timezones.php for a list of valid time zones). The preceding code produces a filename like that on the right in Figure 6-6. Figure 6-6. Using the date() function makes the date and time easier to read. You can check your code against upload08.php in the download files. 171
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.

Submit web site - PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY PHP

Wednesday, January 9th, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY PHP Solution 6-5: Using a timestamp to create a unique name Continue working with the same file. Alternatively, use upload07.php from the download files. 1. You create a current timestamp by calling the time() function, which takes no arguments. If you want to apply a timestamp to all filenames, simply add it between the UPLOAD_DIR constant and the filename in the second argument passed to move_uploaded_file() like this: $success = move_uploaded_file($_FILES[’image’][’tmp_name’], . UPLOAD_DIR.time().$file); Notice that there are periods on either side of time(). This is the concatenation operator, so what you re doing is joining three values together as a single string in other words, the path and filename. 2. If you want to prefix only potential duplicates with a timestamp, you need to check whether a file of the same name already exists, and then use an if… else construct to take the appropriate action. Amend the first section of the switch statement like this: if ($sizeOK && $typeOK) { switch($_FILES[’image’][’error’]) { case 0: // make sure file of same name does not already exist if (!file_exists(UPLOAD_DIR.$file)) { // move the file to the upload folder and rename it $success = move_uploaded_file($_FILES[’image’][’tmp_name’], . UPLOAD_DIR.$file); } else { $success = move_uploaded_file($_FILES[’image’][’tmp_name’], . UPLOAD_DIR.time().$file); } if ($success) { $result = “$file uploaded successfully”; } 3. Save upload.php and test it by uploading the same image twice. As you can see in Figure 6-5, the message displayed in the form still uses the original name, but the duplicate in the upload folder has a timestamp in its filename.
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.

Web site counters - UPLOADING FILES Don t forget that when comparing values

Wednesday, January 9th, 2008

UPLOADING FILES Don t forget that when comparing values to see if they re the same, you must use two equal signs. If you use just one equal sign, the test will always equate to true (see Making comparisons in Chapter 3 if you need reminding why). 3. You can now use $typeOK to control whether the file is moved to the upload folder. Both $typeOK and $sizeOK must be true for the upload to continue. Immediately after the code you have just entered, amend the if statement like this: if ($sizeOK && $typeOK) { switch($_FILES[’image’][’error’]) { 4. There s just one final touch needed. Add details of the permitted types to the else statement at the bottom of the script, just before the DOCTYPE declaration. else { $result = “$file cannot be uploaded. Maximum size: $max. . Acceptable file types: gif, jpg, png.”; } } 6 You could use the values of $typeOK and $sizeOK to create different error mes sages depending on the reason for the failure, but it s probably more user-friendly to indicate all restrictions at the same time 5. Save upload.php, and test it with a variety of files to make sure that only files of the right type and size get through. Check your code against upload07.php if you encounter any problems. Preventing files from being overwritten If you have been testing upload.php regularly through this chapter, by now you probably have quite a few files in the upload folder. If you have only a handful, it s probably because you have been using the same files over and over again. As the script stands, PHP auto matically overwrites existing files without warning. That may be exactly what you want. On the other hand, it may be your worst nightmare. In Chapter 4, you used file_exists() to check the existence of a file. You may be think ing it would be a good idea to use it here and display a message asking the user if the file should be replaced. It s not the solution I m going to suggest. You can never be 100% sure who is accessing your site, so giving users the opportunity to delete files is something you should approach with the utmost caution. A very simple way of giving every file a unique name is to combine it with the date and time of upload. PHP bases date calculations on Unix timestamps, which measure the num ber of seconds since midnight GMT on January 1, 1970. So, by prefixing the existing file name with a Unix timestamp, the likelihood of two files ever having the same name is infinitesimal. Using a timestamp also has the advantage that files are listed in chronologi cal order of receipt. By the way, PHP uses Unix timestamps on all operating systems, including Windows. 169
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

PHP SOLUTIONS: DYNAMIC (Web hosting reseller) WEB DESIGN MADE EASY The

Tuesday, January 8th, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY The way you handle acceptable types is very similar to the preceding PHP Solution. First, you define what is acceptable and assume that the uploaded file is suspect until you have checked its credentials in other words, the value of $_FILES[’image’][’type’]. Since there are several MIME types for images, you store the acceptable ones in an array and loop through the array until you find one that matches the value in the $_FILES array. If there s a match, a Boolean variable is set to true. If not, the file is rejected. PHP Solution 6-4: Restricting upload file types Continue working with the same file. Alternatively, use upload06.php from the download files. The finished script for this PHP Solution is in upload07.php. 1. Start by adding an array of permitted MIME types and a Boolean variable that begins by assuming the type is unacceptable. Insert the code just after the line that converts MAX_FILE_SIZE to kilobytes (new code is shown in bold): // convert the maximum size to KB $max = number_format(MAX_FILE_SIZE/1024, 1).’KB’; // create an array of permitted MIME types $permitted = array(’image/gif’,'image/jpeg’,'image/pjpeg’,'image/png’); // begin by assuming the file is unacceptable $sizeOK = false; $typeOK = false; Although image/pjpeg isn t an official MIME type listed by the Internet Assigned Numbers Authority (IANA), you need to include it in the $permitted array. Otherwise, your form will reject all JPEG files submitted through Internet Explorer. 2. You need to loop through each element in the $permitted array to see if one of them matches $_FILES[’image’][’type’]. Add the code immediately after the conditional statement that checks the size of the file. // check that file is within the permitted size if ($_FILES[’image’][’size’] > 0 && $_FILES[’image’][’size’] <= . MAX_FILE_SIZE) { $sizeOK = true; } // check that file is of a permitted MIME type foreach ($permitted as $type) { if ($type == $_FILES['image']['type']) { $typeOK = true; break; } } This uses a foreach loop (see Looping through arrays with foreach in Chapter 3), which assigns each element of the $permitted array to a temporary variable, $type, and compares it to the uploaded file s MIME type. As soon as it finds a match, it sets $typeOK to true and breaks out of the loop; there s no need to test the others.
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

UPLOADING FILES 8. Change MAX_FILE_SIZE to something more

Monday, January 7th, 2008

UPLOADING FILES 8. Change MAX_FILE_SIZE to something more reasonable say, 51200 (50KB) like this: // define a constant for the maximum upload size define (’MAX_FILE_SIZE’, 51200); 9. Save output.php and test the file again, mak ing sure you choose an image that s smaller than MAX_FILE_SIZE. This time you should see a message like the one shown to the right. 10. Check inside the upload folder. Your image should be there. You can compare your code with upload06.php if you run into any prob lems. Change the value of MAX_FILE_SIZE to suit your particular needs. Accepting only certain types of files The upload script is now much more robust, but it still doesn t restrict the types of files that users can upload. The script refers to $_FILES[’image’], but it s only a name. As it stands, it could be used to upload any type of file, so it s important to check the MIME type and restrict uploads to permitted ones. You can find definitions of recognized MIME types at www.iana.org/assignments/media-types. Table 6-3 lists some of the most commonly used ones. An easy way to find others not on the list is to use upload02.php, and see what value is displayed for $_FILES[’image’][’type’]. Table 6-3. Commonly used MIME types Category MIME type Description Documents application/msword Microsoft Word document application/pdf PDF document text/plain Plain text text/rtf Rich text format Images image/gif GIF format image/jpeg JPEG format (includes .jpg files) image/pjpeg JPEG format (nonstandard MIME type used by Internet Explorer) image/png PNG format image/tiff TIFF format 167
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY The (Cool web site)

Monday, January 7th, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY The basic structure here is an if… else statement, which determines whether the size of the uploaded file is acceptable. If it is, the switch statement examines the value of $_FILES[’image’][’error’]. Error level 0 indicates the file was uploaded successfully, so it s OK to move it to the upload folder. As long as the folder has the correct permissions, and there s sufficient disk space, this operation should succeed. However, move_uploaded_file() returns a Boolean value, so you can verify the outcome of the operation by capturing the result in $success. If $success is true, you can report the successful upload. Otherwise, inform the user of a problem. Error levels 1 and 2 both indicate that the file exceeds the maximum size. You don t need to check for either of these, because the code in step 4 already takes care of files that are too big. Error level 3 indicates that the upload was incomplete, so a suitable message is stored in $result. Using default at the end of the switch statement covers any remaining possibilities. Since the $_FILES array reports a size of 0 when no file is selected, $sizeOK remains false, so the switch statement never encounters error level 4, which is handled separately in the elseif clause. That leaves error levels 6 (no temporary folder) and 7 (cannot write file). These are system errors that the user cannot overcome by trying again, so a suitable catchall message is used. Finally, if the file is too big, a message is prepared, saying that the file can t be uploaded and reporting the maximum permitted size. 6. The common feature of every branch of this decision chain is that a message reporting the outcome of the upload is stored in $result. All that s needed now is to display the contents of $result after the form is submitted. Insert the following code between the opening and

tags: $result

“; } ?>
Since $result is set only after the form has been submitted, this new code block is ignored when the form first loads, but displays the outcome of any upload operation. 7. Let s test the page. Save upload.php and select an image that s bigger than 2.9KB. Click Upload. You should see an error message like the following:
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

UPLOADING FILES After converting MAX_FILE_SIZE, the script assumes (Crystaltech web hosting)

Sunday, January 6th, 2008

UPLOADING FILES After converting MAX_FILE_SIZE, the script assumes that the file is too big by setting a variable $sizeOK to false. The guilty until proven innocent approach may seem harsh, but it s wise on the Web. Finally, an if statement checks whether $_FILES[’image’][’size’] is greater than 0 and less than or equal to MAX_FILE_SIZE. You need to check both conditions, because $_FILES[’image’][’size’] is set to 0 if PHP detects that the file is larger than the maximum permitted by the hidden field or the server configuration. If the size is within the acceptable range, $sizeOK is set to true. 5. You can now use $sizeOK to control whether the file is moved to the upload folder. PHP Solutions 6-1 and 6-2 assume that the upload is successful, but that may not always be the case. It s a good idea to check the error level (see Table 6-2) reported by the $_FILES array, so you can inform users what happens to their upload. This means that you need to create a series of nested decisions. One way is to nest lots of if… else statements inside each other. The code is more readable, though, if you use a switch statement (see Using the switch statement for decision chains in Chapter 3) in combination with if… else. Amend the remaining part of the PHP code above the DOCTYPE declaration like this (new code is in bold): // check that file is within the permitted size if ($_FILES[’image’][’size’] > 0 && $_FILES[’image’][’size’] <= . MAX_FILE_SIZE) { $sizeOK = true; } if ($sizeOK) { switch($_FILES['image']['error']) { case 0: // move the file to the upload folder and rename it $success = move_uploaded_file($_FILES['image']['tmp_name'], . UPLOAD_DIR.$file); if ($success) { $result = "$file uploaded successfully"; } else { $result = "Error uploading $file. Please try again."; } break; case 3: $result = "Error uploading $file. Please try again."; default: $result = "System error uploading $file. Contact webmaster."; } } elseif ($_FILES['image']['error'] == 4) { $result = 'No file selected'; } else { $result = "$file cannot be uploaded. Maximum size: $max."; } } ?> 165
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY 2. (Web hosting directory)

Saturday, January 5th, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY 2. Scroll up to the top of upload.php, and define the value of MAX_FILE_SIZE immediately after the opening PHP tag like this: 0 && $_FILES[’image’][’size’] <= . MAX_FILE_SIZE) { $sizeOK = true; } // move the file to the upload folder and rename it The first line of new code is typical of the concise way PHP is often written: $max = number_format(MAX_FILE_SIZE/1024, 1).'KB'; It converts MAX_FILE_SIZE from bytes to kilobytes and formats it all in one pass. The number_format() function normally takes two arguments: a number that you want nicely formatted with commas as the thousands-separator and the number of decimal places to be displayed. To get the number of kilobytes, you need to divide MAX_FILE_SIZE by 1,024; and PHP takes that calculation as the first argument. It s also perfectly happy for you to tag KB on the end with the concatenation operator (a period). If you find this difficult to follow, the following three lines do exactly the same: $kilobytes = MAX_FILE_SIZE/1024; $formatted = number_format($kilobytes, 1); $max = $formatted.'KB';
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

UPLOADING FILES 3. Save upload.php, and test it

Saturday, January 5th, 2008

UPLOADING FILES 3. Save upload.php, and test it with a file that contains spaces in its name, as well as with one with no spaces. As Figure 6-4 shows, the script works with both types, but spaces are replaced by underscores. You can check your code with upload05.php. Figure 6-4. Spaces should be removed from filenames before storage on a web server. Rejecting large files The ability to upload files is not enough on its own: you need to make your form more secure. The first step is to set a maximum size for file uploads. Even if your hosting com pany sets a lower limit than the 2MB default, you may want to set a much lower limit your self. At the same time, it s a good idea to make your form more user-friendly by reporting whether the upload was successful. You can do this easily by checking the error level reported by the $_FILES array (see Table 6-2). PHP Solution 6-3: Setting a size limit and displaying outcome Continue working with the previous file. Alternatively, use upload05.php from the download files. The final code for this PHP Solution is in upload06.php. 1. In addition to the automatic limits set in the PHP configuration (see Table 6-1), you can also specify a maximum size for an upload file in your XHTML form. Add the following line highlighted in bold immediately before the file input field: This is a hidden form field, so it won t be displayed onscreen. However, it is vital that you place it before the file input field; otherwise, it won t work. The value attribute sets the maximum size of the upload file in bytes. Instead of specifying a numeric value, I have used a constant, which needs to be defined next. 163
In case you need quality webspace to host and run your web applications, try our personal web hosting services.