Mathematical Equations with PHP

•22 Jul 2008 • Leave a Comment

Using PHP Mathematical Functions

Tutorial Level: Beginner

One of the great aspects of PHP programming is that the language includes numerous functions for mathematic equations and problem solving. A complete list of these mathematic functions can be found in the PHP Manual, but explaining every function would be impractical and would only bore those trying to learn PHP. Instead, we going to see some of the most common mathematic equations and functions, such as adding, subtracting, multiplying, dividing, greater-than or less-than, rounding, absolute value and others. While all these may seem very simple, many times PHP involves a great deal of numbers, and these numbers can grow and become large equations, for example: counting the number of seconds since a date and time, and knowing how to minipulate these numbers can be a great benifit to any programmer.

Simple Math

First, let’s start out with the basics: addition, subtraction, multiplication and division. These are the basic functions that will make up larger equations and the ones we will build on as we get into more advanced math. For examples, we will create a variable for the equation, and then print it through the echo function. Let’s start with addition:

<?
$add = 1 + 1;
echo(“$add”);
?>

This example would print the value 2 on the webpage when added to a PHP script. Next, we can try the subtraction function. This function works the same as the addition function, but uses a minus (-) rather than a plus (+), just as in normal grammar school math. For example:

<?
$sub = (5 – 2);
echo(“$sub”);
?>

This equation would produce a value of 3 on the server. Now that we know how to do the simple stuff, we can create more complex equations by using parantheses in the equation. This equation combines the use of addition and multiplication, along with the use of parantheses to follow order of operations:

<?
$par = (11 + 4) * 4;
echo(“$par”);
?>

With the use of multiplication (*), this equation would produce a value of 60 because 11 + 4 = 15, then 15 * 4 = 60. Rather than breaking this into a two step process, the same way the problem can be explained, using parentheses can save space and make this a one step process. Just be careful how many levels of brackets you use in an equation, because it can become cluttered and confusing. For more complex equations, it is okay to only use a small amount of brackets to better see the problem. The last function is division. For example:

<?
$div = 44 / 11;
echo(“$div”);
?>

The division tag (/) is the same as that on a scientific caluculator. Remember when doing PHP math that the signs are scientific, and not simple (IE: multiplication sign is not x, but *). With this problem above, we would get the value 4, because 44 divided by 11 = 4. While it may seem like learning 2nd grade math all over again, it is important to understand the basics before moving on.

Greater or Less-Than

While it may not seem to be a big part in programming, the greater-than and less-than functions are very useful. Most of the time, these functions are used in conjunction with the IF or ELSE statements. For example, if a number is greater-than or equal to 0, than it is positive, else, if the number is less-than or equal to -1, than the number is negative, and will need to be multiplied by (-1) to become positive. As well as using the greater-than ( > ) and less-than ( < ) signs, the function for greater-than or equal (>=) or less-than or equal (<=) can also be use. The following is the PHP version of the example stated in this paragraph…

<?
if($num >= 0)
{
echo(“$num is positive”);
}
elseif($num <= -1)
{
$pos = $num * -1;
echo(“$pos is positive because $num (times) -1 (equals) a positive number”);
}
?>

If a number is plugged into the equation ($num is given a value as a number), than the script will see if the number is positive or negative, and if it is negative, than it will be multiplied by (-1) to become positive. This is the same prinicple behind absolute value, which we will explore further in the tutorial. As you can see in the example above, the simple math functions are essential to equations in PHP.

Rounding Numbers

Rounding is another important part of PHP programming, and can play a big part in Content Management Systems and pagination, which is a script that divides long sets of information into separate, and even pages. There are three types of rounding we will work with: standard rounding, rounding up and rounding down. All these methods are used with a decimal and round to an integer. Standard rounding is a method of rounding used in most math, where if a number is greater-than or equal to 5, than the number is rounded up, but if the number is less than 5, the number is rounded down. The function is called round() for this method. The following is an example of this function…

<?
$num = 6.5;
$num2 = 7.3;
$round = round($num);
$round2 = round($num2);
echo(“Rounded number 1: $round | Rounded number 2: $round2″);
?>

