May 212012
 

A simple contact form, just for reference. Will add more info later on…

<?php
if (isset($_POST['submit'])) {

	$name = $_POST['name']; //name of sender
	$email = $_POST['email']; //e-mail of sender
	$email = stripslashes($email);
	
	$subject = $_POST['subject']; //e-mail subject 
	$subject = str_replace(array("\r\n","\r","\n"), "", $subject); //remove any linebreaks to keep from code injections

	$message = $_POST['message']; // e-mail message
	$message = str_replace(array("\r\n", "\r"), "\n", $message); // fix line-breaks
	$message = stripslashes($message);

	//headers
	$headers = "From:$name<$email>\r\n";
	$headers .= "Return-path: <$email>\r\n";
	$headers .= "Content-type: text/plain; charset=UTF-8\r\n";
	$headers .= "Content-Transfer-Encoding: 8bit\r\n";
	
	$to = 'myadress@mydomain.com'; //recipients e-mail adress

	//validate email and name variables
	if (!filter_var($email, FILTER_VALIDATE_EMAIL))
	{
		echo 'not a valid e-mail adress';
		die();
	}
	if (preg_match('/[^a-z åäöÅÄÖüÜ _-]/i', $name))
	{
		echo 'not a valid name format';
		die();
	}

	//send the email
	$send = mail($to, $subject, $message, $headers);
	if ($send)
		echo 'email sent';
	else
		echo 'something went wrong, email not sent';
}
?>

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8">
</head>
<body>
	<form action="" method="post">
		name:<br>
		<input type="text" name="name"/>
		<br>email:<br>
		<input type="text" name="email"/>
		<br>subject:<br>
		<input type="text" name="subject"/>
		<br>message:<br>
		<textarea name="message"/></textarea>
		<br>
		<input type="submit" name="submit"/>
	</form>
</body>
</html>
May 122012
 

Principle 1.
Always have a clear image of what you want to do BEFORE you start writing your code. Then break it down in logical instructions – making an algorithm.  An algorithm is a step by step instruction on how to solve a specific problem. You might think of it as a recipe. If you want to bake bread – you don’t just start shoving any eatable stuff you find into the oven without a plan. First you decide what kind of bread you want to make, then you find out what ingredients is needed, how much and in what order they are added.

So basically – if you can’t solve the problem with logic you can’t solve it with code.

For example:
You want to write a piece of code that finds the mean (average) of three numbers supplied by a user.  Before you start writing the code, you must of know how to calculate the mean of three numbers. The solution to this mathematical problem is of course (n1+n2+n3) / 3. Now I just have to break it down into step by step instructions, like this:

1. Gather three numbers from the user
2. Add them together.
3. Divide the sum by three
4. Output the sum on the screen

Now I can easily translate this simple algorithm to code in any language, for example PHP. Review your steps and think about how to solve this in code;

Step 1. Make a form with three textfields.
Step 2 & 3. Take the three values from the POST array, add them together and divide by three.
Step 4. Echo the result.

<html>
<body>
<?php
if (isset($_POST['submit'])) {
	$n1 =$_POST['n1'];
	$n2 =$_POST['n2'];
	$n3 =$_POST['n3']; 
	$sum = ($n1 + $n2 + $n3) / 3;
	echo $sum;
}
?>
<form action="" method="post">
	<input type="text" name="n1" />
	<input type="text" name="n2" />
	<input type="text" name="n3" />
	<input type="submit" name="submit" />
</form>
</body>
</html>     

The calculation could even fit in just one single line:

echo ($_POST['n1'] + $_POST['n2'] + $_POST['n3']) / 3;

 
 
Principle 2.
If you use code that you find online (like on a blog or a forum), make sure you learn what every single line of code does. It will take a bit of time, and might demand some hard work – but having code in your application that you don’t really understand is a bit like playing the lottery. 

Getting code to do exactly what you want will be very hard if you don’t know exactly what is does.

Also, this is maybe the best way to learn how to code.

May 072012
 

If you save your date in the format of timestamp in your MySQL database, and want to output it like this:

$result = mysql_query("SELECT * FROM articles");
$row = mysql_fetch_array($result);
$date = $row['timestamp'];
echo $date;

Your date come out looking something like this: 2011-01-30 20:54:12
So it’s formated like YYYY-MM-DD HH:MM:SS

But what if you want it to display, say like this: Sunday, January 30th, 8:54pm
Normally you would use the date function and pass it a format string and a timestamp. Like this:

$result = mysql_query("SELECT * FROM articles");
$row = mysql_fetch_array($result);
$date = $row['timestamp'];
echo date("l, F jS, g:ia", $date);

But that will give you an error, since the second argument of the date function expects a UNIX timestamp (which is the number of seconds passed since 1970-01-01 00:00:00 until a given date).

In our example the variable $date holds a string that looks like this ‘2011-01-30 20:54:12‘. The date function doesn’t know what to do with that information. So we need to convert the date string to a UNIX timestamp.

