Howto: Make a simple files upload system

Howto, php 29 Comments »

An upload system for files is nowadays considered as a mandotory tool for content management systems (CMS). In this tutorial you will learn how to create a basic file upload system. I’ll start by creating the hardest part of the upload system. The upload form.

The form itself is also different from usual html forms.

<form action="form.php" method="post" name="add-form" enctype="multipart/form-data">
<label for="file">Filename:</label><br />
<input type="file" name="file" id="file" /><br />
<input type="hidden" name="action" value="add" /> <!-- Hidden input type, checking which form to use-->
<input type="submit" name="submit" value="Upload" />
</form>

As you can see, the form starts with the action and method. However, the enctype is probably a new attribute you’ve spotted in an HTML form. The enctype attribute indicates how the data is encoded. When an HTML form has no enctype, the default enctype is used, which is “application/x-www-form-urlencoded”. If you run this code you’ll already see a textfield and a browse button next to it. Now for the “form.php”, which is the action the form refers to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
if(isset($_POST['submit'])) {
	// If action is add. 
	if($_POST['action'] == 'add') {
		// Define the folder where the file will be uploaded.
		$upload_path = './uploads/' . $_FILES['file']['name'];
		// Check if the file already exists in the folder.
		if(!file_exists($upload_path)) {
			// Check the size of the file. 
			// The file should be under 100 kb. But OVER 0 bytes.
			if($_FILES['file']['size'] < 100000 && $_FILES['file']['size'] > 0) {
				// If there are any errors.
				if($_FILES['file']['error']) {
					echo "Error: " . $_FILES['file']['error'];
				} else {
					// Success!
					echo "File successfully uploaded.<br /><br />";
					echo "The filename is: <strong>" . $_FILES['file']['name'] . "</strong><br />";
					echo "The filesize is: <strong>" . $_FILES['file']['size'] . "</strong><br />";
					echo "The filetype is: <strong>" . $_FILES['file']['type'] . "</strong><br />";
					echo "The file is temporary saved in: <strong>" . $_FILES['file']['tmp_name'] . "</strong><br />"; 
 
					// Move uploaded file to upload folder.
					move_uploaded_file($_FILES['file']['tmp_name'], $upload_path);
				}
			} else {
				echo $_FILES['file']['size'] < 1 ? 'Incorrect filename.' : 'File size is too big';
			} 
		} else {
			echo "File already exists in your folder. ";
		}
	}
}

In the code an upload path is given in a variable. You can change the upload path to the destinated folder where to upload the file s into. In this code the file is uploaded in the currentfolder/uploads/. When a file is uploaded the file has the exact same filename as the filename you’ve chosen to upload. So if your file is named ‘hi.html’. The uploaded result resides in ‘currentfolder/uploads/hi.html’.

It’s also possible to filter files. For example, if you only want files to have a limited amount of extensions you could make an array with extensions.

$allowed_extensions = array(
	'png',
	'gif',
	'bmp',
	'jpg',
	'jpeg'
);

To check if a file contains the extension, use the following code.

$filename = $_FILES['file']['name'];
$new_filename = explode('.', $filename);
if(in_array($new_filename[count($new_filename) -1], $allowed_extensions)) {
	// Continue with the code
} else {
	// Stop the code.
}

From the $_FILES super global, the variable $filename is created. The filename is modified to an array, using the ” . ” as the place to split the variable. So in this case, the filename could be for example; hello.gif. This variable would be split in two values,

// $new_filename
array('hello', 'gif');

By checking if the last value is correctly nested in the extensions array, the code should return TRUE. Elsewise the code should turn out FALSE and print the error message, saying that the filename contains an invalid extension.

You now know how to create an upload form and validating the upload form. The next step is how to make the php code to view a directory and how to show all files available in the directory. This file is named ‘view.php’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Specify the uploads folder in a variable. 
// This is exactly the same folder used in the upload script.
$dir = './uploads/';
 
// Try to open the directory.
if($dir = opendir($dir)) {
        // Create an HTML table using a small CSS style.
	echo '<table style="width: 250px;">';
        // Create the variable $file. If reading the dir DOESN'T turn out FALSE, print out the file with a link.
	while(($file = readdir($dir)) !== false) {
		// Remove the dots in $file. 
		if($file != '.' && $file != '..') {
			echo '<tr>';
                        // Print a link containing the name of the file.
                        // The link continues to delete.php?file=$filename. 
                        // This is used for deleting the uploaded file.
			echo '<td>' . $file . '</td><td><a href="delete.php?file=' . $file . '">delete</a>';
			echo '</tr>';
		}
	}
	echo '</table>';
        // Close the opened directory.
	closedir($dir);
}