This example would output 7 for both $round1 and $round2 because 6.5 would round up, and 7.3 would round down. You can also change the number of decimal points to round out to. To do this, simply add a comma and a number after the number being rounded. For example…

<?
$num = 6.3567;
$round = round($num, 3);
echo(“Rounded number: $round”);
?>

Notice the 3 after the $num variable in the round function. This means that the number will be rounded out to 3 decimal places (thousandths place). In this case, the number that would be produced is 6.357. The last 7 would round up, and then the rounding would stop because it is set to go to the 3rd decimal place. Now that we have a grasp on the standard rounding method, let’s move onto the rounding up method. The function for rounding up is the the ceil(). Here is an example of this function…

<?
$num = 6.2;
$round = ceil($num);
echo(“Rounded number: $round”);
?>

This example would output 7 because 6.3 would be rounded up. The last method of rounding is the rounding down function. This function is called floor(). Here is an example of this function…

<?
$num = 4.9999;
$round = floor($num);
echo(“Rounded number: $round”);
?>

This example would produce a value of 4 because the number 4.9999 would be forced to round down, and thus become 4. While it may seem like an unimportant math function, rounding can be very useful when an interger is needed after a problem such as division. As stated before, pagination uses this because pages must in integers, and it would be incorrect to have a page number of 4.956, rather than 5 for example.

Absolute Value

This math function is also another useful PHP function, and can also be used in things such pagination. Because it would be incorrect to have a negative page number (IE: -2, -1, 0, 1, 2, 3 rather than 1, 2, 3, 4…), removing negative numbers for the equation would make the end result be positive. It is actually very simple to obtain the obsolute value of a number. The function is called abs(). The following is an example of this function…

<?
$num = -3;
$abs = abs($num);
echo(“The absolute value of $num is $abs”);
?>

This would produce the value 3, rather than -3. Although this tutorial only covers a few of the many mathematic functions, there are many more functions that can be used to minipulate numbers and finding the value of equations. The PHP Manual Mathematics Page is a useful resource. I hope this makes the task of programming in PHP easier for you and more fun.

Dynamically Loading Page Content

•22 Jul 2008 • Leave a Comment

Loading only Template Content Once

Tutorial Level: Intermediate

One of the largest, and most obvious reason that templates take such a long time to load is that many of the templates used on websites have many large and detailed images that the server must load each time a new page is visited. Logically, to cut down on the amount of time required for a page load, we would need to allow the template to load only once, when a user first visits the page, rather than refresh every time a new page loads. Another advantage of this method is that if a change needs to be made to the template, only one file has to be editted, rather than every page on the website. Although this may sound confusing at first, as we go through the steps of creating this dynamic content, the purpose and effects will become more clear and your website will become more practical as well.

Dividing up the Template

This method of page loading is based around the idea of separating the top part of the template (above where the text of the page is located) and the bottom of the template (directly below where the page text is located), and then calling the page content from a separate file to be displayed in between the two parts. While most templates are much longer than the example below, most also share the same principle of having a top half, a location for page content and a bottom half. Let’s take for instance the following example of a simple template below…

<html>
<head>
<title>A simple Template</title>
</head>
<body>
<center>
<div id=”pagecontent” style=”text-align: center; width: 200px; font-size: 12px;”>
<!– page content –>
This is a simple template used to show the principles of how an HTML template is setup. It includes a header part of the template: the coding above this text, and a footer section: the coding below this text.
</div>
</center>
</body>
</html>

As shown above, the coding above the comment: <!– page content –> is considered the Header of the template. The coding below the the text: …the coding below this text… is considered the Footer. This will be very important when we break the template up into different sections. Now that we know logically how the template is setup, and we have planned out how to divide the template into separate parts, it is time to create the different files.

Please keep in mind that when doing these steps, you can still use your own template, but for the purposes of giving a visual example, the template above will be used in this tutorial. Now let’s get started! Because this can become confusing if mixed with other files, I would suggest creating a new folder. For the sake of the tutorial, let’s call that folder mytemplate. Using the template above, the following files (using the names given) should be created with the content quoted below:

