Archive for January, 2008

USING PHP TO MANAGE FILES To move the (Web host server)

Friday, January 25th, 2008

USING PHP TO MANAGE FILES To move the pointer to the beginning of a file Pass the reference to the open file to rewind() like this: rewind($file); To move the pointer to the end of a file This is a little more complex. You need to use fseek(), which moves the pointer to a location specified by an offset and a PHP constant. The constant that represents the end of the file is SEEK_END, so an offset of 0 bytes places the pointer where you want it. You also need to pass fseek() a reference to the open file, so all three arguments together look like this: fseek($file, 0, SEEK_END); SEEK_END is a constant, so it doesn t need quotes, and it must be in uppercase. This is probably the only way you ll need to use fseek(), but you can also use it to move the internal pointer to a specific position or relative to its current position. For details, see www.php.net/manual/en/function.fseek.php. The file fopen_pointer.php uses the fopen() r+ mode to demonstrate combining several read and write operations, and the effect of moving the pointer. The main code looks like this: $filename = ‘C:/private/filetest05.txt’; // open a file for reading and writing $file = fopen($filename, ‘r+’); // the pointer is at the beginning, so existing content is overwritten fwrite($file, $contents); // read the contents from the current position $readRest = ‘’; while (!feof($file)) { $readRest .= fgets($file); } // reset internal pointer to the beginning rewind($file); // read the contents from the beginning (nasty gotcha here) $readAll = fread($file, filesize($filename)); // pointer now at the end, so write the form contents again fwrite($file, $contents); // read immediately without moving the pointer $readAgain = ‘’; while (!feof($file)) { $readAgain .= fgets($file); } // close the file fclose($file); 193
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY If

Thursday, January 24th, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY If you load fopen_exclusive.php into a browser, type some text, and click Write to file, the content should be written to filetest05.txt in your target folder, as shown in the following screenshot: If you try it again, you should get a series of error messages telling you that the file already exists. I ll show you later in the chapter how to use x mode to create a series of consecutively numbered files. Combined read/write operations with fopen() By adding a plus sign (+) after any of the previous modes, the file is opened for both reading and writing. You can perform as many read or write operations as you like and in any order until the file is closed. The difference between the combined modes is as follows: r+: The file must already exist; a new one will not be automatically created. The internal pointer is placed at the beginning, ready for reading existing content. w+: Existing content is deleted, so there is nothing to read when the file is first opened. a+: The file is opened with the internal pointer at the end, ready to append new material, so the pointer needs to be moved back before anything can be read. x+: Always creates a new file, so there s nothing to read when the file is first opened. Reading is done with fread() or fgets(), and writing with fwrite() exactly the same as before, so I won t go through each mode. What s important is to understand the position of the internal pointer. Moving the internal pointer Since reading and writing operations always start wherever the internal pointer happens to be, you normally want it to be at the beginning of the file for reading, and at the end of the file for writing.
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

USING PHP TO MANAGE FILES If you load (Web site domain)

Wednesday, January 23rd, 2008

USING PHP TO MANAGE FILES If you load fopen_write.php into a browser, type something into the text area, and click Write to file, PHP creates filetest04.txt and inserts whatever you typed into the text area. Since this is just a demonstration, I ve omitted any checks to make sure that the file was successfully written. Open filetest04.txt to verify that your text has been inserted. Now type something different into the text area and submit the form again. The original content is deleted from filetest04.txt and replaced with the new text. No record is kept of the deleted text. It s gone forever. Appending content with fopen() The append mode is one of the most useful ways of using fopen(), because it adds new content at the end, preserving any existing content. The main code in fopen_append.php is the same as fopen_write.php, apart from those elements highlighted here in bold: // open the file in append mode $file = fopen(’C:/private/filetest04.txt’, ‘a’); // write the contents after inserting new line fwrite($file, “rn$contents”); // close the file fclose($file); If you load fopen_append.php into a browser and insert some text, it should now be added to the end of the existing text, as shown in the following screenshot. Notice that I have enclosed $contents in double quotes and preceded it by carriage return and new line characters (rn). This makes sure that the new content is added on a fresh line. When using this on Mac OS X or a Linux server, omit the carriage return, and use this instead: fwrite($file, “n$contents”); This is a very easy way of creating a flat-file database. We ll come back to append mode in Chapter 9. Writing a new file with fopen() Although it can be useful to have a file created automatically with the same name, it may be exactly the opposite of what you want. To make sure you re not overwriting an existing file, you can use fopen() with x mode. The main code in fopen_exclusive.php looks like this (changes are highlighted in bold): // create a file ready for writing only if it doesn’t already exist $file = fopen(’C:/private/filetest05.txt’, ‘x’); // write the contents fwrite($file, $contents); // close the file fclose($file); 191
From our experience, we can recommend PHP5 Web Hosting services, if you need affordable webhost to host and run your web application.

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY combination (Virtual web hosting)

