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! :D

[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 :D

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


How to make a Dynamic Image

Dynamic images (as I call them) are images that change depending on a condition.
A regular image URL is something like:
#1

<img src="http://www.papaface.com/blog/wp-content/themes/papaface/images/beer.png" />
 

However a Dynamic Image's URL could be something like:
#2

<img src="http://www.papaface.com/blog/somephpfile.php" />
 

Notice the difference?
Example 1's URL is actually an image file, however example 2's URL is actually a PHP file producing a dynamic image in this case.

These dynamic images are useful if you want to change the image produced at any point.

Lets say we are providing a link checking service and I want to offer the visitors the ability to put an image on their site once they've used the link checking service. The image will change to green when the link is valid, and red when it is not.

<img src="http://www.papaface.com/blog/resources/dynamicimage/example.php?id=22451" />
 

Now every time the image is loaded the script can actually look for link id "22451" in a database. It can then check the image for validity and produce a green or red image like so:

This is the code that would allow you to do this:

<?php  
       
        $linkid = $_GET['id']; //this is the link id that the script needs to look for in the database
       
        //you would open a mysql connection here
       
        $get = @mysql_query("SELECT `link` FROM `tbllinks` WHERE `linkid`='".mysql_real_escape_string($linkid)."'"); //@ suppresses the error message (this is usually a bad coding practice, but in this case we do not want anything other than an image displayed to the user.

        list($url) = mysql_fetch_array($get);
        /*The code below checks the link. If it is a valid and working link it will return a 200 code.*/
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        $info = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if      ($info == "200")
                $colour = "green";   //link is valid
        else
                $colour = "red"; //link is NOT valid
        }

    //code above decided if it should be green or red and produced $colour
   
        header("Content-type: image/jpg");
        $im     = imagecreatefromjpeg($colour.".jpg"); //tells the script what image to source locally (green.jpg/red.jpg are actual images in the directory)
        $orange = imagecolorallocate($im, 220, 210, 60);
        $px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
        imagestring($im, 3, $px, 9, $string, $orange);
        imagepng($im);
        imagedestroy($im);

?>
 

And that is a way of making a dynamic image. I have provided a relatively basic example of how to use dynamic images, I hope it was interesting :)

Feel free to ask me any questions!

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


A Simple Banner Rotator Script

I'm in the coding mood today :) .
I cannot count how many times I've been asked to code a UBER simple banner rotator script.
These things are so simple, but if you don't know PHP it can be difficult to understand.

The script below has two variables:

$links = array(
"http://www.google.com",
"http://www.msn.com",
"http://forums.digitalpoint.com"
);
//add a new link for the banner to a new line in the same format as above
 

and:

$images = array(
"http://www.google.co.uk/intl/en_uk/images/logo.gif",
"http://stc.msn.com/br/hp/en-us/css/35/decoration/msn_b.gif",
"http://forums.digitalpoint.com/images/misc/dps_logo.gif"
);
//add a new image link for the banner to a new line in the same format as above
 

As you can see they match up. The first line for the $links variable is for a google image, the second is for a msn image etc.
Here is the full code:

<?php
session_start();

$links = array(
"http://www.google.com",
"http://www.msn.com",
"http://forums.digitalpoint.com"
);
//add a new link for the banner to a new line in the same format as above

$images = array(
"http://www.google.co.uk/intl/en_uk/images/logo.gif",
"http://stc.msn.com/br/hp/en-us/css/35/decoration/msn_b.gif",
"http://forums.digitalpoint.com/images/misc/dps_logo.gif"
);
//add a new image link for the banner to a new line in the same format as above
//-------- DO NOT EDIT BELOW THIS LINE----------
$count = count($links) -1;

$randnum = mt_rand(0,$count);

if      ($randnum == $_SESSION['randnum'])
        {
        $randnum = mt_rand(0,$count);
        }
$_SESSION['randnum'] = $randnum;
echo '<a href="'.$links[$randnum].'"><img style="border:none" src="'.$images[$randnum].'" /></a>';

?>
 

The code has been constructed so that the likelihood of getting the same banner displayed twice is greatly reduced.

Comment here if you like the script, or have any questions :D

You can see an example of the script running here.

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


A Register/Login Class

Hello,
Well it has been a while since any posts were made here so I guess its time for me to post something useful (if you're a coder).
I've been working on a new project and in the process I have been constructing a login/register class that could easily fit into any current script I think.
Here it is :)