header.php

<html>
<head>
<title>A simple Template</title>
</head>
<body>
<center>
<div id=”pagecontent” style=”text-align: center; width: 200px; font-size: 12px;”>

footer.php

</div>
</center>
</body>
</html>

With the creation of these two files, our new folder (mytemplate), should have the following files located in it (along the way, we will check to make sure that you have all the files in your template folder, to ensure that a step was no skipped by accident)…

  • header.php
  • footer.php

The next step is to create a folder for the pages themselves to go in. To keep is simple, we will call this folder pages (original, I know). To make a page the default page to load, we need to call it idx.php, signifying that it is the index file. Below is what should be contained in that file (NOTE: this file should be saved inside the pages folder)…

idx.php

<!– page content –>
This is a simple template used to show the principles of how an HTML template is setup. It includes a header part of the template: the coding above this text, and a footer section: the coding below this text.

Now that we have created the header and footer files, the pages folder, and added a page (idx.php) into that folder, our folder for the template should look like the following (in tree format)…

  • pages (folder)
    • idx.php
  • header.php
  • footer.php

The last step is to create a file that will tie this system together. The index.php (below) file is used to call the header file, then the page content from the pages folder, and lastly the footer file. By doing this, we create the exact same template as the simple HTML one in the beginning, but now the header and footer files only load when the user first views the page (manually hitting the refresh button in the browser may also refresh the entire template). This is what the index.php file, saved in the normal directory (mytemplate) should look like (this file should be used both for this template and any custom templates, such as a template created by you)…

index.php

<?
include (“header.php”);
//Calls header file
$act = $_GET[‘act’];  //Delcares a variable for the URL
if(!isset($_GET[‘act’]))
{
$act = “idx”;
//If no page is specified, than the idx page is used
}
$page = ‘pages/’. $act .’.php'; //Variable for the filename of the page
if($act)
{
if(!file_exists($page))
{
@include(“pages/404.php”);
//Loads the 404 Error page
}
else
{
@include($page);
//Loads the content of the page
}
}
include(“footer.php”);
//Calls the footer file
?>

Now that we have have created this new file, the directory for the template should have the following files in it…

  • pages (folder)
    • idx.php
  • header.php
  • footer.php
  • index.php

Creating New Pages

With this method of dynamic page loading, creating new pages is also simplified. To create a new page now, you only have to create a file with page content (text and images) and save it under the pages folder, rather add the entire template into each file, just like in the idx.php file. Note that all the files in the pages folder must have the extension .php or the index.php will not recognize them as pages. There is also no extra scripting required, simply drop the file into the folder, and upload it to the server, and the index.php file will automatically recognize it. To view the new page, use the following URL, replacing mywebsite.com with the URL of your website, and page with the name of your page (NOTE: when using the URL, do not add the .php extension to the file)…

http://mywebsite.com/?act=page

By adding the ?act= peripheral to the URL, the server fetches the page and knows to add the .php extension to find the page in the pages folder. That is why you don’t have to add the .php extension, because it is understood when fetching the file.

A Custom Error Page

Another benifit of this method is that you can create a custom error page to be displayed when a page cannot be found in the pages folder. To create this page, simply create a file with text and/or images on it, name it 404.php and place it in the pages folder. When you upload it to the server, the index.php file will call it if there is an error calling a page. If you don’t have a 404.php file, then the server will issue the normal 404 error. The following is an example of an error page…

404.php

<center>
<strong>404 Error!</strong>
<br /><br />
Sorry, there was an error loading the following page:
<br /><br />
<?
$act = $_GET[‘act’];
echo(“” . $act . “.php”);
?>
<br /><br />
Please be sure that this page exists before retrying.
<br /><br />
<a href=”javascript:history.go(0);”>Refresh</a> | <a href=”javascript:history.go(-1);”>Back</a>
</center>

