Author Archives: Christoffer Wadensten

(PHP) Simple e-mail contact form.

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>

A couple of principles when learning how to code.

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:

Continue reading

Hide elements with radio buttons

Sometimes you want to show or hide certain elements of a form, depending on the selection of a radiobutton.

 

I am by no means any javascript ninja, but this is one simple way I came up with:

<html>
<head>
<script type="text/javascript">
	function DisplayElement(element)
	{
		x = element.value;
		if (x == 1) {
			document.getElementById('text').style.display = '';
		}
		else {
			document.getElementById('text').style.display = 'none';
		}
	}
</script>
</head>

<body>
<form name="form">
<input name="choice" type="radio" value="1" onclick="DisplayElement(this)" checked/>
<input name="choice" type="radio" value="2" onclick="DisplayElement(this)"/>
<input name="text" type="text" id="text"/>
</form>
</body>
</html>

 
This could apply to any element. For example, you could put a whole bunch of elements in a div and the hide/show the div. Like this:


<script type="text/javascript">
	function DisplayElement(element)
	{
		x = element.value;
		if (x == 1) {
			document.getElementById('container').style.display = '';
		}
		else {
			document.getElementById('container').style.display = 'none';
		}
	}
</script>

<form name="form">
<input name="choice" type="radio" value="1" onclick="DisplayElement(this)" checked/>
<input name="choice" type="radio" value="2" onclick="DisplayElement(this)"/>
<div id="container">
	<input type="checkbox"/>
	<input type="checkbox"/>
	<input type="text"/>
	<input type="text"/>
	<input type="text"/>
</div>
</form>

 
 
Here’s another way to do it. This example takes a number as a parameter instead of using the value of the element. A bit more compact code and it might be more flexible.

<script type="text/javascript">
    function DisplayElement(x)
    {
        if (x == 1) {
            document.getElementById('text').style.display = '';
        }
        else {
            document.getElementById('text').style.display = 'none';
        }
    }
</script>

<form name="form">
<input name="choice" type="radio" onclick="DisplayElement(1)" checked/>
<input name="choice" type="radio" onclick="DisplayElement(2)"/>
<input name="text" type="text" id="text"/>
</form>

 
And here’s an even more flexible version. In this example you can pass the id of the element you want to hide as a second argument to the function. This way you can use the same function to toggle the visibility of many different elements.

<script type="text/javascript">
    function DisplayElement(x,target)
    {
        if (x == 1) {
            document.getElementById(target).style.display = '';
        }
        else {
            document.getElementById(target).style.display = 'none';
        }
    }
</script>

<form name="form">
<input name="choice" type="radio" onclick="DisplayElement(1,'text')" checked/>
<input name="choice" type="radio" onclick="DisplayElement(2,'text')"/>
<input name="text" type="text" id="text"/>
</form>

Here is another post, to do the same thing with a checkbox.

Hide elements with checkbox

This is a slightly edited version of this post. Just to make it work with a checkbox instead of radio buttons.

 

 

<html>
<head>
<script type="text/javascript">	
	function DisplayElement(checked) 
	{
		if (checked) {
			document.getElementById('text').style.display = '';
		}
		else {
			document.getElementById('text').style.display = 'none';
		}
	}
</script>
</head>
<body>
<form name="form">
<input type="checkbox" onclick="DisplayElement(this.checked)" checked/>
<input type="text" id="text"/>
</form>
</body>
</html>

Convert MySQL timestamp to PHP date

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.

(PHP) How to make a simple gallery

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= InnoDB 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);
$index = count($splits) - 1;
$ext  = '.'.$splits[$index];

// Here's an alternative, more slick way of finding the file extension
// $ext = '.'.pathinfo($filename, PATHINFO_EXTENSION);

/* 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_basenumber = 10000000;
$new_filename = $new_filename_basenumber.$ext;

while (file_exists("images/$new_filename")) {
	$new_filename_basenumber++;
	$new_filename = $new_filename_basenumber.$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
mysqli_query($link, "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 = mysqli_query($link, "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")) {
		mysqli_query($link, "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 = mysqli_query($link, "SELECT * FROM gallery WHERE id='$id'");
$row = mysqli_fetch_array($result);

$filename = $row['filename'];

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

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