Archive for the ‘PHP’ Category

Fun with PHP data types

Thursday, February 2nd, 2012

All data stored by PHP is put into one of eight different types of buckets, technically called data types. The data type determines what operations can be carried out on that piece of data.

Four of the data types are scalar–they support only a single value. These are integer (a whole number), float (a number with a decimal point), string (a sequence of symbols) and boolean (0 or 1).

PHP also has two compound data types. One is an array, or a bounded collection of multiple values. The other is an object, or a collection of data that also contains properties and methods. Finally, PHP has two special data types. One is a resource, which is a reference to some external data source. The other, null, has only one value, null.

PHP is a loosely typed language, meaning the variables do not need to have their data types defined before they are used. If you code $sample = 4.5; then PHP will assume the the $sample variable is a floating point data type. It is totally up to you to make sure that you pass the correct data type to any operation (i.e. don’t ask PHP to multiply two text strings).

That said, PHP offers some tools to help get a handle on all your loose data types. PHP’s gettype() function can let you know what type of data type the provided variable is, i.e. gettype( $sample ). You can also change a data type with PHP settype(), i.e. settype ( $sample, “integer”) will return the value of 4. PHP tries to preserve as much of the original value as possible during the conversion process.

Finally, you can set a variable’s type even before it is assigned a value. This is called type casting. Here you place the name of the data type, in parenthesis, before the name of the variable. So “(float) $sample = 4.5″ will ensure that the $sample variable will be a floating point data type.

From the book




All mistakes are my own, however…-Joab Jackson





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





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:





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:





PHP: Writing to a disk file

Friday, April 10th, 2009

Now, that we have learned how to create and open a disk file with PHP, now it’s time to write something to it.

Again referring to this tutorial, we insert two lines into the previous set of code:

$Name = “FileToAddStuffTo.txt”;
$Handle = fopen($Name, ‘w’);

$TextToAdd = “HelloWorld\n”;
fwrite($Handle, $TextToAdd);

fclose($Handle);

The new part is here:

$TextToAdd = “HelloWorld\n”;
fwrite($Handle, $TextToAdd);

The PHP “fwrite” command is key here. With it, you are instructing PHP to 1: open the file “FileToAddStuffTo.txt” (which has been assigned to the variable $Name, and is opened by calling the variable $Handle), and 2: write into the file the contents of variable $TextToAdd).

(For the full working code, click here. To get the code to run in a PHP environment, change the “txt” suffix to “php”.)


Running the above code, you will just overwrite what was previously there. Appending a file requires an different flag. Instead of this:

$Handle = fopen($Name, ‘w’);

you’d write this:

$Handle = fopen($Name, ‘a’);

Also, be sure to add a new line break at the end of the string (“\n”):

$TextToAdd = “HelloWorld\n”;

For this sample, I used PHP 5.2.4

–Joab Jackson

And now, a brief word on why you should buy something:





PHP: Creating a file on disk

Tuesday, April 7th, 2009

The PHP command for both creating and opening a file is “fopen” … Like typical Unix file programs, if it doesn’t see a file called “x” it will create a file called x.

How to create a disk file using PHP? This tutorial advises us to add these three lines to a PHP skeleton file:

$Name = “ThisFileWasCreatedByPHP.txt”;
$Handle = fopen($Name, ‘w’);
fclose($Handle);

(For the full working code, click here. To get the code to run in a PHP environment, change the “txt” suffix to “php”.)

All you do to execute this action of creating a file is to call up this page with a browser. The page should have a suffix of .php (i.e. “01-CreateFile.txt.php”) and you should have PHP working on your server.

NOTE: For this to work, the administrator must give “all” user permissions for reading, writing and executing programs for the directory this file is in. Sucks, I know. In other words, don’t use this in a directory with any valuable info (at the command line, type “chmod a+rwx [Name of Directory]“)

In the above code, the tutorial tutors us, the first line creates a name of the file (“ThisFileWasCreatedByPHP.txt”") and assigns it to a variable ($Name).

The second line instructs PHP to open and write (“w”) to a file, or if one doesn’t exist, create that file, with the “fopen” command, giving it the name of variable $Name (which in this case, happens to be “ThatThatWasCreatedByPHP.txt”). The third line closes the file.

For this sample, I used PHP 5.2.4

–Joab Jackson

And now, a brief word on why you should buy something:





PHP: Installing PHP on Ubuntu

Saturday, February 21st, 2009

PHP works as a module on the Apache Web server….

First download and install the PHP package, from root:

#apt-get install php5 libapache2-mod-php5

When PHP is installed, it is run by default by Apache. You need to restart the Apache module for the chnages to take effect:

#/etc/init.d/apache2 restart

To test to see if PHP is running,, save a sample script in the root directory (var/www) under a file with a php extension (i.e phpinfo.php):

<?php
print_r (phpinfo());
?>

Then, open the page in a browser (http://hopstname/phpinfo.php). You should get a page with PHP operational info.

OTHER THINGS TO CONSIDER:

Also, if you PHP in conjunction with MySQL, you need to install the PHP MySql package (if it wasn’t installed during the OS installation):

#apt-get install php5-mysql

PHP also has a terminal client. To install that, enter this in the command line:

#apt-get install php5-cli

From the Ubuntu server guide.

–Joab Jackson





PHP: Getting started

Saturday, January 3rd, 2009

(In order to insert data and draw data from my MySQL database, I’ll use PHP….)

PHP is a scripting language that is run by the server.

It is set off by:

<?php [insert PHP code here] ?>

A string can be added through the “echo” command, along with what you want to appear on the screen within quotes:

<?php echo( “Hullo <b>World</b>” ) ?>

You can add HTML into the statement, which gets parsed by the server:

<?php echo( “Hullo World” ) ?>

A variable within PHP is assigned through the dollar sign:
$test = “Frank”;

Here is an example:

<?php $test = “Hello”; echo ($test); ?>

Note: PHP is loosely-typed, meaning you don’t have to specify what kind of variable you enter.

Here is an example combing and inline text:

<?php $test = “Hello”; echo ($test . ” world”) ?>

will return:

Hello world

This is implanted within the body of the page, which has a .php suffix

(For the full working code, click here. To get the code to run in a PHP environment, change the “txt” suffix to “php”.)

(Taken from this tutorial, “Building a Database-Driven Web Site Using PHP and MySQL, Part 3: Getting Started with PHP.”)

–Joab Jackson