This above example will tell the user that there was a 404 Error (in bold) and then tell them which page they were trying access when the error occurred. It also includes Javascript links to visit the previous page (back) or to refresh the current page. Although very short and simple, it contains some dynamic features that can help the user diagnose the problem and direct him or her to the currect location.

Credit & Recognition

I’d like to mention that the index.php file used in this tutorial was not created from the ground up by me, and I do not take credit for its use or features. The process that makes up this tutorial was also taught to me from the same person, and I have used it for the last few years as a standard on all webpages I create. I am only passing it on after getting comfortable using it and have put it to good use. I was given a basic version of the script, and over the past few years it has been modified to fit the various uses it was applied to. If you have any questions with this file or tutorial in general, I will be happy to help: simply leave a comment below. I would just like to state that I am not the creator of this script, and give recognition to those that it is due. I hope you can also put this script to good use, and most important of all: enjoy!

Listening to Restricted Formats

•21 Jul 2008 • 1 Comment

Listening to Restricted Music Formats

Tutorial Level: Beginner

When listening to music, getting a notice that specific songs cannot be listened to due to restricted formats can become frustrating very quickly. The good news is that OpenSUSE has a package that un-restricts many of the most popular music formats. Although there is not much to installing this package, there are two options to select, depending on which Desktop Environment you use. There is a package for Gnome and another for KDE. Below are links for the 1-Click Installers for both the Gnome and KDE version of the Restricted Multimedia Formats package. Note that these packages are for version 11.0 of OpenSUSE.

Gnome Desktops

KDE Desktops

Due to the nature of the 1-Click Installer, the installation process for this package is the easiest part. Simply follow step-by-step what YaST2 suggests for your and provide the information needed, and the package installer will do the rest. Once you have completed the installation, you will be able to listen to formats such as MP3, MPEG-4 and many others! Although a very simple tutorial, this package can make your music experience in OpenSUSE much smoother and more enjoyable!

Transferring Music to Banshee

•21 Jul 2008 • Leave a Comment

Transferring Songs from iTunes to Banshee

Tutorial Level: Beginner

With the growing popularity of the iPod and iPhone, a large majority of Windows users use Apple’s iTunes as their dedicated media player. One of the hard parts of switching from Windows to OpenSUSE is the transfer of data. To solve this problem with music and videos, Gnome’s Banshee player has adopted a very functional and useful tool to import music. While many media players can only import a single song at a time, Banshee allows you to transfer folders or even your entire music collection with just a few simple clicks. So now that we know about the feature to transfer songs, let’s put it to good use.

Transferring your Music Library

Because iTunes organizes it’s library into a single folder, we are able to transfer this entire folder (what we will refer to as the Library) into Banshee with a single import. Most of the time, the iTunes Library can be found in My Music in your Windows Documents, or it may be the My Music folder itself that contains the songs. If you are unsure of where your music for iTunes in located, open iTunes, and go to the Edit tab, and then Preferences. Select the Advanced tab on the top of the new window, and the General section will be selected by default. The first item on this window will be the iTunes Music folder location: this will show you where the current library for your music is located.

Now that we know the location of the folder, we have to import the library. Boot back into OpenSUSE if you are currently in Windows and open your Banshee Media player. Click the Media tab on the top-left of the Banshee player and select Import Media… (or press Ctrl+I). When the prompt appears, click the dropdown menu and select Local Folder. Next, press the Import Media Source button. This will open a window for you to select the location of your media source: in our case, the iTunes Library.

First, we need to get into the Windows folder. To do this, click the File System link in the left column of the locator. Once in the file system, scroll down to the bottom and select: windows. Once in this folder, double-click on the C directory. Now we are in the Windows directory. If you know the specific location of your iTunes Library, navigate to this location; if your iTunes Library is the My Music folder, use the following navigation to get to the folder (replacing Your name with your Windows username)…

Documents and Settings -> Your name -> My Documents

In this folder, you will find the My Music folder. Click this folder, but do not double-click, or it will explore the folder. Once you have clicked the folder once (same goes for those who have their library in a separate location: click the folder once), press the Open button on the bottom-right of the locator window. Now the music files will begin to upload. You can see the progress in the bottom-left of Banshee. Cover art will also be downloaded to match the albums in your library. If some of the cover artwork does not automatically download, press the Tools tab, then mouseover the Cover Art option and then select Download Cover Art.