Wednesday, January 23rd, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY combination with feof() to read right through to the end of the file. This is done by replacing this line $contents = fread($file, filesize($filename)); with this (the full script is in fopen_readloop.php) // create variable to store the contents $contents = ‘’; // loop through each line until end of file while (!feof($file)) { // retrieve next line, and add to $contents $contents .= fgets($file); } The while loop uses fgets() to retrieve the contents of the file one line at a time !feof($file) is the same as saying until the end of $file and stores them in $contents. It doesn t take a genius to see that both methods are more long-winded than using file() or file_get_contents(). However, you need to use either fread() or fgets() if you want to read the contents of a file at the same time as writing to it. Replacing content with fopen() The first of the write-only modes (w) deletes any existing content in a file, so it s useful for working with files that need to be updated frequently. You can test the w mode with fopen_write.php, which has the following PHP code above the DOCTYPE declaration: There s no need to use a loop this time: you re just writing the value of $contents to the opened file. The function fwrite() takes two arguments: the reference to the file and whatever you want to write to it. In other books or scripts on the Internet, you may come across fputs() instead of fwrite(). The two functions are identical: fputs() is a synonym for fwrite().
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

USING PHP TO MANAGE FILES The fopen() function (Photo web hosting)

Tuesday, January 22nd, 2008

USING PHP TO MANAGE FILES The fopen() function returns a reference to the open file, which can then be used with any of the other read/write functions. So, this is how you would open a text file for reading: $file = fopen(’C:/private/filetest03.txt’, ‘r’); Thereafter, you pass $file as the argument to other functions, such as fgets(), feof(), and fclose(). Things should become clearer with a few practical demonstrations. Rather than building the files yourself, you ll probably find it easier to use the download files. I ll run quickly through each mode. Reading a file with fopen() The file fopen_read.php contains the following code: If you load this into a browser, you should see the following output: The inline comments in the code explain the process. Unlike file_get_contents(), the function fread() needs to know how much of the file to read. So you need to supply a second argument indicating the number of bytes. This can be useful if you want, say, only the first 100 characters of a text file. However, if you want the whole file, you need to pass the file s pathname to filesize() to get the correct figure. The nl2br() function in the final line converts new line characters to XHTML
tags. The other way to read the contents of a file with fopen() is to use the fgets() function, which retrieves one line at a time. This means that you need to use a while loop in 189
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.

Web hosting reseller - PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY the

Monday, January 21st, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY the existing content. At other times, you may want to append new material. At yet other times, you may want PHP to create a file if it doesn t already exist. The other thing you need to understand is where each mode places the internal pointer when it opens the file. It s like the cursor in a word processor: PHP starts reading or writing from wherever the pointer happens to be when you call fread() or fwrite(). Table 7-2 brings order to the confusion. Table 7-2. Read/write modes used with fopen() Type Mode Description Read-only r Internal pointer initially placed at beginning of file. Write-only w Existing data deleted before writing. Creates a file if it doesn t already exist. a Append mode. New data added at end of file. Creates a file if it doesn t already exist. x Creates a file only if it doesn t already exist, so no danger of deleting existing data. Read/write r+ Read/write operations can take place in either order and begin wherever the internal pointer is at the time. Pointer initially placed at beginning of file. File must already exist for operation to succeed. w+ Existing data deleted. Data can be read back after writing. Creates a file if it doesn t already exist. a+ Opens a file ready to add new data at end of file. Also permits data to be read back after internal pointer has been moved. Creates a file if it doesn t already exist. x+ Creates a new file, but fails if a file of the same name already exists. Data can be read back after writing. Choose the wrong mode, and you could end up overwriting or deleting valuable data. You also need to be careful about the position of the internal pointer. If the pointer is at the end of the file, and you try to read the contents, you ll end up with nothing. On the other hand, if the pointer is at the beginning of the file, and you start writing, you ll overwrite the equivalent amount of any existing data. You work with fopen() by passing it the following two arguments: The pathname to the file you want to open One of the modes listed in Table 7-2 (for a binary file, such as an image, add b)
We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.

USING PHP TO MANAGE FILES If you re working (Michigan web site)

Monday, January 21st, 2008

