Calendar
Archives |
Wednesday, October 18. 2006Digg Button GeneratorI've recently begun adding "Digg This" buttons to my blog posts to enable visitors to easily submit useful posts to Digg, complete with all of the required fields already populated. However, in order to provide Digg with your URL, title and description, you must URL encode these data - which I found to be slightly tedious. The Digg Button Generator simplifies the process of creating Digg buttons for your blog or website by providing a simple form and a choice of buttons and topics. Click here to try it out, or try clicking on the "Digg It" button above, which was created using the Digg Button Generator. Wednesday, August 30. 2006Reading XML files using PHP 5PHP provides a number of straightforward methods of parsing XML files "out of the box". This simple example shows how an XML file containing information about a number of movies can be read and displayed using PHP’s built-in simplexml_load_file() method. The XML file we’ll use looks something like this: <?xml version="1.0" encoding="utf-8" ?> <movies> <movie> <title>Star Wars</title> <year>1977</year> </movie> <movie> <name>Apocalypse Now</name> <year>1979</year> </movie> <movie> <title>Raiders Of The Lost Ark</title> <year>1981</year> </movie> </movies> In the above example, the XML file contains a list of "movie" nodes, each with a title and a year. The root node, which represents the entire list of movies, is called "movies". Notice that the file includes a valid XML header and that the XML itself is well-formed (i.e. for every opening tag there is a closing tag). Now, to loop through each of the movies in the file (saved as "mymovies.xml") and display their title and year, the PHP code would be as follows: Each of the movie nodes is turned into an array called $movie, the contents of which which may then be accessed in the usual manner. The output of the above code should be something like this: It doesn’t get much easier than that!Title: Star Wars Saturday, July 29. 2006
How to password protect your website ... Posted by Matt
in Stuff at
19:54
Comments (0) Trackbacks (0) How to password protect your website using .htaccessUsing htaccess is a simple and fairly secure method of password-protecting a site, or a specific directory within a site, on an Apache web server. In fact, the process of adding password protection to a directory consists of little more than creating and uploading a pair of ASCII text files. This tutorial won’t look at the wider applications of htaccess files, but will tell you all you need to know to start using them to password protect your sites. To begin with, simply open up a text editor such as Notepad and enter the following, taking care to reproduce the line breaks exactly as they appear below: AuthName ProtectedDirectory The first line is simply the name of the directory or site you wish to protect – the name you choose is not important, although if you want to use spaces in the name, you should enclose it in quotes. The second line refers to the type of user authentication used to protect the directory, in this case Basic authentication (i.e. username and password). The next line is the path to the file on your web server containing your usernames and passwords (the .htpasswd file described below). Ideally, this file should be stored outside of the web-accessible area on your server, typically in a directory above the root of your website. If you aren’t sure what this should be, ask your hosting provider. The last line simply indicates that user credentials specified by you (in the .htpasswd file) must be supplied. Save the file with the name .htaccess, including the preceding dot. If your text editor tries to append an additional suffix to the file name such as .txt, we’ll remove this when we’ve uploaded the file. Next, open up a new document in your text editor. Here we’re going to specify the username and password required to access the protected directory, but first you’ll need to encrypt the password using one of the many htaccess password generator tools available on the web. The password tool should produce something similar to the following, consisting of the username you specified (“webuserâ€) followed by a colon then an encrypted version of the password you specified (in this case it was “letmein†– make sure you choose a more unique password!). webuser:weVUuXQPkIDEI Copy and paste this line into your new text document and save it as .htpasswd, again taking care to include the dot at the beginning. Now you are ready to upload the files. The .htaccess file should be uploaded to the root of the directory you wish to protect, and the .htpasswd file should be placed in the directory specified in the .htaccess file. The files should both be uploaded as ASCII (your FTP program should give you the choice of uploading files as either ASCII or BINARY). Bear in mind that all of the subdirectories beneath the directory containing the .htaccess file will also be password-protected. You can, however, override an .htaccess file by creating another and placing it in a directory beneath the one that contains the original .htaccess file. This allows you to remove the password protection for a particular subdirectory (and its subdirectories) or to specify a different username or password. Tuesday, July 18. 2006Turning off the "auto complete" feature in browsersFor some time now, all of the major browsers - including Internet Explorer and Firefox - have provided an optional "autocomplete" feature that remembers the values a user has entered into HTML forms, usually providing previously entered values in a drop down list. If you have your browser's auto complete feature turned on, clicking in the following text box, for example, should provide you with a list of possible values based on what you've entered on previous forms. The browser bases the list of previous values on the name given to the text box in the HTML code. In the above example, the text box is given the name "username". The browser, therefore, provides all of the values you've previously entered for other text boxes named "username". The code for this simple form is shown below:
While this feature is often considered to be a convenient time saver, it is also a potential security risk, especially on computers that are shared by more than one user. Imagine, for example, if Amazon's checkout form remembered your credit card number. However, there is an easy method of disabling this feature in your HTML code, as demonstrated by the form below: The code for this form has one simple addition, as shown below:
As you can see in the above example, the auto complete feature can be disabled on a field-by-field basis, so you could, for example, allow usernames and email addresses to be auto completed by the browser while at the same time disable the feature for more sensitive input such as credit card details on the same form. However, you can also disable auto completion for the whole form simply by adding autocomplete="off" to the opening form tag. Saturday, July 1. 2006
How to encrypt passwords stored in a ... Posted by Matt
in Stuff at
18:36
Comments (0) Trackbacks (0) How to encrypt passwords stored in a MySQL databaseWhen storing user login credentials (i.e. usernames and passwords) in a database to facilitate a password-protected site of some kind, a simple and effective security precaution is to hash or encrypt the password. This has the benefit of protecting your users' passwords from prying eyes, should your database be compromised in any way, since their chosen passwords will be stored as an apparently random sequence of characters. MySQL provides a simple hashing function called SHA1 (a member of the Secure Hash Algorithm family of cryptographic hash functions). To illustrate its use, imagine that we have a MySQL table, tbl_users, with the following simple schema: username varchar(40) To add a record of your username and password to the table, you can use the following SQL statement: insert into tbl_users (username, password) values ('myusername', SHA1('mypassword')); Now, in order for your users to log in - i.e. enter a password that matches the one held in the database - you must take the password they enter and apply the SHA1 function to it before comparing it with the password held. This can be done using the following SQL statement: select * from tbl_users where username = 'username' and password = SHA1('password'); Note: It is assumed that the parameters username and password are form variables, extracted from a form using your programming language of choice, such as PHP, ASP or Java. The SQL used in this example is generic, as it is intended to work with whatever language you are using. When you run the above query, the username and hashed password stored in the database are compared with the username and a hashed version of the password entered by the user and will return a matching record if one exists. Friday, June 16. 2006How to convert a Java String to an int, or an int to a StringTo Java veterans, converting from a String to an int - or less commonly, from an int to a String - may seem like a trivial matter. However, for beginners, it's a common sticking point and a question that pops up time and time again. The purpose of this post, therefore, is to provide a short overview of the methods available to convert between the two data types. The following sample code demonstrates these methods.
Most of these methods are very straightforward. However, it's worth noting that attempting to parse a String that doesn't consist entirely of numerical digits as an int will result in a NumberFormatException. Other mistakes, such as attempting to assign a String or char value to a variable of type int, should be caught a compile time. Also notice that it is not possible to cast from a String to an int or vice versa. These are inconvertible types and an attempt to do something like the following would also result in a compilation error: myString = (String) myInt; //wrong! Finally, remember that - as demonstrated in method two above - you don't need to explicitly convert an int to a String to be able to use it with other Strings. The int will be implicitly converted to a String value as soon as you concatenate it with another String, for example: String myMessage = "The number of people reading this blog is currently " + 2; Output: The number of people reading this blog is currently 2 Friday, June 2. 2006"Printer friendly" pages using CSSMany webpages provide a link to a "printer friendly" version that typically strips the page of images and superfluous content such as the menu and ensures the text fits nicely onto an A4 page. Usually, these pages are either created manually or programmatically using some form of server-side scripting. However, CSS allows the specification of printer-specific style sheets that are automatically used to style a page when it is sent to the printer. The advantage of this is that you don't need to maintain a separate "printer friendly" version of every page you wish to print. From the user's perspective printing is also more straightforward, being simply a click of the Print button away. Assuming you're using an external stylesheet to define the styles for your pages on screen, you can use the following code in the <head> section of your HTML page to define another stylesheet for printers:
The screen.css file defines your CSS styles as usual, but the print.css file defines styles that are better suited to printed output. Consider the following examples:
Notice that the display property for the banner and the menu have been set to none in the print stylesheet, so that they are not displayed. A serif font instead of a sans-serif font is also used in the printer friendly version. You can view a simple example and download the source code here. To try it out, visit the page and select Print Preview from your browser's File menu - you should see the simplified, printer-friendly version of the page that uses the print.css stylesheet. Saturday, May 20. 2006
Using CSS and JavaScript to show and ... Posted by Matt
in CSS at
19:30
Comments (18) Trackbacks (0) Using CSS and JavaScript to show and hide contentAt some point, you've probably visited web pages that use a small plus (+) and a small minus (-) to show and hide content, like many familiar desktop applications. Typically, these work by clicking on the plus sign to expand your view of some data then clicking on the minus sign to hide it again. This is a useful technique for displaying large amounts of data, allowing the user to decide on just how much detail they wish to see. In a nutshell, the effect can be achieved by writing the data you wish to initially have hidden inside a div (or other element) and using the CSS properties of that div to prevent it from being displayed when the page is loaded. Then you can use some JavaScript to reset the div's display property based on the user's input. First, let's take a look at the JavaScript, which consists of two small functions. The first toggles the display property of a given element between "none" (hide) and "block" (show). The second function, which is called by the first, simply swaps the plus and minus images around when they're clicked on. By taking note of the current state of the button, this function ensures that the plus sign is only displayed when there is hidden data to be expanded, and the minus sign only when the displayed data is to be hidden again. //function to display or hide a given element //function to swap an image based on its current state Now let's look at the HTML code used to display the plus or minus button. The onclick event is used to call the showHideItems() function when the link is clicked. The function takes the ID of the hidden item (used to identify the div below) and the ID of the button being clicked (so that the function knows which image to swap from a minus to a plus or vice versa). A suitable title is provided so that users unfamiliar with the "show and hide" technique will be given a small tool tip describing the purpose of the button. Since the item is initially hidden, the image displayed in the first instance is the plus sign (plus.gif), used to expand the hidden data. <a onclick="showHideItems('item1', 'button1');" title="Show/hide items"> Finally, here is the HTML that creates the initially hidden div. The ID given to the div element is the same as that called in the showHideItems() function call above. Also notice that the display style attribute is set initially to "none" (hide). <!-- begin div containing hidden items --> By putting all of these elements together, you will be able to add sophisticated-looking functionality to any data-heavy page. Remember that if you wish to have more than one of these expanding divs on your page, they (and their associated button) should be given unique IDs (e.g. item2 and button2, item3 and button3, etc.) so that the showHideItems() function knows which div to expand and which image to swap. Tuesday, May 2. 2006
How to set the value of a form field ... Posted by Matt
in Stuff at
20:41
Comments (0) Trackbacks (0) How to set the value of a form field using JavaScriptIf you want to set the value of a form variable using client-side code (i.e. JavaScript), you can't use the document.write() technique to simply write the form value into your HTML - instead you must use the Document Object Model (DOM) to assign a value to your form elements. The following code shows how to set the value of a couple of hidden form fields to the current day and month:
Now, when the form is submitted, the numerical values of the day of the month and the month of the year will be passed as part of the POST request. Note that JavaScript starts counting the months from zero, i.e. January = 0, February = 1, and so on. In order to pass the "human friendly" value you might expect, simply alter the code above to read value = now.getMonth()+1. Thursday, April 20. 2006Checking if a variable contains a given substring in JavaScriptYou can test a String in JavaScript to see if it contains a given substring in a number of ways. Here's one way, which effectively checks to see if the image referred to by the variable myImage matches the file name "logo.jpg". This is useful for finding images on a page regardless of their full path. if (myImage.src.match("logo\.jpg") != null) { Note that the match() method returns null if the substring is not found, which is how we detect if the match was found. Alternatively, you can use the indexOf() method, which returns -1 if no match is found:
Thanks to pig for pointing out some improvements to this post. He also suggests the built-in JavaScript search() method for searching strings. For example, str.search("logo") will return the position of "logo" in the string str if it exists, or -1 if no match is found. Thursday, April 6. 2006Obtaining the auto-incremented key of the last inserted MySQL recordAfter inserting a new record into a table in your MySQL database, you'll often find that you need to know the automatically-incremented primary key given to that record by MySQL. This value is typically used to insert related records into other tables that reference the first table via a foreign key, or to simply perform further updates to the recently inserted record itself. The following SQL statement will return the most recently inserted primary key from the table specified in any MySQL database: SELECT last_insert_id() AS lastKey FROM MyTable In order to use this value within your Java application, simply execute your insert statement as normal, then execute the above SELECT statement to extract the primary key: private static final String SQL_SELECT_LAST_KEY = "SELECT last_insert_id() AS lastKey FROM MyTable"; ... //code to execute insert statement ... myStatement = myConnection.createStatement(); myRecordSet = myStatement.executeQuery(SQL_SELECT_LAST_KEY); while(myRecordSet.next()) { myKey = myRecordSet.getInt("lastKey"); } Sunday, April 2. 2006How to find out the machine name in JavaOften you'll be testing and deploying your Java web applications across more than one environment, perhaps a development machine, a test machine and a production machine (or machines). I've found that there are some operations that you don't always want to carry out "for real" on your test or development box and have found it useful to be able to programmatically determine the identity of the machine on which your code is executing. This way, you can move your code between environments without worrying that you forgot to comment out or otherwise disable that critical piece of code. To discover the name of the computer from within your Java program, use the following code (note the import statement): import java.net.InetAddress; Monday, March 27. 2006
How to install Apache and Microsoft ... Posted by Matt
in Stuff at
19:23
Comments (0) Trackbacks (0) How to install Apache and Microsoft IIS on the same machineIf you're developing sites on both the Apache web server and Microsoft's Internet Information Services (IIS), it's sometimes convenient to be able to run and test both platforms on the same box. Assuming you're running Windows, the easiest way to do this is to install IIS then Apache on your machine and have IIS listen on port 80 (the default, so you need to do nothing) and have Apache listen on another - typically port 8080. This can be specified during the Apache install using the wizard or if you've already installed Apache, you can change the port as follows:
Your IIS pages will be available via http://localhost and your Apache pages via http://localhost:8080 Friday, March 24. 2006Using SAX to parse an XML file in JavaIn order to parse (i.e. read from) an XML file using SAX (Simple API for XML), you must first instantiate a SAX parser object, which will do all the hard work for you. The following code outlines the packages you'll need to import and how to instantiate the parser: import org.xml.sax.*; Then you have to provide methods to deal with the events triggered when the parser encounters each of the following:
For example, an outline method for processing a start tag might look like:
Wednesday, March 15. 2006Removing the line break from an HTML heading tagIt's always a good idea to use HTML heading tags such as <h1>, <h2> etc. to mark up headings within your HTML in order to preserve the logical structure of your document, and improve search engine readability By default, heading tags are followed by a line break that forces an text or other elements following the heading to appear on a new line, as shown: My Heading: To remove this line break, a simple line of CSS code is required, as follows: h1 { display: inline; } The <h1> tag will now behave as an inline element (in much the same manner as the <span> tag) instead of a block level element (such as a <p> tag or <div> tag), which would ordinarily force a line break. My Heading: My text |
QuicksearchCategoriesBlog Administration |
|||||||||||||||||||||||||||||||||||||||||||||||||