Now that you have your music imported to Banshee, there’s only one thing left to do: listen to it! I hope this helps make the process of switching from Windows to OpenSUSE much easier, and much more fun. Note that some of the music formats may be restricted, and may require a special package to be installed to be able to listen to these restricted formats, for more help on that, refer to the Listening to Restricted Formats tutorial. Feel free to post any comments, concerns or suggestions below, and most importantly: enjoy!

Zypper Library Update

•15 Jul 2008 • Leave a Comment

Missing Library Files for Zypper

Severity: Major

The following error is very important to steer-clear of because the only alternative I have found that will solve this problem once it occurs is to completely reinstall OpenSUSE 11.0. The error began when I was alerted that updates were available for installation and allowed my system to install the patches. The first error I received was a list of dependency errors (as follows)…

nothing provides libexiv2.so.4 needed by libkexiv2-3-0.1.7-15.i586
nothing provides libexiv2.so.4 needed by ufraw-0.13-52.i586
nothing provides libexiv2.so.4 needed by ufraw-gimp-0.13-52.i586
nothing provides yast2 >= 2.17.7 needed by yast2-installation-2.17.0-2.noarch
zvbi-0.2.30-3.i586 requires libzvbi.so.0, but this requirement cannot be provided
gconf2-branding-openSUSE-2.20-60.noarch requires desktop-data-openSUSE = 11.0, but this requirement cannot be provided
libtunepimp5-mp4-0.5.3-100.pm.9.i586 requires libtunepimp5 = 0.5.3-100.pm.9, but this requirement cannot be provided
zypper-0.11.9-0.1.i586 requires libzypp.so.424, but this requirement cannot be provided

The problem was compounded when I went to install a package in YaST Package Manager. I received the following error as I tried to install an unrelated package: click here. After some time of letting this problem go, I made the decision to downgrade Zypper. This worsened the problem as I now could not open any YaST Modules, such as Package Manager and LAN Connections. I got the following xmessage error…

Error while creating client module sw_single

The update for Zypper also had the dependency…

zypper-0.11.9-0.1.i586 requires libzypp.so.424, but this requirement cannot be provided

I downloaded the source files for libzypp.so.424 and moved them into the /usr/lib directory. This did not solve the problem. I was instructed to issue the command zypper sl in a terminal window to give a readout of the current repositories installed. After reinstalling OpenSUSE 11.0 (the second time, because I ran into this problem once, then reinstalled, and had it again, and reinstalled again), it was found that the error was caused by repository errors.

Solution

The error above is a known OpenSUSE problem, but is only caused by manually installing specific repositories. It was found that if Factory repositories, rather than 11.0 repositories, were added to YaST/Zypper, a dependency error would occur because the Factory repositories were not the same version as that of the operation system (OpenSUSE 11.0). The best way to keep this error from happening is to be sure that the repositories you add should be for version 11.0 (or your version of OpenSUSE) and not the Factory or another version of the repository.

The OpenSUSE 11.0 Installation Tutorial

•27 Jun 2008 • Leave a Comment

After much work and effort, the OpenSUSE 11.0 Installation Tutorial page is now available for use. It is a bit lengthy, but includes all the basic aspects of installing OpenSUSE 11.0 on your system. This tutorial includes step-by-step screenshots to aid visually in the process. It also has detailed explaination of each step of installing the operating system and configuration the basic components of OpenSUSE 11.0, such as repositories and video drivers. It will take you all the way from creating the DVD to working with your new desktop. Hope you enjoy!

Compling Wine from Binary Files

•23 Jun 2008 • Leave a Comment

Compiling Wine from Binary Files

Tutorial Level: Intermediate

