PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY Figure 6-2. The $_FILES array contains five important pieces of information about an uploaded file. You can see that the $_FILES array is actually a multidimensional array. The key (or name) of the top-level array comes from the name attribute of the file input field in this case, image. The image subarray consists of five elements, namely name: The original name of the uploaded file type: The uploaded file s MIME type tmp_name: The location of the uploaded file error: An integer indicating any problems with the upload (see Table 6-2) size: The size of the uploaded file in bytes 5. On Windows, open Explorer, and navigate to C:WINDOWSTEMP or the location indicated in tmp_name. On a Mac, open Terminal (it s in Applications:Utilities), and type the following commands, both followed by pressing Return: cd /var/tmp ls -l Don t waste time searching for the temporary file: it won t be there. It really is temporary. If you don t do anything with it immediately after uploading, PHP discards it. It s a highly efficient way of doing things, because it means your server doesn t get clogged up with files that are no longer needed. I ll explain shortly how to handle a file upload, but first let s continue our exploration of the $_FILES array. 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 Understanding the $_FILES array What confuses many people is that their file seems to vanish after it has been uploaded. This is because you can t refer to an uploaded file in the $_POST array in the same way as with text input. PHP transmits the details of uploaded files in a separate superglobal array called, not unreasonably, $_FILES. Moreover, files are uploaded to a temporary folder and are deleted unless you explicitly move them to the desired location. Although this sounds like a nuisance, it s done for a very good reason: you can subject the file to security checks before accepting the upload. The best way to understand how the $_FILES array works is to see it in action. If you have installed a local test environment, you can test everything on your computer. It works in exactly the same way as uploading a file to a remote server. Inspecting the $_FILES array 1. Create a new folder called uploads in the phpsolutions site root. Create a new PHP file called upload.php in the uploads folder, and insert the code from the previous section. Alternatively, copy upload01.php from the download files for this chapter, and rename the file upload.php. 2. Insert the following code right after the closing
tag (it s also in upload02.php):
This uses the array_key_exists() function that you met in the previous chapter. It checks whether the $_POST array contains upload, the name attribute of the submit button. If it does, you know the form has been submitted, so you can use print_r() to inspect the $_FILES array. The
tags make the output easier to read. 3. Save upload.php and load it into a browser. It should look like Figure 6-1. 4. Click the Browse (or Choose File) button, and select a file on your hard disk. Click Open (or Choose on a Mac) to close the file selection dialog box, and then click Upload. On Windows, you should see something similar to Figure 6-2 on the next page. A Mac should display the same information, although the value of tmp_name will probably be something like /var/tmp/phpAVSylw. 155 If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.
PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY The default limits set by PHP are quite generous, but you need to make sure that you don t exceed any limits set by your hosting company; if you do, scripts that are otherwise perfect will fail. It s important to note the limit imposed by post_max_size. Even though the default values theoretically permit the simultaneous upload of four 2MB files, the upload is likely to fail because the content of the $_POST array would bring the total to more than 8MB. If the Local Value of file_uploads is Off, uploads have been disabled. There is nothing you can do about it, other than ask your hosting company if it offers a package with file uploading enabled. Your only alternatives are to move to a different host or to use a different solution, such as uploading files by FTP. After using phpinfo() to check your remote server s settings, it s a good idea to remove the script or put it in a password-protected directory. Adding a file upload field to a form Adding a file upload field to an XHTML form is easy. Just add enctype=”multipart/ form-data” to the opening
In most browsers, this code inserts a text input field with a Browse button alongside, as shown in Figure 6-1. However, as the figure shows, not only does Safari label the button differently, but also it doesn t permit direct input of the filename; users are obliged to click Choose File to navigate to the local file. This doesn t affect the operation of an upload form, but you need to take it into consideration when designing the layout. Figure 6-1. Browsers automatically add a button to enable users to select a file ready for uploading. 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 Checking whether your server supports uploads All the information that you need is displayed in the main PHP configuration page that you can display by creating a PHP page with the following script and uploading it by FTP to your remote server: Load the page into a browser, and locate the section shown in the screen- shot to the right. Scroll down until you find file_uploads. If the Local Value column contains On, you re ready to go, but you should also check the other configu ration settings listed in Table 6-1. Table 6-1. PHP configuration settings that affect file uploads Directive Default value Description max_execution_time 30 The maximum number of seconds that a PHP script can run. If the script takes longer, PHP generates a fatal error. max_input_time 60 The maximum number of seconds that a PHP script is allowed to parse the $_POST and $_GET arrays, and file uploads. Very large uploads are likely to run out of time. post_max_size 8M The maximum permitted size of all $_POST data, including file uploads. Although the default is 8MB, hosting companies may impose a smaller limit. upload_tmp_dir This is where PHP stores uploaded files until your script moves them to a permanent location. If no value is defined in php.ini, PHP uses the system default temporary directory. upload_max_filesize 2M The maximum permitted size of a single upload file. Although the default is 2MB, hosting companies may impose a smaller limit. A number on its own indicates the number of bytes permitted. A number followed by K indicates the number of kilobytes permitted. 153 If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.
PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY What this chapter covers: Understanding how PHP handles file uploads Restricting the size and type of uploads Preventing files from being overwritten Organizing uploads into specific folders Handling multiple uploads PHP s ability to handle forms isn t restricted to text. It can also be used to upload files to a server. In theory, this opens up great possibilities. For instance, you could build a real estate website where clients could upload pictures of their properties, or a site for all your friends and relatives to upload their holiday photos. However, just because you can do it, doesn t necessarily mean that you should. Allowing others to upload material to your web- site could expose you to all sorts of problems. You need to make sure that images are the right size, that they re of suitable quality, and that they don t contain any illegal material. You also need to ensure that uploads don t contain malicious scripts. In other words, you need to protect your website just as carefully as your own computer. Fortunately, the way that PHP handles file uploads makes it relatively simple to restrict the type and size of files accepted. What it cannot do is check the suitability of the content. It s therefore always a good idea to implement a strategy that prevents indecent or illegal material from being automatically displayed on your site. One way is to store uploaded material in a nonpublic directory until it has been approved. Another way is to restrict uploads to registered and trusted users by placing the upload form in a password- protected area. A combination of both approaches is even more secure. User registration and authentication are covered in Chapters 9 and 15. Until you know how to restrict access to pages with PHP, I recommend that you use the PHP Solutions described in this chapter only in a password-protected directory if deployed on a public website. Most hosting companies provide simple password protection through the site s control panel. Before you dive into the scripts, you ll next look at how PHP handles file uploads, which should make the scripts easier to understand when you come to them. How PHP handles file uploads The term upload means moving a file from one computer to another, but as far as PHP is concerned, all that s happening is that a file is being moved from one location to another. This means you can test all the scripts in this chapter on your local computer without the need to upload files to a remote server. PHP supports file uploads by default, but hosting companies can restrict the size of uploads or disable them altogether. Before going any further, it s a good idea to check the settings on your remote server. Check Tomcat Web Hosting services for best quality webspace to host your web application.
6 UPLOADING FILES From our experience, we can recommend PHP5 Web Hosting services, if you need affordable webhost to host and run your web application.
BRINGING FORMS TO LIFE other whitespace ahead of the opening PHP tag. Also check any include files for white- space and new lines before the opening PHP tag and after the closing one. The error is frequently triggered by a single new line after the closing tag of an include file. Summary What began as a slender 50 lines of XHTML and PHP at the beginning of the chapter has grown by nearly 300 lines, of which about 100 process the form content ready for sending by email. This may seem like a lot if you have a phobia about code, but the most important sections of code (in PHP Solutions 5-5 and 5-6) filter out suspect input and should never need changing. Once you have built the script above the DOCTYPE declaration, you can copy and paste it into any form or use an include file. The only parts that need tweaking are the $expected and $required arrays and the section that builds the body of the email message. In order to concentrate on the mechanics of working with forms, I have kept the body of the message plain and simple. However, once you have extracted the form contents into variables, such as $name, $email, and so on, you can incorporate them into an email message any way you like. I ve also avoided talking about HTML email because the mail() function handles only plain text email. The PHP online manual at www.php.net/manual/en/function.mail.php shows a way of sending HTML mail by adding an additional header. However, it s not a good idea, as HTML mail should always contain an alternative text version for email programs that don t accept HTML. If you want to send HTML mail or attachments, I suggest that you use the PHPMailer class. It s open source and is available for free from http:// phpmailer.sourceforge.net/. The site has a tutorial showing you how to use it. As you ll see in later chapters, online forms lie at the heart of just about everything you do with PHP. They re the gateway between the browser and the web server. You ll come back time and again to the techniques that you have learned in this chapter. 149 Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.
PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY 2. In the code that processes the message, set a default value for a multiple-choice list in the same way as for an array of check boxes. $interests = isset($interests) ? $interests : array(’None selected’); $characteristics = isset($characteristics) ? $characteristics : . array(’None selected’); 3. When building the body of the message, use a foreach loop to iterate through the subarray, or use implode() to create a comma-separated string like this: $message .= ‘Characteristics associated with Japan: ‘.implode(’, ‘, . $characteristics); A complete script using all form elements is in contact10.php in the download files for this chapter. Redirecting to another page Throughout this chapter, everything has been kept within the same page, even if the message is sent successfully. If you prefer to redirect the visitor to a separate acknowledgment page, locate this section of code at the end of the message processing section: // send it $mailSent = mail($to, $subject, $message, $additionalHeaders); if ($mailSent) { // $missing is no longer needed if the email is sent, so unset it unset($missing); } } } Change it like this: // send it $mailSent = mail($to, $subject, $message, $additionalHeaders); if ($mailSent) { // redirect the page with a fully qualified URL header(’Location: http://www.example.com/thanks.php’); exit; } } } The HTTP/1.1 protocol stipulates a fully qualified URL for a redirect command, although most browsers will perform the redirect correctly with a relative pathname. When using the header() function, you must be very careful that no output is sent to the browser before PHP attempts to call it. If, when testing your page, you see an error message warning you that headers have already been sent, check there are no new lines or If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.
BRINGING FORMS TO LIFE selected=”selected” >friends of ED . . .
2. Because there is always an element in the $_POST array for a drop-down menu, it doesn t require any special handling in the code that builds the body of the email. PHP Solution 5-10: Getting data from a multiple-choice list Multiple-choice lists are similar to check boxes: they allow the user to choose zero or more items, so the result is stored in an array. If no items are selected, the $_POST array contains no reference to the list, so you need to take that into consideration both in the form and when processing the message. 1. The following code shows the first two items from the multiple choice list in con tact.php with the name attribute and PHP code highlighted in bold. Note that the name attribute needs a pair of square brackets on the end to store the results as an array. The code works in an identical way to the check boxes in PHP Solution 5-8.
147 If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.
PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY As with radio buttons, if no check box is selected, the $_POST[’interests’] element is not even created. So the code for the first check box contains the following: $OK = isset($_POST[’interests’]) ? true : false; This uses the same $OK variable as the radio button group, but that s not a problem, since you ve finished with $_POST[’subscribe’]. So it s safe to reuse $OK. 2. Because the check box array might never be created, you need to set a default value before attempting to build the body of the email. This time, rather than a string, it needs to be presented as an array like this: // set default values for variables that might not exist $subscribe = isset($subscribe) ? $subscribe : ‘Nothing selected’; $interests = isset($interests) ? $interests : array(’None selected’); 3. To extract the values of the check box array, you can use a foreach loop or the implode() function. This oddly named function joins array elements. It takes two arguments: a string to be used as a separator and the array. So, implode(’, ‘, $interests) joins the elements of $interests as a comma-separated string. PHP Solution 5-9: Getting data from a drop-down option menu Drop-down option menus created with the