<?php
class MemberFunctions
        {
        var $pass;
        var $username;
        var $email;
        var $userid;

        function CheckUsername($username)
                {
                $username = trim($username);
                if      (!empty($username))
                        {
               $check = mysql_query('SELECT `id`,`username` FROM `members` WHERE `username`="'.$username.'"');
               if       (mysql_num_rows($check) == 0)
                {
                list($_id,$un) = mysql_fetch_array($check);
                $this->username = $username;
                $this->userid = $_id;
                return true;
                }
               else
                                return false;
                        }
                else
                        return false;
                }

        function CheckPasswords($pw1,$pw2)
                {
                $pw1 = trim($pw1);
                $pw2 = trim($pw2);
                if      (!empty($pw1) && !empty($pw1))
                        {
                        $pw1 = md5(trim($pw1));
                        $pw2 = md5(trim($pw2));
                                if      ($pw1 == $pw2)
                                        {
                                        $this->pass = $pw1;
                                        return true;
                                        }
                                else
                                        return false;
                        }
                else
                        return false;
                }

        function CheckEmailAddress($email)
                {
                        $email = trim($email);
                        if      (!empty($email))
                                {
                                $this->email = $email;
                                return true;
                                }
                        else
                                return false;
                }

        function Register()
                {
                $insert = mysql_query("INSERT INTO `members` (username,password,email) VALUES ('".$this->username."','".$this->pass."','".$this->email."')");
                if      ($insert)
                        {
                        $_SESSION['loggedin'] = 1;
                        $_SESSION['username'] = $this->username;
                        $_SESSION['userid'] = $this->userid;
                        return true;
                        }
                else
                        return false;
                }

        function LoginCheckUsername($username)
                {
                if      (!empty($username))
                        {
               $check = mysql_query('SELECT `id`,`username` FROM `members` WHERE `username`="'.$username.'"');
               if       (mysql_num_rows($check) == 1)
                {
                list($_id,$un) = mysql_fetch_array($check);
                $this->username = $username;
                $this->userid = $_id;
                return true;
                }
               else
                                return false;
                        }
                else
                        return false;
                }

        function LoginCheckPassword($pw)
                {
                if      (!empty($pw))
                        {
                        $pw = md5($pw);
                  $check = mysql_query("SELECT `password` FROM `members` WHERE `password`='".$pw."' AND `username`='".$this->username."'");
                  if    (mysql_num_rows($check) == 1)
                        {
                        $this->pass = $pw;
                        return true;
                        }
                  else
                        return false;
                        }
                else
                        return false;
                }

        function Login()
                {
                if      ($this->pass != "" && $this->username != "")
                        {
                        $_SESSION['loggedin'] = 1;
                        $_SESSION['username'] = $this->username;
                        $_SESSION['userid'] = $this->userid;
                        return true;
                        }
                else
                        return false;
                }

        function Logout()
                {
                if      ($_SESSION['loggedin'] == 1)
                        {
                        $_SESSION['loggedin'] = 0;
                        return true;
                        }
                else
                        return false;
                }

        }
$_mem = new MemberFunctions();
?>
 

Feel free to offer any suggestions as to how the code can be improved as it is still in its early stages.

Update 02 Jan 2008:
I have updated the code to change a few things.

Here is also a way to use the class in your script:

<?php
if      (!$_mem->LoginCheckUsername($_POST['username']))
                {
                $_SESSION['lerror'][] = "Incorrect username entered.";
                }
        if      (!$_mem->LoginCheckPassword($_POST['password']))
                {
                $_SESSION['lerror'][] = "You have entered an incorrect password. Please try again.";
                }
        if      ($_SESSION['lerror'])
                {
                header('Location: login.php');
                exit;
                }
        else
                {
            if  (!$_mem->Login())
                {
                $_SESSION['lerror'][] = "There was a problem logging you in, please try again later.";
                header('Location: login.php');
                                exit;
                }
                else
                        {
                        $_loggedin = 1;
                        }
                }
?>
 

If there are any errors you can print them out using this code:

<?php
if(!empty($_SESSION['lerror'])){
   if(is_array($_SESSION['lerror'])){
        foreach($_SESSION['lerror'] as $value){
              echo $value."
"
;
         }
   }
   $_SESSION['lerror'] = NULL;
}
?>
 

Hope that helps :D

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


Protect a PHP page the easy way…

Have you ever wanted to protect a PHP page to prevent people from viewing sensitive information?
Well I haven't but that doesn't stop me showing you how to do it if you ever need to :D .
The code below is extremely simple indeed. Anyone with a basic PHP understanding will see how simple it is.

All you have to do is paste the code below to the top of your PHP page and change these values:

$pass = "YOUR PASSWORD HERE";
$user = "YOUR USERNAME HERE";

Here is the code that I wrote, enjoy.

<?php
        session_start(); //initiates the sessions
        if      ($_POST['submit'])//checks to make sure the login form has been submitted
        {
        $pass = "YOUR PASSWORD HERE";
        $user = "YOUR USERNAME HERE";
        if      ($_POST['pass'] == $pass && $_POST['user'] == $user)//checks if the password submitted by the user matches the password stored in the $pass variable
        {
        $_SESSION['access']     = 1;//if login is successful create a session that can be authenticated
        header("Location: " . $_SERVER['PHP_SELF']);//reload the page. The page will now not load the login form (see the first if condition)
        }
        else// if password is incorrect reload the login form
        {
        header("Location: " . $_SERVER['PHP_SELF']);
        }
        }
        else if (!$_SESSION['access'])//if the "access" session is not accessible show the form (not logged in)
        {?>
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <table align="center" cellpadding="3" cellspacing="3">
        <tr>
        <td bgcolor="#F7F7F7">Username:</td>
        <td bgcolor="#F7F7F7"> <input name="user" type="text" /></td>
        </tr>
        <tr>
        <td bgcolor="#F7F7F7">Password</td>
        <td bgcolor="#F7F7F7"><input name="pass" type="text" /></td>
        </tr>
        <tr>
        <td colspan="2" bgcolor="#F7F7F7"><div align="center">
        <input name="submit" type="submit" value="Login">
        </div></td>
        </tr>
        </table>
        </form>
        <?php
        exit;
        }
        ?>
 

What is interesting about this code is that you don't need to keep logging in everytime you return to the PHP page. It stores your valid login session :) .

Feel free to post a comment about the simple script, or indeed ways to improve it.

You may test the script here
Username: username
Password: pass

[Slashdot][Digg][Reddit][del.icio.us]