After running this script, you’ll see an 250 pixels width table containing the name of the file and a hyperlink refering to the delete.php page. Now, let’s create the delete page.

1
2
3
4
5
6
7
8
9
10
11
12
13
// Using the superglobal $_GET, get the filename.
$file = $_GET['file'];
// The upload dir, exactlty the same as in the previous scripts.
$upload_dir = './uploads/';
// The complete file path to the file. 
$file_path = $upload_dir . $file;
// Check if the filepath is correct.
if(is_file($file_path)) {
        // Delete the file using the unlink function.
	unlink($file_path);
        // Give a message to tell the user, the file is deleted.
	echo "File " . $file . " deleted.";
}

This script isn’t very hard, is it? You’ve seen the hyperlink refering to a ‘delete.php’ page. After the delete.php you’ve seen ‘file=$filename’. with the $_GET[’file’] array, the PHP script literally GETS the name after ‘file’. So in this case it’s $filename. $_GET methods are commonly used to make websites more dynamic and it’s much better than creating seperate pages and updating them frequently.

Download the zip file.

Howto: Create a login form in PHP

Howto, php 41 Comments »

On most websites you can register and login as a user. Today, we’re going to create a form where you can register and a form to login. We will use the programming language PHP for it.

Requirements

  • Basic knowledge of HTML
  • Basic knowledge of PHP
  • A webserver and PHP + MySQL

Contents

  • Setting up the database
  • Creating the database connection
  • Creating the registerform
  • Handle the registerform
  • Creating the loginform
  • Handle the loginform

Setting up the database

Create a database for this tutorial. It doesn’t matter what name you use for the database. If you do not know how to create a new database, use the following code.

CREATE DATABASE `login`

When you’re done creating a new database, you’ll need to create the tables. In the tables the data proccessed from the registerform is stored. And the data in the table is used to check if a user has registered.

CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL ,
`email` VARCHAR( 255 ) NOT NULL
)

In this code, the table users is created. The id is a mandotory value and is used as a primary key. Username, password and email are the fields you want to store data in. They’re given a allowance of 255 characters in a single field. Last, each time new data is stored, the id auto increments, which means the id will increment with ‘one’.

Creating the database connection

Creating the database connection is simple. Enter the following code, but with your own username and password.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php 
// Your host, 99% of the time it's localhost.
$db_host = 'localhost';
// Your username for MySQL.
$db_user = 'user';
// Your password for MySQL.
$db_pass = 'pass';
// And your given name for the database.
$db_name = 'login';
 
// The database connection.
$con = mysql_connect($db_host, $db_user, $db_pass);
if(!$con) { 
	die("Cannot connect. " . mysql_error());
}
// The database name selection.
$dbselect = mysql_select_db($db_name);
if(!$dbselect) { 
	die("Cannot select database " . mysql_error());
}
?>

Just save this file as ‘connection.php’. We’ll include this file in the authenticate page.

Creating the registerform

Create an empty PHP page with the name ‘register.php’ and write the following code within the <body> tags.

<form method="post" action="authenticate.php"> <!-- you can use another action if you'd like -->
	<label for="username">Username: </label><br />
	<input type="text" name="username" id="username"><br />
	<label for="password">Password: </label><br />
	<input type="password" name="password" id="password"><br />
        <label for="password2">Confirm: </label><br />
        <input type="password" name="password2" id="password2"><br>
        <label for="email">Email address:</label><br />
        <input type="text" name="email" id="email"><br />
	<input type="submit" name="submit" id="submit" value="Submit">
</form>

Handle the registerform

Now it gets interesting. Create another empty PHP page and name it after the action given in the <form action=”"> tag. If you’ve copied the previous code, the page would be named ‘authenticate.php’.

