Archive for the ‘Web’ Category

PHP: Post the results of a simple MySql Query on a Web Page

Saturday, October 24th, 2009

Say you want to post the results of a simple query from a MySQL database on a Web page, using PHP. You would think that all you’d need to do is assign a variable name to the results of the SQL query, and then ask PHP to print the variable.

It doesn’t work that way. Instead of PHP printing the result, what gets printed is a mysterious message, like “Resource ID #3″

As explained here, the variable itself points to a place holder of sorts. To get the actual value, you have to use another MySQL function.

In this case that function would be mysql-fetch-row.

For example, within the PHP body of code, you do something like this:

$QueryResult = mysql_query(“select avg(Height) from Boys);

$ResultInBetweenStep = mysql_fetch_row($QueryResult);

$ResultPresent = $ResultInBetweenStep[0];

echo($ResultPresent);

In the above quote, we’re getting the result of a query from a table called Boys that is the average of all the entries in the Height column. It is assigned to the variable $QueryResult.

In order to get the actual data from the query, the function mysql_fetch_row is applied to $QueryResult, and the results are stored in another variable, $ResultInBetweenStep.

The final step is to assign a variable to the first row of $ResultInBetweenStep only (which would be the *only* row in the query, as the average function will return a single number), which, here, is called $ResultPresent.

$ResultPresent can then be printed.

There are other MySql functions that allow you to extract more complex bits of information from a MySQL query. Check the mysql_fetch_* entries here for more info.–Joab Jackson





Web: HTTP, the King of URIs

Thursday, October 15th, 2009

The Web is based on Universal Resource Identifiers, or URI. “HTTP” is a URI. It is the most popular one, in fact. “FTP” is a URI. There is no centralized organization that manages “official” URIs. There is an unspoken assumption that URIs are not created lightly. Generalizing, the URI specification defines a space in which resources can be organized by some means. “The principle that anything, absolutely anything, ‘on the Web’ should identified distinctly by an otherwise opaque string of characters,” according to the document.

The resources can be formally defined in relation to one another. Or not.

HTTP has proved to be the most popular URI. It is a protocol for getting stuff, hence the name (Hypertext Transfer Protocol). It makes no assumptions about what you want to get, be it a HTML Web page, PDF, Word document, etc. The most used format it serves on the Web, HTML has “no special place architecturally” within the Web architecture. It is just another format. The format of the data is notated by its MIME type.

The intro also states an interesting, though, thus far in my mind, unconnected factoid: That HTTP runs up against some compatibility problems with distributed object-oriented systems developed by the software development community (As opposed to the Web developers), namely CORBA, DCOM and RMI. Remote Procedure Calls could be a bridge: RDF can work with RPC, namely by considering RPC a structured document.

Taken from a W3C document on design issues for the Web, notably this overview section.

–Joab Jackson





Apache: Assembling Web pages with Server Side Includes

Saturday, September 12th, 2009

For some time I’ve been thinking about putting all my Web pages in a standard template, one that would have with links running down one side of the page and a title on the top (This is called chrome, so I understand).

I could embed these elements by hand easily enough on each page, but if I ever needed to make a change to the chrome, I would then have to go back and change each and every page. I figured there must be a way to have a single file somewhere with one the code, which then could be read for each page being served up.

After some surfing about, I found the best way to do this, at least in Apache, is with Server Side Includes (SSI).

In a nutshell, SSI is a server-side scripting language that tells Apache to include a file or set of files into a Web page. (There is actually a whole range of things that can be inserted in a Web page with SSI. For simplicity, I’ll just concentrate on including all the contents of another file).

And example of the basic use of the command for including a file in a Web page is:

<!–#include virtual=”PageToBeIncluded.txt”–>

You embed this bit of text into the place on your Web page where you want the text to be inserted. Then when the page is called, Apache will insert the text at that point of the document.

Note that the SSI command is included as a *HTML Comment* — This is done so that if the server doesn’t render the page correctly, the user won’t see the actual SSI command.

So, at its simplest, here is an example of how SSI works. One file, “sample.html”, has this code:

