Category Archives: Coding

Simple PHP Page Protector

A couple of years ago I posted a way to protect a PHP page from access on the internet in an easy way.
I've spent around 15 minutes producing what I feel is a better version of the same script at the original post.
In order for it to work, you'll need a MD5 string, which you can get using the below box, just enter you password and then replace 6121904d3138741fb744fba85c276606 in the code, its quite self-explanatory.

<?php
session_start();
$_userpassword = "6121904d3138741fb744fba85c276606";
$_username = "pass";
/*DO NOT EDIT*/
if      ($_POST['pageprotector'])
        {
        if      (md5($_POST['pageprotectorpass']) == $_userpassword && $_POST['pageprotectoruser'] == $_username)
                {
                $_SESSION['bG9nZ2VkaW4p=']=$_userpassword; $_SESSION['bG9nZ2VkaW4u=']=$_username; header('Location:'.$_SERVER['PHP_SELF']);
                }
        else
                header('Location:'.$_SERVER['PHP_SELF'].'?wrongpass=1');
        }
if      ($_GET['pageprotectlogout'] == "1")
        {
        unset($_SESSION['bG9nZ2VkaW4p=']);unset($_SESSION['bG9nZ2VkaW4u=']);header('Location:'.$_SERVER['PHP_SELF']);
        }
if      ($_SESSION['bG9nZ2VkaW4p='] != $_userpassword && $_SESSION['bG9nZ2VkaW4u='] != $_username)
        {
        if      ($_GET['wrongpass'] == "1") echo "Wrong password";?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Username: <input name="pageprotectoruser" type="text" /> Password: <input name="pageprotectorpass" type="text" /><input name="pageprotector" type="submit" value="Login">
</form><?php
        exit;
        }
/*DO NOT EDIT ABOVE*/
?>
 


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Copy to clipboard using javascript

In a current project i am working on, I need to be able to copy some posted content to my clipboard. Well I looked for a solution so I thought I’d show you….

<span style="#800000;"><span id="texttobecopied"  STYLE="height:150;width:162;background-color:pink">
This text will be copied onto the clipboard when you click the button below. Try it!
</SPAN> </span>
<span style="#800000;"><TEXTAREA ID="holdtext" STYLE="display:none;">
</TEXTAREA>
<BUTTON onClick="ClipBoard();">Copy to Clipboard</BUTTON></span>

We have a button here and a span that contains text that will be copied. The button is calling “ClipBoard();” . This is a function that we have written in javascript. It is below…

<code><SCRIPT LANGUAGE="JavaScript"></code>

function ClipBoard()
{
holdtext.innerText = texttobecopied.innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
}

</SCRIPT>

This script reads the inner text of the span, we defined the span on the first line of the function…

<span style="#800000;"> holdtext.innerText = texttobecopied.innerText;</span>

and then holds it in the computers memory. You can assign when clicking an image to copy text or other data by just adding

<span style="#800000;">onclick="ClipBoard();"</span>

To any Link,Image, script ect…


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Try and Catch (…me if you can)

PHP is a great language for creating dynamic websites and has a lot of functions to do just about everything on the server side.

Only, with all those functions you need a good error handler. The other languages like perl, c, c# etc. have a try and catch function. As of version 5, this function is also available in PHP. In this post I will try to explain to usage and benefits of try and catch. Ready ?

Example:
Let's say you have a website with some blog posts. Visitors can view the latest post by going to www.example.com/?posts
You also create a page to let visitors read a single post. They'll go to: www.example.com/?posts&item=1
This will tell your script that it needs to get item #1 from the database and display it. Now, as we all know, visitors will try all sorts of things, for example: www.example.com/?posts&item=blablabla. This well tell your script that it should fetch item #blablabla from the database which, ofcourse, does not exist and you get a pretty MySQL error.

Try and Catch
Try and catch works by 'throwing errors'. The script executes a try block and if an error is thrown, the try block will end and the catch function will be executed.

try {
    if (isset($_GET['item'])) {
        $postId = mysql_real_escape_string($_GET['item']);
        $qryPost = "SELECT * FROM posts WHERE id = $postId";

    if (!$rsltPost = mysql_query($qryPost)) {
        Throw new Exception();
    }
    if (!mysql_num_rows($rsltPost)) {
        Throw new Exception();
    }
    $arrPost = mysql_fetch_array($rsltPost);
    echo $arrPost[1];
    }
}
catch (Exception $e) {
    echo "There is no such post!";
}

Try
For starters, all the code that we want to error check, needs to be in the try statement. So we start with:

try {

Next is the code to check whether the URL contains the item variable and if it does, execute the code to display that item. Ofcourse we sanitize the variable before sending it to the database.

if (isset($_GET['item'])) {
    $postId = mysql_real_escape_string($_GET['item']);

Query
Normally I write my queries like this:

$qryPost = mysql_query ("SELECT * FROM Posts WHERE id = $postId") or die (mysql_error());

That works fine for most queries. The downside is that when an error occurs, the script dies and displays an error message which could reveal some of your MySQL configuration to the visitor!
We are going to write our query like this:

$qryPost = "SELECT * FROM posts WHERE id = $postId";

Next we're going to evaluate the query and check if it runs without an error:

if (!$rsltPost = mysql_query($qryPost)) {
        Throw new Exception();
    }

As you see, if the query fails, an error is thrown. this will stop the rest of the try statement from executing and go to the catch statement. The same goes for the second if statement. Only this time it checks if the query returns a row.

Catch
The catch statement is executed when an error is thrown.

catch (Exception $e) {
    echo "There is no such post!";
}

Will only echo "There is no such post!" and the rest of your script/site will continue to function.
The try statement also has some debugging features. You can, for example, get the script line on which the error is thrown, or the exact error message.

This is just a basic example of how to use try and catch. You can read more in the php manual

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Youtube Without The Video

Hello there,
It has been a while since I posted something new on my blog, I’ve just been to busy lately.

Today I am going to show you how to put a Youtube video on your website but in a way that only allows you to hear the video rather than being able to see it as well.

Why would I want to do that?
I hear you say. Well sometimes you might want to put music on a page. Youtube is an ideal place to get music from.
Of course you can simply put the video in the page as you would normally do, but that big intrusive box can be annoying at times, especially on myspace etc.

Although this may not be much use to you, it is a nice trick to know :)

You can use this tool to produce the code needed!

The tool allows you to put in Play and Stop controls, but they only work for Firefox.

Feel free to show me a better way to do this if there is one :)

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

MySQL – Connecting, Selecting…. and more.

Today I am going to show you various things that you can do with MySQL using PHP.
I am going to assume you have fairly good knowledge of PHP while following these instructions.

Connecting to MySQL

Connecting to MySQL is extremely simple. I am going to presume you know your MySQL credentials, if you don't know them, find them out 😉 .

$databasehost = "localhost"; //put your MySQL host into this variable. It is usually localhost
$databaseusername = "root"; //put your MySQL username into this variable.
$databasepassword = "somethingreallydifficulttoguess"; //put your MySQL password into this variable.
// I have used long variable names because the likelihood of them being overwritten is unlikely.
$conn = mysql_connect($databasehost,$databaseusername,$databasepassword) or die (mysql_error());
 

And thats it. In the event that your credentials are incorrect and error will be produced.

Creating a MySQL database using PHP

Creating a database in PHP is extremely simple.

mysql_query("CREATE DATABASE `database_name`",$conn) or die (mysql_error());
//this will create a database called "database_name" and use the connection we established earlier to create that database.
 

Selecting the MySQL database

Selecting the MySQL database is even simpler. Once you know your database name you can use this code to select the database:

$databasename = "database_name"; // the name of the database you want to select.
mysql_select_db($databasename,$conn) or die (mysql_error());
//the database you created earlier is now selected. If you already have a database created, you do not need to run the CREATE DATABASE code obviously.
 

Creating a MySQL table within a database

Things start to get a bit more complicated when it comes to creating tables. You may want to look at the MySQL website to get some more information on how to create tables using SQL.

Here is how we would create a table called "new_table" in the database.

mysql_query("CREATE TABLE `new_table` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(25),`age` int, PRIMARY KEY(id))",$conn) or die(mysql_error());
 

This code will create a table with 3 fields in (id - which is the primary key, name which allows up to 25 alphanumeric characters and age that allows an integer) .

Retrieving data from a MySQL table

I am going to show you a basic way of getting data from a table when you know all the field names of that database.
There are numerous ways of doing this (look into mysql_fetch_assoc() and mysql_fetch_array())

$select = mysql_query("SELECT `id`,`name`,`age` FROM `new_table`") or die (mysql_error());
if (mysql_num_rows($select) > 0)
 {
 while (list($_id,$_name,$_age) = mysql_fetch_array($select)) //gets the data from the SELECT query and puts it into variables
  {
   echo "The ID for this record is: " . $_id . "\n";
   echo "The Name for this record is: " . $_name . "\n";
   echo "The Age for this record is: " . $_age . "\n";
  }
 }
else
 {
 echo "There are no records to display";
 }
 