Although using YaST package manager may be a very simple and easy way to install Wine on your OpenSUSE system, sometimes different games or programs will require a patches or to have Wine compiled from scratch. Compiling Wine from binary files may sound like a long process, but it is actually quite simple. In this tutorial, we’ll patch a binary file for Wine, compile and then install Wine. If you wish only to install a clean binary file without patching it, simple skip over the patching section. Now that we know why we should compile from scratch, let’s get started.

Preparations

Although compiling Wine is a few step process, it will require your OpenSUSE system to have some packages installed. These packages will do the work of preparing your binary files for the installation and installing Wine itself. There are specific packages that this installation requires, but to save time looking for each individual file and worrying about the dependencies of each, we are going to install an intire pattern through YaST. First, open YaST Software Management, and once the reopsitories load, set the grouping (below the left column) from the default, which may be Groups, to Patterns. Now scroll down in the left column to Development. There, click the Base Development pattern, and click the Install All button. Now, hit the Apply button to the right of the window, and wait for the packages to install. Once all the packages have installed, decline to install more.

Downloading and Extracting the Binary

Now that we are ready to compile the files, let’s put them on your system. The Wine website will have a link on the top right of the page of their latest release version. Click this link (which should look like Wine-1.0, only with the most recent version of the files). Now you will be directed to the download page. On this page, there should be links with the extension of .tar.bz2. Click one of the links to download the file to your system. Please remember where this file is being downloaded to. Once you have finished downloading the file, we are ready to open the package.

To open the package, open a new terminal window and login as SuperUser (su). Now, use the cd command to open the directory where you downloaded the folder. Next, we need to extract the files into a folder. To do this, type the following command into the terminal, replacing filename with the name of the file you have downloaded…

tar xvf filename

Now you should see a list of files being extracted and placed into a new folder (which will be named the same as the .tar.bz2 package, only without the extension). You can check if such a folder was created by typing dir in the terminal. This will return a list of all the files in the current directory. Now just check to see if the new folder is there.

Patching the Binary

If you want to patch the files, here is the time to do it. To do this, download the patch for Wine you wish to use. Remember where you download this file, the location is very important. Now we need to use the cp command to copy the patch into the folder you just created. To do this, run the following command, replacing /patch/location.diff and folder/location with the location of the patch you downloaded and the location of the folder you created, respectively…

cp /patch/location.diff folder/location

Note that there is only one space that seperates the location of the patch from the location of the folder. Now that the patch has been copied into the folder, we must run the patch command to initiate the patch. To do this, use the cd command to place yourself inside the new folder, and then run the following command, replacing patchname with the name of the patch you downloaded…

patch -p1 < patchname

This will now enact the patch, replacing or changing what the patch has to. This should only take a matter of moments, although may take longer if the patch is larger.

Compiling Wine

This part may take some time, but requires very little on your part. To start the compiling process, use the cd./configure command to place yourself inside the new folder you have created (if you have not already). Now, the command we need to run is…

./configure

Now you should see a long list of items being checked. Because we install the development packages earlier, you should not encounter any problems. If you do, the terminal will output an error message, most of the time giving the name of the package missing. Open software management, and search for this package and type the ./configure command again in the terminal.

Once you have completed the configuration, it is now time to run the make command. For this, we do not need to specify any location or parameters, just simply type make into the terminal window and hit the enter button; the rest the terminal will do. This part may take some time, so patiences will pay off.

Once the process is finally complete, run make install. This will install the configured binaries, and thus install Wine. This part may also take some time, but is much quicker than the previous command. Although not required, you can also run the make clean command to leave you with a clean installation, rather than having files left over from the compiling and installation steps.

To make sure everything has gone according to plan, test that Wine was installed and works properly. You can simply type wine –version to find the current version of Wine that you are running. If the version matches the one you installed, then you are good-to-go.

Keep in mind that the process of compiling is not only used for Wine, but for many open source applications and programs. That is one of the reasons we installed the entire development pattern in the beginning of the tutorial, because you will most likely see or use these programs again. It is a good idea to keep these packages installed on your system, in case you need them in the future. Always be sure to check the Wine Application Database to see if a program requires patching or other outside sources to install the program.

 
Follow

Get every new post delivered to your Inbox.