Luckily there’s a function called strtotime(), that will take care of this for us.

$result = mysql_query("SELECT * FROM articles");
$row = mysql_fetch_array($result);
$date = $row['timestamp'];
$date = strtotime($date);
echo date("l, F jS, g:ia", $date);

After running the $date variable through the strtotime function (on line 4) it will hold the value 1296420852. The date function will now return the date of this timestamp – in the format we passed in the first argument.

Check out the date function on php.net to learn more about how to format the date string.

May 062012
 

This is just a VERY basic gallery that you can modify to suit your needs. For example you could add columns in the database and store more info about the images (date, size, tags etc.). You could very easily make the output use Lightbox or similar images viewers. And you could of course do a very solid file validation check.

Just to make it clear, I’m not doing any mime verification or size checking of the images, no login or session check (which would be used for uploading or deleting images) and no fancy presentation of the images. This is just a rudimentary , minimal gallery for you to get started. Think of it as a sponge cake base recipe.

Here’s what it does:

  • Allows the user to choose an image and enter a title (or caption).
  • Uploads the image to a folder on the server.
  • Enters the filename and caption in a MySQL database.
  • Output all the images.

I have chosen to break this up in four files, to keep it separated nice and clean. This solution will need a MySQL database. (if you need info on that, follow some tutorial like this).

Also, you need to create a folder, with appropriate read/write-rules, named “images” in the same folder as these scripts.

First off… The MySQL database table should look something like this:

CREATE TABLE IF NOT EXISTS `gallery` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `filename` varchar(128) NOT NULL,
  `title` varchar(1024) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

And here’s the form (the ul-list is just to display the form in a somewhat non-horrible fashion):
gallery_form.php

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<style type="text/css">
	li {
		list-style: none;
	}
</style>

</head>

<body>

<form action="gallery_process.php" method="post" enctype="multipart/form-data">
<ul>
	<li>
    	Choose image
    </li>
	<li>
		<input type="file" name="file" id="file" />
	</li>
	<li>
    	Add title
    </li>
	<li>
		<input type="text" name="title" id="title" />
	</li>
	<li>
		<input type="submit" name="submit" />
	</li>
</ul>
</form>

</body>
</html>

Here's the process that will save the image and update the database.
gallery_process.php

<?php
// This is just my database connection.
include 'includes/db_connect.php';

// Gather the information sent by the form
$temp_filename = $_FILES["file"]["tmp_name"];
$filename = $_FILES["file"]["name"];
$title = $_POST['title'];

/* Split the filename at every dot, take the last part and put it in $ext
(this will be the file extension) */
$splits = explode(".", $filename);
$n = count($splits)-1;
$ext  = '.'.$splits[$n];

/* To get away from any pesky non-standard character problems, weird or duplicate
filenames I swap the filename for an 8-digit number. The loop will check if
an image of that name exists and add 1 to the number until the filename is unique. */
$new_filename_basnumber = 10000000;
$new_filename = $new_filename_basnumber.$ext;

while (file_exists("images/$new_filename")) {
	$new_filename_basnumber++;
	$new_filename = $new_filename_basnumber.$ext;
}

// Move the file to the server and give it the generated name.
move_uploaded_file($temp_filename, "images/$new_filename");

// Enter all information to the database and head over to the output
mysql_query("INSERT INTO gallery (filename, title) VALUES ('$new_filename', '$title')");
header("Location: gallery_output.php");
?> 

Here's the output:
gallery_output.php

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
// Database connection
include 'includes/db_connect.php';

// Get all data from the database table
$result = mysql_query("SELECT * FROM gallery");

// Go through the table and output all images.
while ($row = mysql_fetch_array($result)) {
	$filename = $row['filename'];
	$title = $row['title'];
	$id = $row['id'];

	/* If a post is missing the physical image file, delete it from the database
	this is to keep redundant data to a minimum */
	if (!file_exists("images/$filename")) {
		mysql_query("DELETE FROM gallery WHERE id='$id'");
	}
	else {
		echo '
		<p>
		<a href="images/'.$filename.'" title="'.$title.'" >
			<img src="images/'.$filename.'" title="'.$title.'" width="100"/>
		</a>
		<a href="gallery_delete.php?id='.$id.'" onclick="return confirm(\'Are you sure you wish to delete the image?\')">Delete Image</a>
		</p>';
	}
}
?>

<p><a href="gallery_form.php?">Add new image</a></p>
</body>
</html>

And last the delete image process:
gallery_delete.php 

<?php
// Connect to database
include 'includes/db_connect.php';
// Get the database id of the post to delete
$id = $_GET['id'];

// First get the data and find the filename
$result = mysql_query("SELECT * FROM gallery WHERE id='$id'");
$row = mysql_fetch_array($result);

$filename = $row['filename'];

// Then delete the file and the database post.
if (file_exists("images/$filename")) {
    unlink("images/$filename");
	mysql_query("DELETE FROM gallery WHERE id='$id'");
}

// And head back to the output page
header("Location: gallery_output.php");
?>