<html>
<body>
<!–#include virtual=”add.txt”–>
<p>
I’m some text too!
</body>
</html>

And, in the same directory, a text file called “add.txt” has this content:

Hello World!
<p>
HELLO!

When requested by a user, “sample.html” will be returned by the Apache server with this code:

<html>
<body>
Hello World!
<p>
HELLO!
<p>
I’m some text too!
</body>
</html>

Not only plain text, but HTML markup can be inserted as well.

* * *

In order to use SSIs, you may have to make a number of changes to your setup of Apache.

The first thing to do is compile the “include” module into Apache, if it isn’t already.

For Debian/Ubuntu servers running Apache, you can run the a2enmod tool from the command line. When it asks which module to enable, type in “include”–then restart Apache (“/etc/init.d/apache2 restart”).

In addition to adding the include module, you should also make a few changes to your configuration files, as detailed here.

First, you should add a line into either a .htaccess file or the httpd.conf file. The line is “Options +Includes” The httpd.conf file is in the etc/apache2 directory on your server. If you haven’t created an .htaccess file before, you can create one in the root directory of your Web site, or whatever subdirectory below that where you want all the SSI action to take place.

Also, you should add another directive into the default config file of the “/etc/apache2/sites-enabled” folder (mine is “000-default”). The directive is “XBitHack Full” — the (somewhat convoluted) explanation for why you need to do this is here.

Again, within this file, find, or write, an entry for the specific folders where you want the SSI actions to take place, if it isn’t for the entire site (in which case you’d use the entry for the document root directory). For the document root entry, for instance, you would add it thusly:

DocumentRoot /var/www/
<Directory />
Options FollowSymLinks
AllowOverride All
XBitHack full
</Directory />

Lastly, the SSI tutorial advises that, if using XBitHack, to add execution permission to the Web page that is being embedded with another file:

chmod +x pagename.html

One more tip: While testing, if your SSI page is not working yet, try emptying the cache on your browser.





[ad]

CSS: Making a Box for a Web Page

Wednesday, July 1st, 2009

I needed to make a box on the right hand of my Web site, to hold some information. It turned out to be pretty easy: I used the CSS Box Model.

First, add the CSS box model specifications in the header of your html document:

<style type=”text/css”>
#box {
width: 200px;
height: 650px;
float: left;
margin: 1px;
border-color: black;
border-style: solid;
border-width: 30 px;
background-color: #F00;
padding: 1em 2em;
}
</style>
</head>

Note: You can also put them in a separate CSS stylesheet, but for simplicity’s sake, we’ll place it in the document this time around.

Then, add in the box where you need it in the HTML part of the document:

<div id=”box”>
Test in the box goes here.
</div>
</body>
</html>

I’ve shamelessly lifted these examples from a fine Tech Republic tutorial.

The full set of box model attributes can be found in W3C’s specification. You can get quite fancy with placement, fonts and whatnot.

Now you’d think you could use “align” to put the box’s “div” tag, right? Wrong! It’s been deprecated. Use “float” and place it in the CSS spec instead.

For a crude example of this in action, see the code for my home page.

–Joab Jackson





Java: Embedding Applets in a Web page

Saturday, June 27th, 2009

For most Java programming classes, the programs that students write are submitted as stand-alone executables. But how does one put them on the Web and offer them as a service for others to use?

You can make an applet. An applet is a Java program that can be run from within a Web browser (on a system that runs the Java Runtime Engine [JRE] that is, which, as of this writing, the iPhone doesn’t).

Pretty much anything you can do with the Java language you can do within an Applet. Both use the Java Virtual Machine (JVM). Though setting up the program to run as an Applet is a wee bit different than setting up as a stand-alone program.

Once, embedding an Applet on a Web page was easy. You’d simply use the <Applet> tag. That W3C has deprecated that tag, which means you shouldn’t use it any longer (Though it still works in most all browsers).

Instead, you have to use either the <embed> tag for Mozilla-based browsers, and the <object> tag for Internet Explorer browsers. And, realistically, if you’re planning to have any visitors at all, you should use both.

(Before we begin, you should test to see if you have Java properly installed on your machine, go here.)