USING PHP TO MANAGE FILES If you re working with each line as a whole, pass the entire line to rtrim(). 5. As always, you need to check that the file is accessible before attempting to process its contents, so wrap the main PHP block in a conditional statement like this (see file03.php): $textfile = ‘C:/private/filetest03.txt’; if (file_exists($textfile) && is_readable($textfile)) { // read the file into an array called $users $users = file($textfile); // loop through the array to process each line for ($i = 0; $i < count($users); $i++) { // separate each element and store in a temporary array $tmp = explode(', ', $users[$i]); // assign each element of the temporary array to a named array key $users[$i] = array('name' => $tmp[0], ‘password’ => . rtrim($tmp[1])); } } else { 7 echo “Can’t open $textfile”; } To avoid typing out the file pathname each time, begin by storing it in a variable. This simple script extracts a useful array of names and associated passwords. You could also use this with a series of sports statistics or any data that follows a regular pattern. Opening and closing files for read/write operations The functions we have looked at so far do everything in a single pass. However, PHP also has a set of functions that allow you to open a file, read it and/or write to it, and then close the file. The following are the most important functions used for this type of operation: fopen(): Opens a file fgets(): Reads the contents of a file, normally one line at a time fread(): Reads a specified amount of a file fwrite(): Writes to a file feof(): Determines whether the end of the file has been reached rewind(): Moves an internal pointer back to the top of the file fclose(): Closes a file The first of these, fopen(), is the most difficult to understand, mainly because you need to specify how the file is to be used once it s open: fopen() has one read-only mode, three write-only modes, and four read/write modes. Sometimes, you want to overwrite 187
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

Web design course - PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY The

Sunday, January 20th, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY

The count() function returns the length of an array, so in this case the value of count($users) is 2. This means the first line of the loop is equivalent to this: for ($i = 0; $i < 2; $i++) { The loop continues running while $i is less than 2. Since arrays are always counted from 0, this means the loop runs twice before stopping. Inside the loop, the current array element ($users[$i]) is passed to the explode() function, which converts a string into an array by splitting the string each time it encounters a separator. In this case, the separator is defined as a comma followed by a space (', '). However, you can use any character or sequence of characters: using "t" (see Table 3-4 in Chapter 3) as the first argument to explode() turns a tab-separated string into an array. The first line in filetest03.txt looks like this: david, codeslave When this line is passed to explode(), the result is saved in $tmp, so $tmp[0] is david, and $tmp[1] is codeslave. The final line inside the loop reassigns $tmp[0] to $users[0]['name'], and $tmp[1] to $users[0]['password']. The next time the loop runs, $tmp is reused, and $users[1]['name'] becomes chris, and $users[0]['password'] becomes bigboss. 4. Save file.php, and view it in a browser. The result should look like this: Take a close look at the gap between codeslave and the closing parenthesis of the first subarray. If a line ends in a new line character, the file() function doesn t remove it, so you need to do it yourself. Pass the final item of $tmp to rtrim() to remove the new line character like this: $users[$i] = array('name' => $tmp[0], ‘password’ => rtrim($tmp[1]));
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Photo web hosting - USING PHP TO MANAGE FILES To demonstrate the

Saturday, January 19th, 2008

USING PHP TO MANAGE FILES To demonstrate the file() function, let s use filetest03.txt, which contains just two lines as follows: david, codeslave chris, bigboss This will be used as the basis for a simple login system to be developed further in Chapter 9. PHP Solution 7-2: Reading a text file into an array 1. Create a PHP file called file.php inside the filesystem folder. Insert the following code (or use file01.php from the download files for this chapter):

  

This draws the contents of filetest03.txt into an array called $users, and then passes it to print_r() to display the contents of the array. The

 tags simply make the output easier to read in a browser.   2. Save the page, and load it in a browser. You  should see the output shown in the screenshot  to the right.  It doesn t look very exciting, but now that each line is a separate array element, you can loop through the array to process each line individually.   3. You need to use a counter to keep track of each  line; a for loop is the most convenient (see  The  versatile for loop  in Chapter 3). To find out how  many times the loop should run, pass the array to the count() function to get its  length. Amend the code in file.php like this (or use file02.php):   $tmp[0], ‘password’ => $tmp[1]); }   ?>
   185    
If you are in need for cheap and reliable webhost to host your website, we recommend http web server services.

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY If (Unable to start debugging on the web server)

Friday, January 18th, 2008

PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY If the file_get_contents() function can t open the file, it returns false. Often, you can test for false by using the negative operator like this: if (!$contents) { The reason I haven t used that shortcut here is because the external file might be empty, or you might want it to store a number. As explained in The truth according to PHP in Chapter 3, an empty string and 0 also equate to false. So, in this case, I ve used the identical operator (three equal signs), which ensures that both the value and the data type are the same. 6. Test the page in a browser, and it should work as before. Change the first line like this so that it loads filetest02.txt: $contents = file_get_contents(’C:/private/filetest02.txt’); The new text file contains the number 0, which should display correctly when you test file_get_contents.php. Delete the number in filetest02.txt, and reload file_get_contents.php. You should get a blank screen, but no error message. This indicates that the file was loaded successfully, but doesn t contain anything. 7. Change the first line in file_get_contents.php so that it attempts to load a nonexistent file, such as filetest0.txt. When you load the page, you should see an ugly error message reporting that file_get_contents() failed to open stream in other words, it couldn t open the file. 8. This is an ideal place to use the error control operator (see Chapter 4). Insert an @ mark immediately in front of the call to file_get_contents() like this: $contents = @ file_get_contents(’C:/private/filetest0.txt’); 9. Test file_get_contents.php in a browser. You should now see only the following custom error message: Always add the error control operator only after testing the rest of a script. When devel- oping, error messages are your friends. You need to see them to understand why some- thing isn t working the way you expect. Text files can be used as a flat-file database where each record is stored on a separate line, with a tab, comma, or other delimiter between each field (see http://en.wikipedia.org/ wiki/Flat_file_database). When handling this sort of file, it s more convenient to store each line individually in an array ready for processing with a loop. The PHP file() function builds the array automatically.
From our experience, we can recommend PHP5 Web Hosting services, if you need affordable webhost to host and run your web application.