The above example is the way I sometimes chose to do my SELECT queries because it is quite self explanatory with the variables. I would not recommend this method however if you have a lot of variables in your script as it could pose problems with overwriting variables.

This is another way of performing the same query:

$select = mysql_query("SELECT * FROM `new_table`") or die (mysql_error());
if (mysql_num_rows($select) > 0)
 {
 while ($row = mysql_fetch_assoc($select)) //gets the data from the SELECT query and puts it into the $row array
  {
   echo "The ID for this record is: " . $row['id'] . "\n";
   echo "The Name for this record is: " .  $row['name'] . "\n";
   echo "The Age for this record is: " .  $row['age'] . "\n";
  }
 }
else
 {
 echo "There are no records to display";
 }
 

The above does the same thing as the example beforehand, but utilizes only one variable.

Deleting data from a MySQL table
The DELETE query is extremely simple. You simply define the table from which you'd like to delete a record, and specify a record. In this case we are specifying the record with an id of 1.

$del = mysql_query("DELETE FROM `new_table` WHERE `id`= '1' ",$conn) or die(mysql_error());
if (mysql_affected_rows() == 1)
 {
 echo "Record Deleted";
 }
else
 {
 echo "There was a problem deleting the specified record.";
 }
 

Dropping a table from a MySQL database
If you would like to remove a table and all its data from a MySQL database then use the following code:

$drop = mysql_query("DROP TABLE `new_table` ",$conn) or die(mysql_error());
  if($drop)
   {
    echo "new_table has been dropped from the database.";
   }
 

Inserting data into a table
Inserting data into a table is extremely simple.

$insert = mysql_query("INSERT INTO `tblname` (`name`,`username`,`email`) VALUES ('Andrew','papa_face','someone@somewhere.com')",$conn) or die(mysql_error());
  if($insert)
   {
    echo "The record has been inserted into the database.";
   }
 

Of course you can make insert queries dynamic by using variables, but that is one quick and easy example of how to insert data into a table :) .

And that's it!
I hope this blog post have been very informative. Any questions or comments are greatly appreciated.
Thanks for reading!

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Sanitizing $_POST and $_GET

Hey,
Well I haven't posted something PHP related for quite a few days now so I thought I'd show you something I use in every single script that I write that involves form submissions or URL data.
It is important to escape (sanitize) all data from forms that may be used in a mysql database query.
If you use some other database type, the function can easily be modified.

Place this code at the top of all your pages (maybe via an include):

        if(!function_exists(mysql_real_escape_array))
                {
        function mysql_real_escape_array($t)
                        {
        return array_map("mysql_real_escape_string",$t);
                        }
                }

        mysql_real_escape_array($_GET);
        mysql_real_escape_array($_POST);
 

It will automatically sanitize all your $_POST (from forms) and $_GET (URL data) to help prevent SQL injections.

Be aware though, that this is just one precaution you should take when inserting data into a mysql database.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

FORTRAN and Other Programming Languages from the 50’s

FORTRAN-FORmula TRANslating system was invented in the year 1957. The language was very easy to use as it contained limited commands like GOTO, IF and DO. FORTRAN paved the way for today’s languages as it contained basic data types like integer, double precision, logical variables and real numbers which are very much used in today’s languages.

As in those days people were only looking for solving mathematical operations via programming languages, FORTRAN was a result of that need. This is why FORTRAN was amazing with numbers but was not the same in other areas, like handling input and output. As a result the language was not famous amongst businesses. When computers started getting into the businesses in the year 1959 A.D. the need for another language arose.

This is why COBOL was invented. From the beginning itself, COBOL was developed as a businessman’s language. The language was easier than FORTRAN to understand as it had only two types of data types; strings and numbers. The main feature of COBOL was to handle records, as businesses needed to keep an account of previous records. COBOL statements were related to the English language. This made it very easy for the businessman to get the grasp of the language better and they were able to adapt it easily.

In the year 1958 A.D. a new type of language was designed. It was called LISP-LISt Processing language. The main reason for the invention of this language was to explore the field of artificial intelligence. Syntax of the language was different from all the existing languages as the language dealt with a completely new area of concern. As the name suggests, the program in the LISP language are written as a set of lists that represents series of items. As a result of this the LISP programs have a distinctive ability to modify itself from time to time and consequently to develop on its own.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

The Beginning of PHP

PHP – Hypertext preprocessor is basically a computer coding language. The language was designed by Rasmus Lerdorf and was developed by the PHP group. PHP was created in 1994 by Rasmus Lerdorf to help maintain his personal homepage.