First, here is the bare-bones markup you’d use to embed your applet using the <object> tag, for IE browsers. You can put this tag within the body of the html document:

<OBJECT
classid=”clsid:8AD9C840-044E-11D1-B3E9-00805F499D93″>
<PARAM name=”code” value=”[NAME OF THE YOUR PROGRAM].class”>
</OBJECT>

The markup above was derived from this Java documentation page.

The classid tells the browser what program (In this case, the JRE) on the user’s computer should run the code being pointed to (in this case the class file). The above series of numbers tells the browser to use the latest version of the JRE, though you can also specify some specific version (see documentation). You can also use optional attributes for setting height, width or other aspects of the applet. See a list of attributes here.


For the Mozilla family of browsers, you must use the embed tag. Embed is NOT supported by Internet Explorer and it is NOT recognized by the World Wide Web Consortium (W3C), but since Firefox et al do not support the Object tag, at least for Applets, you should use the embed tag. Here is the code for the Web page, again which can appear in the body:

<embed code=”[NAME OF YOUR PROGRAM].class”
type=”application/x-java-applet;version=1.6″>
</embed>

Again there are additional options you can add in.

It is worth noting for the beginner that with both the embed tag and the object tag, supplying the correct plug-in name is crucial. In this instance, for instance, “version=1.6.0″ would NOT work. If your Web page is not running the Applet by now, it may be due to you not using the correct name. Search the Web for answers!


If you put your Java Applet out on the Web, however, you have to prepare yourself for both types of browsers. This site helpfully demonstrates how to use both with an html document:

<object
classid=”clsid:8AD9C840-044E-11D1-B3E9-00805F499D93″>
<PARAM name=”code” value=”[NAME OF YOUR PROGRAM].class”>
<comment>
<embed code=”[NAME OF YOUR PROGRAM].class”
type=”application/x-java-applet;version=1.6″>
</embed>
</comment>


You can also post your program the old fashioned (i.e. deprecated) way, through the applet tag. Most browsers still recognize the applet tag, even though is not even supported in html 4.1 or even xhtml. Here’s how:

<body>
<applet code = “[NAME OF YOUR PROGRAM].class”>
</applet>

Please to note that all the description about the applet is actually in the opening tag. So you have to put a close bracket onto the end, and then you have to do a close applet (“</applet>”) tag as well.

Within the Applet tag, you can also specify attributes like width (“width = [fill in value here]“), height (“height =”), vertical margin (“vspace =”) horizontal margin (“hspace =”), alignment (“align =”) and others. Go here for a full list of optional attributes.


What about the code itself? You would build an Applet pretty much the same way you would build a stand-alone Java program.

Just like on the command line, what gets executed is a class file (a file with a .class extension), one that has been compiled from Java source code.

In the program code itself, there doesn’t have to be a “main” method, for instance. Instead, this subclass is used:

import javax.swing.*;
public class TestApplet2 extends JApplet {
public void init() {
add (new JLabel(“Hello World”, JLabel.CENTER));
}
}

After this, control of the applet is handed by “init” “start” “stop” and “destroy” control the applet.

For the user-interface, you can use some libraries, like Swing, but more on that later. If you don’t wish to test your code through a browser each time out, you can also use the Java Applet Viewer, which is in the SDK, and can be evoked from the command line.


All the code used in this entry, including Web pages for object, embed, applet and combined tagging, as well as a sample Java program, both before and after compilation, can be found in this zipped package. –Joab Jackson





PHP: Entering data into MySql with PHP

Tuesday, May 12th, 2009

For some reason, there is very little direct instruction on the Web about how to enter data into a MySQL database from a Web page, using PHP. This dearth of info is surprising insofar as this procedure is one of the most commonly executed actions on the Web.

There are plenty of online tutorials, but for some reason, they tend to be made more complicated than they need to be.

Anyway, forthwith, here is the very basic mechanism used for entering data into a database over the Web.

First gather the ingredients: This tutorial uses Linux for the Web server (Ubuntu 8.04), with Apache running the PHP module, with the MySQL package. Also, MySQL (5.1 in this example) is already set up and running, with all the permissions worked out.