Type in the following code in your PHP page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php 
// Include the database connection file.
include("connection.php");
// Check if a person has clicked on submit.
if(isset($_POST['submit'])) { 
	// Check if a person has filled every form.
	if(empty($_POST['username']) || empty($_POST['password']) || 
           empty($_POST['password2']) || empty($_POST['email'])) {
                // Display the error message.
		echo "You have to fill in everything in the form."; 
               // Exit the code.
                exit;
	}
	// Create variables from each $_POST.
	$username = $_POST['username'];
	$password = $_POST['password'];
	$password2 = $_POST['password2'];
	$email = $_POST['email'];
 
	// Now, compare passwords and check if they're the same.
 
	if($password != $password2) {
		// If the passwords are NOT the same. Again display an error message and redirect.
		echo "Sorry, wrong password.";
                exit;
	}
	// Secure the password using an md5 hash.
	$password = md5($password);
 
	// Create a variable containing the SQL query.
	$query = "INSERT INTO `users` (username, password, email) 
                      VALUES ('$username', '$password', '$email')";
	// Perform the SQL query on the database.
	$result = mysql_query($query);
	// If the query failed, display an error.
	if(!$result) { 
                // The dot seperates PHP code and plain text.
		echo "Your query failed. " . mysql_error();
	} else {
		// Display a success message!
		echo "Welcome " . $username . " You are now registered";
	}
}
?>

By filling in the registerform. The data from the regsiterform is posted to the PHP file ‘authenticate.php’ and processed. The data is then stored into the database, in the table ‘users’. The user will now be able to log in

Creating the loginform

This is almost the same as creating the registerform.

<form method="post" action="login2.php">
	<label for="username">Username: </label><br />
	<input type="text" name="username" id="username"><br />
	<label for="password">Password: </label><br />
	<input type="password" name="password" id="password"><br />
	<input type="submit" name="submit" id="submit" value="Submit">
</form>

The user types in his/her username and password and then clicks on submit. In the file ‘login2.php’ we’ll create the login process.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php 
// login2.php
include("connection.php");
 
// Start a session. Session is explained below.
session_start();
 
// Same checking stuff all over again.
if(isset($_POST['submit'])) {
	if(empty($_POST['username']) || empty($_POST['password'])) {
		echo "Sorry, you have to fill in all forms";
                exit;
	}
	// Create the variables again.
	$username = $_POST['username'];
	$password = $_POST['password'];
	// Encrypt the password again with the md5 hash. 
	// This way the password is now the same as the password inside the database.
	$password = md5($password);
 
	// Store the SQL query inside a variable. 
	// ONLY the username you have filled in is retrieved from the database.
	$query = "SELECT username,password 
			  FROM	 `users`
			  WHERE	 username='$username'";
 
	$result = mysql_query($query);
	if(!$result) { 
		// Gives an error if the username given does not exist.
		// or if something else is wrong.
		echo "The query failed " . mysql_error();
	} else {
		// Now create an object from the data you've retrieved.
		$row = mysql_fetch_object($result);
		// You've now created an object containing the data.
		// You can call data by using -> after $row.
		// For example now the password is checked if they're equal.
		if($row->password != $password) {
			echo "I am sorry, but the passwords are not equal.";
                        exit;
		}
		// By storing data inside the $_SESSION superglobal,
		// you stay logged in until you close your browser.
		$_SESSION['username'] = $username;
		$_SESSION['sid'] = session_id(); 
		// Make it more secure by storing the user's IP address.
		$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
		// Now give the success message.
		// $_SESSION['username'] should print out your username.
		echo "Success! You are now logged in " . $_SESSION['username'];
	}
}

This all should work fine if you correctly followed everything. I have included a .zip file with the full login form in it. Feel free to comment and ask questions

Download .zip

Make simple arrays in PHP

Howto, php No Comments »

I always liked the qw function from perl. You could easily make an array just by seperating the values with whitespaces. For example:

1
2
#!usr/bin/perl 
$array = qw("first second third fourth");

You would now have an array consisting of the values ‘first’, ’second’, ‘third’ and ‘fourth’. in PHP you would have to type the following code.

1
2
3
<?php
$array = array('first', 'second', 'third', 'fourth'); 
?>

This is much longer than the perl function.. So I simply made the qw function for PHP. It was actually very simple.

1
2
3
4
5
6
7
<?php 
function qw($string)
{
	$array = explode(' ', $string);
	return $array;
}
?>

Sample use:

1
2
3
4
<?php
$array = qw('first second third fourth fifth');
print_r($array);
?>

Output:

Array
(
    [0] => first
    [1] => second
    [2] => third
    [3] => fourth
    [4] => fifth
)

Hello World in PHP

Hello World, php No Comments »

The hello world example in PHP.

1
2
3
<?php 
echo "Hello World!";
?>
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Login