Christoffer Wadensten

Teach by day, code by night.

May 082013
 

This is an enhanced version of this

It’s a VERY simple php gallery. You could develop it in any direction. This one only supports jpg, but that could be augmented as well.
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.
  • Creates a thumbnail
  • 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
// FUNCTION:		image_to_thumb
// Parameters:
// $src: 			source jpeg
// $dest: 			destination file
// $thumb_width: 	width of thumbnail
// $thumb_quality: 	quality of thumbnail (0-100)
function image_to_thumb($src, $dest, $thumb_width, $thumb_quality) {

	// Read the source image
	$src_image = imagecreatefromjpeg($src);
	$src_width = imagesx($src_image);
	$src_height = imagesy($src_image);
	
	// Generate thumbnail height, relative to its width 
	$thumb_height = floor($src_height * ($thumb_width / $src_width));
	
	// Create a new image with target dimensions
	$dest_image = imagecreatetruecolor($thumb_width, $thumb_height);
	
	// Copy source image to destination image, with new dimensions
	imagecopyresampled($dest_image, $src_image, 0, 0, 0, 0, $thumb_width, $thumb_height, $src_width, $src_height);
	
	// create the physical thumbnail image to its destination 
	imagejpeg($dest_image, $dest, $thumb_quality);	
	
	// Free up resources
	imagedestroy($src_image);
	imagedestroy($dest_image);		
}


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

// path to images folder
$images_path = "images";
$images_path .= "/";

// Desired width of thumbnail, in pixels
$thumb_width = 150;

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

// Check that the image is a jpeg. 
$image_info_array = getimagesize($temp_filename);
if ($image_info_array['mime'] !== 'image/jpeg')
{
	echo "This script only supports jpeg images"; 
	// ... add appropriate  actions
}
else 
{
	// Find file extension
	$ext = '.'.pathinfo($filename, PATHINFO_EXTENSION);

	// To get away from any filename problems the filename is swapped for a 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;

	while (glob($images_path.$new_filename_basenumber.'*')) 
	{
		$new_filename_basenumber++;
	}

	$new_filename = $new_filename_basenumber.$ext;
	$thumb_name = $new_filename_basenumber."_thumb".$ext;

	// Move the file to the server and give it the genereated name.
	move_uploaded_file($temp_filename, $images_path.$new_filename);

	// Make a thumnail
	image_to_thumb($images_path.$new_filename, $images_path.$thumb_name, $thumb_width, 80);

	// 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';

// Set image folder path
$images_path = "images";
$images_path .= "/";

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

echo "<strong>Click the thumbnails to see full size image</strong><br />";

// Go through the table and output all images.
while ($row = mysql_fetch_array($result)) {
	$filename = $row['filename'];
	$title = $row['title'];
	$id = $row['id'];
	
	$thumb_filename = pathinfo($images_path.$filename, PATHINFO_FILENAME).'_thumb.'.pathinfo($images_path.$filename, PATHINFO_EXTENSION);
	
	echo '<p>
			<a href="'.$images_path.$filename.'" title="'.$title.'" ><img src="'.$images_path.$thumb_filename.'" title="'.$title.'" /></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';

// Set image folder path
$images_path = "images";
$images_path .= "/";

// 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'];

$thumb_filename = pathinfo($images_path.$filename, PATHINFO_FILENAME).'_thumb.'.pathinfo($images_path.$filename, PATHINFO_EXTENSION);
echo $thumb_filename;


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

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

To prevent a Phonegap-wrapped app from opening external links in the apps webview, use javascript to open the link in the external browser.

This works on Android (probably other platforms as well)

<a href="#" data-rel="external" target="_blank" onclick="window.open('http://www.jymden.com', '_system')">Jymden</a>
Aug 312012
 

Add an event handler for Form Closing and use this code. This is a really simple solution.

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
  if (MessageBox.Show("Are you sure?", "Close application", MessageBoxButtons.YesNo) == DialogResult.Yes)
     e.Cancel = false;
  else
     e.Cancel = true;
} 
Jul 312012
 

Sometimes you need to check if a number is even or odd. A simple way to do this is using the modulus operator (the %-sign). It will calculate and return the remainder when dividing a value with another value.

So how do you use that to find out if a number is even or odd?

As usual you need to understand the logic of the operation to be able to program a solution. In this case it’s really easy… The definition an even number is of course that it’s dividable by two (leaving no remainder). This is simple second grade school math.

So all we have to do is divide the number by 2 and check that the remainder is 0. Using the modulus operator this could look like this: 4 % 2 == 0. That operation will return TRUE, since dividing 4 by 2 will give the remainder of 0.

Sometimes you need to check a lot of numbers through out your application, and it might be convenient to have a function you can simply call whenever needed.
A very simple function, that takes one argument (number) could look like this:

<?php
function isEven($number)
{
	if ($number % 2 == 0)
		return true;
	else
		return false;
}
?>

The function will return TRUE if the number is even and FALSE if it is odd. Also, since the only values the function will return is either TRUE or FALSE (depending on the outcome of the if-condition). You could put the condition directly in the return statement. Looks better and saves some code. Like this:

function isEven($number)
{
	return ($number % 2 == 0);
}

You just call the function with the variable or number you need to check. Like this:

<?php
function isEven($number)
{
	return ($number % 2 == 0);
}

$dude = 3; 

if (isEven($dude))
	echo $dude." is an even number";
else
	echo $dude." is an odd number";

?>

You could of course just use the modulus directly in your code, without a function since it holds very little code. But there might be other operations you want to do in there – like checking if the number is an integer and so on.

Also, putting often used code inside a good function with a self explanatory name – will increase the readability of your code.

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 082012
 

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.

May 072012
 

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>