In this example, we will use a new database to be run inside MySQL, called “test.” It will have a single table called “sample” with one column of data text data. What it is called is not relevant. You will also require a username and password for the database.

For this action to happen, we will need TWO web pages, an HTML landing page where the user enters the data, and a PHP page that the HTML page will call that will do the actual work of entering the data into the database. (These can be combined into one page with the “form action = self” html declaration, which I’ll figure out another day).

First, you create an HTML page, where the user can enter data. Instructions on how all this is done are here.

In the code on this page, the user has a box in which some data can be entered, which the page tags as the variable “somedata” when the submit button is pushed. Also, when the submit button is pushed, this page will call up a PHP page in the same directory, called “InsertingIntoDatabase.php” (which we will create in a moment).

<FORM ACTION=”InsertingIntoDatabase.php” METHOD=”get”>
<p>
Enter Data: <INPUT TYPE=”text” NAME=”somedata” />
</p>
<INPUT TYPE=SUBMIT VALUE=”GO” />
</FORM>

Note: For the full working code, click here, and save page, and replace the .txt extension in the file name with a .html extension.

For this setup, I used the HTML “get” method. I could have also used “post.” The differences between the two are explained here.

Now onto the PHP page. Basics on creating a PHP page are here. The PHP code block will have a number of discrete steps:

1. Connect to the database server:

$open = @mysql_connect(“localhost”,”[USERNAME]“, “[PASSWORD]“);
if (!$open) {
echo( “

Can’t connect to database!

” );
exit();
}

In this chunk, you are opening the database.

The @mysql_connect PHP command is the command that does the actual work of opening the database. It requires three things: Type of connection, user name and password. Since the Web page is on the same server as the database, the connection will be “localhost”. You need to enter a username and password for an account that has write privileges to the database you will be using.

You save this command and its arguments as a variable, called $open, in this case. $open is run when the Web page is called. If the connection does not work, (signified by “!$open”) either because the database is not found, or your username or password doesn’t work, then you will get an error message (“Can’t connect to database!”).

2. Gather the data and specify database to be used.

$somedata = $_GET["somedata"];
$db = (“test”);

In this step, you grab the data from the server that was saved by the HTML page under the variable “somedata”. In PHP, it will also be called somedata, as $somedata. You also specify the name of the database within MySQL that you will open. Here it is called “test” but you set the name when you created the database.

3. Prepare the SQL query:

$sql = “INSERT into sample VALUE(‘”.$somedata.”‘) “;

Here is the the actual query you will submit to the database. It is formatted exactly like any other MySQL query. (Note: in SQL speak, even inserting data is called a “query,” evidently).

For this query, we are sending the contents of $somedata to a one-column table called “sample.” (Obviously you need to replace “sample” with the name of your own table, the one that you created when you created your database within Mysql). Note all the query is in quotes, except for the PHP variable $somedata.

In PHP, variables can not be called from within a quoted stream of text. So we are concatenating a string together by breaking the query into two strings, one before the variable (which is placed where it is needed in the statement) and the other after. Concatenating elements together in PHP is done with the period, “.”

Also, MySQL itself (at least the 5.1 version) requires that text data must be entered with SINGLE, not double quotes, hence the single quotes above.

This query is saved in php as a variable, called $sql. It looks complicated, but what PHP is storing is a straight-forward MySQL data insert query.

4. Run the query

Here is the code for doing this..

$doit = mysql_db_query($db, $sql);

The database is already open, so all we need to do is enter the query. The PHP “mysql_db_query” command runs the actual query. It requires two bits of information: First element is the name of the database (captured as a variable called “$db” here). The second element is the SQL-formatted query (“$sql”).

The entire command is captured as the variable “$doit” which, again, runs when the page is called.

5. Report results on the page:

If the query for some reason does not take, we need to alert the user. Likewise, if it works, then we should also report that. This mightbe best handled by the PHP “If … Else” statement:

if (!$doit) {
echo(“It didn’t work because of this: ” .mysql_error());
}
else
echo (“Data entered!”);