He had written a bunch of Common Gateway Interface (CGI) binaries via the C coding language and wanted to restore a trivial set of Perl scripts which he had been using to preserve his homepage by the CGI. He wanted to do this in order to check the traffic on his homepage. This later was released publicly as the first ever version of Hypertext Preprocessor on 8 June, 1995 named PHP/FI (Form Interpreter).

One would wonder why there is an extra letter P in the abbreviation. The reason being the language is initialized again and again, recursively and that’s why the abbreviation PHP. PHP is an essential, object-oriented language. PHP is extensively used as an all-purpose scripting language, which is particularly fitting for web development. The working of PHP is simple. PHP essentially uses a web server to run, which takes the PHP code as input and results in web pages as output.

PHP was originally created for designing dynamic web pages. Over the years the main focus of PHP has changed. Server side scripting is the spotlight of PHP now. Moreover PHP has been declared as free software by the free software association. It is available over the internet and any one can download it. Due to this reason PHP stands out in comparison with competitors like Microsoft’s ASP.NET system, mod_perl framework and Sun Microsystems’ JavaServer Pages as they are not free. The PHP parser can run with both, a web browser and a web server which help in providing dynamic content.
The following is a simple Hello World code example for PHP:

<?php
Echo ’Hello World!’;
?>
 


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

PHP – The Basics – Tags, echo and if/else

One of the most basic things when writing code in PHP is to use the PHP tags which signify the beginning and the ending of the PHP code. You must have the tags in order for PHP to process the code you write. The tags are:

beginning tag:

<?php

ending tag:

?>

e.g

<?php
//code here
?>
 

You can have anything proceeding/preceding the PHP tags, but anything in between them must be valid PHP.

I advise you to only use the tags that I have stated above. Try not to use tags like:

<?
//some code
?>

or

<?= "Hello!" ?>
 

Shorthand tags are not 100% compatible on 100% of servers, however:

<?php
//some code
?>

is! 😉

We’ll start with something pretty simple and it is the echo statement.
This is an example of the echo statement:

<?php
echo "Hello you!";
?>
 

When the script is run, the page will display “Hello you!”.
Notice the semicolon? The semicolon (;) is a line terminator. It tells PHP that you are finished with that particular set of instructions, and that PHP can continue with the script until it reaches the end. If the semicolon is not present at the end of instructions/commands/statements/variables a error may be triggered as a result.

Now lets move on to something a little more useful, the if/else statement.

This is an example of an if/else statement:

<?php
if (5 > 10)
 {
 echo "5 is greater than 10";
 }
else
 {
 echo "5 is not greater than 10";
 }
?>
 

Okay with an if statement you must define the conditions of the if between the brackets. The aim of an if statement, is to get true returned (a boolean). If the condition returns false, then it will run the code in the else statement (if there is one).

In the code above the if statement will return false and display “5 is not greater than 10″ – understand?

Yeah its pretty easy at this level.
If I used this code:

<?php
if (5 < 10)
 {
 echo "5 is less than 10";
 }
else
 {
 echo "5 is NOT less than 10";
 }
?>
 

The if statement would return true, and therefore we would get “5 is less than 10″ printed out on the page.

When writing an if statement there are two important parts.

  1. The condition – this is contained in between brackets (5 < 10)
  2. The curly braces – { } – the code you want to execute should be placed in between the two curly braces. The only exception to this is when you only have one line of instructions like this:
<?php
if (5 < 10)
echo "5 is less than 10";
?>
 

That concludes this part of my help guide I hope it was useful to those starting to learn PHP.
If you want to look into the if/else statement more, look into elseif. The PHP manual is a great resource, so make good use of it. It contains everything you need to know about PHP (literally).

Feel free to comment on this post, I appreciate all the comments I receive! 😀

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Data Types in PHP

PHP is not a very strict language when it comes down to data types.
Strings:

$string = "This is a string";
 

Strings are values that contain characters. This can include basically everything you can type on your keyboard.

Integers:

$string = 1;
 

Integers are values that just contain numbers. Notice in the example above that there are no quotes?
Well, you can write an integer like that, or like this:

$string = "1";
 

PHP automatically converts numbers contained in a string with no other characters into a integer. The only time you need to be careful of this is when you are using operators (I will discuss that in another post).

Boolean:

$string = true;
$string2 = false;
 

Booleans are values that contain either true or false. They can be used in if statements like:

$string = true;
if ($string)//checks if $string is true
 {
 echo '$string is true';
 }
else
 {
 echo '$string is false';
 }
 

Hope that helps you understand data types in PHP better. Obviously I have just scratched the surface in my explanations.
Feel free to comment and ask any questions 😀

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]