Here, if the data was not inserted due to some error (“!$doit”) then the PHP returns a statement saying so (“It didn’t work because of this: “) along with the error message returned by MySQL itself (“mysql_error()”) concatenated onto the end.

If the transaction did work (“else”),a message of success is returned.

6. Close database

mysql_close($open);

And that is how you enter data into a MySQL database using PHP. There are lots more you can do it terms of security, handling of errors, input-checking and so on, but this is the bare-bones approach.

Note: For the full working code for this PHP page, click here, and save page, but replace the .txt extension in the file name with a .php extension. Also replace the [USERNAME] [PASSWORD] and [DATABASENAME] with your own variables.

–Joab Jackson

And now a word from our sponsor:





HTML: The Difference Between id and class

Thursday, April 30th, 2009

In HTML markup, an id is an attribute you can graft onto a element markup tag, one that identifies that element with a word:

<p id=”sampletest”>This is the sample test</p>

The W3C defines id as the “document-wide unique id.” You can use the name of an id only once, and in a single type of tag, on a Web page. Ryan Fiat writes, “Simply put, an ID is like the sticker that says ‘you are here’ on a mall directory, and there can only ever be one of those.”

Very much like the id, a class can also be grafted onto an element, in a very similar fashion:

<p class=”sampletest”>This is the sample test</p>

The class attribute specifies a classname for an element, says the W3C. You can add your own class to most elements (except base, head, html, meta, param, script, style, and title).

A class can be used to give a name to a particular part of a web page, i.e. <p class=”preamble”>. This can be useful for manipulating that part of the HTML document, through CSS (to stylize that section), or Javascript (to process the content of that section).

Unlike an id, a class can be used across multiple tags. For example, you could have both of these elements in a document:

<h3 class=”legalese”>title</h3>
<div class=”legalese”>content</div>

You could call only one of the classes (i.e. “div.legalese”), or define legalese, and it will apply in both instances. (Click here for working example. View source to see how it works)

ALSO, another cool thing about classes is that more than one can be used in a single element. They are separated by spaces within the quotes:

<p class=”legalese preamble”>content<p>

In this case, if you have CSS stylesheet definitions for both legalese and preamble, then they would both apply to the content above.

In a CSS style sheet, for instance, you could embed these style elements in your document via CSS:

.preamble { font: bold; }
.legalese { font-size: 325%;}

And any content marked with these classes (i.e. <div class=”preamble legalese”>) would be stylized accordingly (Click here for working example. View source to see how it works).


One nice thing you can do with an id that you can’t do with a class: Internal navigation. Anchor linking, it’s called. A browser can use an id as a sort of internal navigation by attributing it to a markup tag of some sort:

<a href=”#content”>This will take you over yonder</a>

<p>hilldale</p>

<p>hilldale</p>

<p>hilldale</p>

<p>hilldale</p>

<p>hilldale</p>

<p id=”content”>Yonder!!</p>

(Click here for working example. View source to see how it works).

–Joab Jackson





XHTML: Upgrading from HTML to XHTML

Saturday, April 25th, 2009

You can think of XHTML as a proper version of HTML. Or strict version, as the W3C like to put it. XHTML is HTML based on XML, with the “<HTML>” tag as the root.

You can’t get away with some of the lazy tricks that browsers overlook with HTML. But the upside, besides being in standards compliance which is always helpful down the road, is that you are preparing your pages for machine readability. Since it is XML, XHTML can be parsed. More on that in later posts.

Surprisingly, it does not take a lot of work to make your HTML documents all XHTML-y, especially if you already practice good markup. Six easy steps is all you’ll need to do. Here is what to do:

1. The page must have a DOCTYPE declaration in the header: This gives a XML parser something to validate against. When I open a new XHTML file in the NetBeans editor, this is the declaration I get, placed in-between the Head tags of the document. So this one will work for all XHTML files:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

2. Code must be well-formed. This simply means that closing tags must be deployed in the exact reverse order from which they were deployed. This is simply proper nesting:

<b><i><u>This is not well formed mark-up.</b></u></i>

<b><i><u>This is properly-formed mark-up.</u></i></b>

3. All elements and attributes must be lower-cased: So <B> is wrong while <b> is correct. HTML itself is not case-sensitive, though XML is.

All attributes must be in quotes: So, now when you add in a link, or any other attribute, you must put it in quotes. There will be no more of this:

<a href=http://www.joabj.com tagert=_blank>Joab;lt;/a>

Instead you must do thusly:

<a href=”http://www.joabj.com” Target=”_blank”>Joab;lt;/a>

Oh, if you put a quote at the beginning of an attribute, be sure to put put the closing quote at the end of the attribute. Seems obvious, but nothing befuddles a browser faster than half a quote.

4. Empty elements must be closed: No more just putting down a <br> and leaving it at that. Now, you write <hr/>. This goes for <hr>, <img> <param> <meta> <input> <col> too!

5. All elements must have end-tags: This seems obvious, except in cases where it is not. This listing tag, for instance. If you put a <li> element at the beginning of a list item, you must now close it with a </li>. Also applies to <body> <html> <option> <p> <head> <tr> and, well, all the other tags too.

6. All attributes must have defined values: I didn’t know you could do attribute without values, but I guess in certain cases you could have.

One example is the “compact” attribute for the underline “<ul>” element. Under plan ole element you could just write “<lt compact>” Now though, you should spell out what it really means, namely ‘<ul compact=”compact”>.’

And believe it or not, that is about all there is to it. Please keep in mind that this is XHTML version 1.0. Version 1.1 of XHTML is stricter still, but for now, most Web developers shouldn’t have to worry about it.

Also, if you want to ensure that a Web page is coded in the correct XHTML form, you can check it at the W3C’s Validation Service.

For learning more on XHTML, check out the W3C’s fine tutorial. Material was also taken from “HTML Programmer’s Reference, 2nd Edition.”

–Joab Jackson

And now, a word from the sponsor:





Project: Roll Your Own URL Shortener

Sunday, April 19th, 2009

Like many other folks, I started using Twitter, and soon thereafter, found the value in URL shorteners. You need to keep each message to 140 characters or less, and if you are passing along the Web link, sometimes that link can take up most of the allotted space.

A URL shortener basically assigns a Web address with as few characters as possible to a longer address, so that when you enter the shorter address into the browser, a server automatically redirects the page requester to the original, longer address.

While there are plenty of free Web sites that offer this service, there are reasons for deploying your own, if you have the gumption and a Web server at your disposal.

For one, how long will these services last? They don’t seem to have business plans. So it keeping your own file of URLs assures that the shortened links won’t be recycled (unless you want them to), and that they’ll be up as long as you want them to.

Another reason for rolling your own is pure vanity (media companies should take note). Like personalized license plates, a shortened URL can say what you want. It can also advertise domain name of the owner.


This is how I built my own URL shortener.

Please note that this code I’ll present has some previous limitations. I would strongly advise not offering it as a public service, at least not without more security measures in place (Filtering what is placed in the Web input, for instance, to prevent cross-site scripting).

I set it up to use as a private service. In other words, place it in some hard-to-find cranny of your Web server, inaccessible from the spidering probes of the search engine. Even as a private service, you should consider putting some authentication code in place.

This is bare-bones code-showing how URL redirect works, on a Unix box, using a Web front-end. It’s so crude, you even have to provide your own shortened URL.

Here is what you need to do:

To set up a URL shortening service, at its most basic, you need to set up three files. I’ll explain each in detail.

One is a Web page that users can use to submit a long link and its short link (to keep things simple for me as a non-programmer, I’ll ask the user to create the short link names, rather than have them automatically generated).

The second file is a text file on the Unix server listing all the short file names, alongside the original ling URL addresses that they will redirect for. It is called the .htaccess file and it is for the Web server, so when the request for the short link comes in, it will redirect the browser to the original (long link).

The third file, a PHP-Web page connects the two above-named pages. So that when a user hits “submit” on the HTML page, the information is sent to the PHP page, which has code to append the Unix file with the new link information.

And that’s about it.

Now the details:
STEP 1: Set up a directory on you Web server for the shorteneing service: For the sake of keeping things tidy, I set up a specific directory on my Web server, just to keep the URL shortening service. It is immediately under the root directory, and is called “A” (“xttp://www.joabj.com/A”). This directory itself has the same permissions as other publicly-accessible directories on the server (drwxr-xr-x). It will contain only the three files needed for this service, plus an obscuring index page so others can’t snoop on the directory’s contents.

STEP2: Set up the .htaccess file: Most of the decent URL shorteners use 301 redirect HTML command. To use 301 redirect, you set up a file, called .htaccess in one of the Web server’s directories. It should be in a directory that the Web server can read and that can be written to by the PHP software.

Setting up an .htaccess file takes a number of steps. I’ve covered them here. Follow these steps and come back when your finished.

The permissions of the .htaccess file should be set so that anyone can write to the file, and read it (-rw-rw-rw-). Security-wise, this sucks. Hiding it in a part of the publicly-accessible though unlinked part of the Web server will keep it from snoopers, though the security-through-obscurity approach is not a good long-term solution. But for the purposes of this instruction, it is the easiest path. You’ve been warned though.

For more information on changing permissions on a Unix box, go here you fool!

STEP 3: Set up the landing HTML page: So the idea is to set up a basic html page that you can bookmark and go to when you want to shorten a URL. It should have a short and easy-to-remember title so you can get to it when you are on the road. But you should NOT link to it from any other page on your site that is crawled by human or search engine spider. Warning: Security through obscurity again.

Anyway, at its most basic, this should page should include three things. It should have two fields for the user to enter the original URL and a short URL that they make up. The page should also have a button that can be pushed to kick off the whole operation, once the values are filled in.

This would be the active code for such a page:

<FORM ACTION=”Shorten.php” METHOD=”get”>
The link to be shorted: <INPUT TYPE=”Text” NAME=”Link” />
Shorty nickname: <INPUT TYPE=”Text” NAME=”Shorty” />
<INPUT TYPE=SUBMIT VALUE=”GO” />
</FORM>

To see this code in an actual working html page, go here. To make it operational, change the suffix of the file name from .txt to .html .

O.k., some explanation of what is going on here. Using the W3C standards for creating Web forms, we’ve given the user two fields to fill in. The content filled into the “Link” field will be assigned to the variable “Link” and the content filled into the short field will be assigned to the variable “Shorty.”

Note that we are asking the user to fill the original link address into the “Link” field and the shortened link name in the “Shorty” field. Also on the page is the code:

FORM ACTION=”Shorten.php” METHOD=”get”

and

INPUT TYPE=SUBMIT VALUE=”GO”

This basically instructs the browser to fetch the Shorten.php page and feed it the contents of the “Link” and “Shorty” variables, when the SUBMIT button is pushed.

Next we create the Shorten.php page.

STEP 4: Create the PHP page: next you have to create the page that the HTML page is sending its information to. And this page will format and insert the data into the .htaccess page in such a way that it can be read by the Web server, capiche?

Here is some background material on getting started on PHP. Here is a bit on how to pass information from Web forms to a PHP page. And here are some pages on how a PHP can open a disk file and append data to that text file on a Web. Familiarize yourself with all of these pages, please. Mash them together you’d get code like this:

$Link = $_GET["Link"];
$Shorty = $_GET["Shorty"];

$Preamble = “redirect 301 “;
$Space = ” “;
$Directory = “/A/”;
$NewLine = “n”;
$All = $Preamble.$Directory.$Shorty.$Space.$Link.$NewLine;
$Name = “.htaccess”;
$Handle = fopen($Name, ‘a’);
fwrite($Handle, $All);
fclose($Handle);

To see this code in an actual working html page, go here. To make it operational, change the suffix of the file name from .txt to .php .

So what is going here? What we need to do is take the information given to this page from the HTML page (“$Shorty = $_GET["Shorty"]” and “$Shorty = $_GET["Shorty"];”) and format it in the appropriate way for an .htaccess file (“redirect 301 [new short address] [original address]).

To do this, PHP has to make a one-line string. You can concatenate multiple PHP variables through the “.” symbol. So we create variables for the additional formatting we have to do. “$Preamble” is the first statement needed on the .htaccess line (“redirect 301″). “$Directory” is the directory (in this case “A”) the new address will be appear to be in (so the user doesn’t have to type it in, as a prefix). “$Space” adds the space needed between the two addresses, and “$NewLine” tells Unix to start a new line after this string is entered.

Finally, $All assembles all these variables together in the order of a proper 301 redirect request.

The page then opens the .htaccess file, appends on the new request, and closes the file. After this file is appended, when the short link is typed into the browser, as part of the full file-name (i.e. http://www.joabj.com/A/0″), your Web server should automatically send the viewer to the page you indicated.

That’s it. Ezy pezy, yes?


Again, this is just the bare bones code, to show you how it works.

There are some easy things you can do to pretty up the service, by adding to the HTML portion of these pages: You need to see up error messages, to tell the user when they fill in the boxes incorrectly. You may want to place a Twitter submission box on the results page, so you can submit your newly-christened short link directly to the microblogging service. Or you could post a link to try the new short URL. Or show the URL to the last link, so you know where you left off. You could even insert a generator of short addresses, taking the manual naming of the address out of the process.

Heck, this code doesn’t even offer the ability to tell the user that the short link submitted has already been used!

A word on naming the short links: As you can tell, the user has to supply the own short links, which become live as soon as they are entered. While this offers a way to way to customize Web addresses (“http://www.yourname.com/ThisStorySucks.html”), if you want to make them as short as possible, you should use as few letters as possible. And long-term use requires a few heuristics, as they say.

Myself, I am starting by running through all the 1-character options (0-9 a-z, for a total of 36 links) in order (“0″ then “1″ then “2″ and so on). When they are exhausted, I’ll go through all the 2-character options (“01″ then “02″ and so on). This will provide a total of 1296 links (36*36), and then, all the three-character options (36*36*36 = 46,656 links), and so on.

In my lifetime, I probably won’t use up all three-letter URL combinations. So my URLs will, at the most, run only 20 characters in length (i.e. “http://joabj.com/z99″), thanks to my relatively short domain name. This is the exact length as the shortened links that Bit.Ly current offers. Yay! Brevity! –Joab Jackson

If you found this useful, consider buying something from these people:





Automatically Reposting Delicious Tags to Identica and Twitter

Saturday, April 18th, 2009

I wanted the bookmarks that I added on to my Delicious account to also be automatically reposted on to my Identica and Twitter accounts. This is how I learned to do that.

I didn’t work up the solution myself: This chap figured it out. But I’ll recap the basics here, because I’ll forget how to do it, and forget where to find the link.

1. Grab the RSS Feed from your Delicious account: Look at the bottom of your Delicious homepage [http://www.delicio.us/[YOURACCOUNTNAME], find the “RSS Feeds” link. Click on that. Copy the resulting address from the browser.

2. Sign up for an account on Twitterfeed. Once signed in, you will be given an opportunity to create a new feed for either the Twitter, Identica, Ping or Hellotxt microblogging serves. After authenticating though your microblogging service of choice, paste your Delicious Feed link.

And that is basically it.

When a new Delicious bookmark is added onto the RSS feed, Twitterfeed picks it up next time it checks the the feed, and reposts it to the microblogging service of your choice. Specifically, it uses the information in the Delicious “Title” field and the link. It automatically deploys a link shortening service for long URLs.

It doesn’t post links prior to you turning on the feed. It checks for new entries based on the date or on the GUID (the incremental numbering of new entries).

In the settings, you can prefix the reposts with a brief tag, up to 20 characters. For instance, I used “Bookmark:” Note, however, we only have 140 characters to work with. So given that the small URL will about 30 characters, and “Bookmark:” is itself 9 characters, I’ll need to keep the Delicious “Title” field to 110 characters or less.

You can adjust how often you want Twitterfeed to check for updates. It doesn’t seem to pull Delicious bookmarks entered prior to signing up.

Note: For Identica, you have to choose Laconica on the Twitterfeed range of microblogging site options, as Identica is one implementation of Laconica.

–Joab Jackson

Oh, here, support capitalism: