Thursday, December 12, 2024

PHP Tips & Tricks – A Picture Upload, Part 1

First, I’d like to give credit to my co-author, Mundi King. I’ve
mentioned him before — he’s the PHP guru who can wite code with both hands tied
behind his back (well, almost!!) Thanks, Mundi, for great work on this! And now
to it……

There are entire shelves of books dedicated to tackling the question "how should
one write a program?". It is a difficult question and you will invariably get a
different answer depending on the programmer you ask.

One of the harder tasks to writing a PHP application (or any program) is to know
how to break down the processes into smaller, more manageable pieces.

Many PHP files start out as simple little scripts, but after time (and many
feature requests) they tend to grow into very long, complicated programs. It may
even become difficult to determine exactly what the program is doing at any
given point. It is at this point where breaking it down will add a bit of
clarity to the program flow.

Fortunately, PHP provides a few simple, yet elegant methods for breaking out
code into separate pieces. The first one we will concentrate on is PHP’s very
powerful include() statement.

Let us start with an often requested web application that will allow an end user
to upload an image file to the web server and then give them a list of the
images they have uploaded in the past.

Starting with first things first, we know that we will need a web form that has
a file upload field and a submit button. And we know we will need some php code
to actually handle the upload. Here is an example.

<?
//print_r($_POST);

if($_POST["action"] == "Upload Image")
{
unset($imagename);

if(!isset($_FILES) && isset($HTTP_POST_FILES))
$_FILES = $HTTP_POST_FILES;

if(!isset($_FILES[’image_file’]))
$error["image_file"] = "An image was not found.";

$imagename = basename($_FILES[’image_file’][’name’]);
//echo $imagename;

if(empty($imagename))
$error["imagename"] = "The name of the image was not found.";

if(empty($error))
{
$newimage = "images/" . $imagename;
//echo $newimage;
$result = @move_uploaded_file($_FILES[’image_file’][’tmp_name’], $newimage);
if(empty($result))
$error["result"] = "There was an error moving the uploaded file.";
}

}

?>

<form method="POST" enctype="multipart/form-data" name="image_upload_form"
action="<?$_SERVER["PHP_SELF"];?>">
<p><input type="file" name="image_file" size="20"></p>
<p><input type="submit" value="Upload Image" name="action"></p>
</form>

<?
if(is_array($error))
{
while(list($key, $val) = each($error))
{
echo $val;
echo "<br>n";
}
}
?>

Without going into great detail, here is the basic low-down of the up-load.

The bulk of the php code only get activated if $_POST["submit"] is "Upload
Image" and this only occurs if someone has pressed the submit button. The form
actually submits back to itself by using the <?$_SERVER["PHP_SELF"];?>. Inside
the HTML of the form, we will print out any error messages that may have
occurred. This script also assumes that there exists a directory named "images"
that is writable by the web server. You can usually accomplish this by ftping
into your website and making a folder named "images" and changing the
permissions of the folder to 777 or xxx or execute execute execute.

You may want to take a look at this tutorial about uploading files.

https://www.htmlgoodies.com/beyond/php/article.php/3472551

Now that we have our uploading script, it is time to take a step back and see if
there is a way that we can make it more modular. Imagine a scenario where you
are working with a team, and a designer who only knows HTML wants to modify the
form. This could lead to a dangerous situation where he inadvertently changes
some php code when he just wants to change some HTML.

Here is where php’s include() comes in handy. include() lets you grab other
files and php will automatically insert everything from that file at the exact
place you invoke the include() statement. To accomplish this, one only has to
type the file name in-between the parentheses of the statement. For example,
include("myfile.txt");

If we separate out our one giant php script so that the html part is in another
file and leave most of the php in the original script, the HTML designer can go
into that file and not have to worry about changing code.

After putting in our include, the main file would appear like this…

<?
//print_r($_POST);

if($_POST["action"] == "Upload Image")
{
unset($imagename);

if(!isset($_FILES) && isset($HTTP_POST_FILES))
$_FILES = $HTTP_POST_FILES;

if(!isset($_FILES[’image_file’]))
$error["image_file"] = "An image was not found.";

$imagename = basename($_FILES[’image_file’][’name’]);
//echo $imagename;

if(empty($imagename))
$error["imagename"] = "The name of the image was not found.";

if(empty($error))
{
$newimage = "images/" . $imagename;
//echo $newimage;
$result = @move_uploaded_file($_FILES[’image_file’][’tmp_name’], $newimage);
if(empty($result))
$error["result"] = "There was an error moving the uploaded file.";
}

}

include("upload_form.php");

if(is_array($error))
{
while(list($key, $val) = each($error))
{
echo $val;
echo "<br>n";
}
}

?>

and our mostly HTML file would be this…

<form method="POST" enctype="multipart/form-data" name="image_upload_form"
action="<?$_SERVER["PHP_SELF"];?>">
<p><input type="file" name="image_file" size="20"></p>
<p><input type="submit" value="Upload Image" name="action"></p>
</form>

The next step is to have something that actually shows what images are in the
directory. We can write a quick script that will iteratively go through images
directory and echo out what is there like this…

<?
$handle = @opendir("images");

if(!empty($handle))
{
while(false !== ($file = readdir($handle)))
{
if(is_file("images/" . $file))
echo ‘<img src="images/’ . $file . ‘"><br><br>’;
}
}

closedir($handle);
?>

Again, here is where the power of include comes in handy. We can provide a
direct link to our list_images.php, but we can also just include it in our
original upload.php This saves us from having to write it twice!

So at the bottom of our upload.php we can just include the include like this…

<?
//print_r($_POST);

if($_POST["action"] == "Upload Image")
{
unset($imagename);

if(!isset($_FILES) && isset($HTTP_POST_FILES))
$_FILES = $HTTP_POST_FILES;

if(!isset($_FILES[’image_file’]))
$error["image_file"] = "An image was not found.";

$imagename = basename($_FILES[’image_file’][’name’]);
//echo $imagename;

if(empty($imagename))
$error["imagename"] = "The name of the image was not found.";

if(empty($error))
{
$newimage = "images/" . $imagename;
//echo $newimage;
$result = @move_uploaded_file($_FILES[’image_file’][’tmp_name’], $newimage);
if(empty($result))
$error["result"] = "There was an error moving the uploaded file.";
}

}

include("upload_form.php");

if(is_array($error))
{
while(list($key, $val) = each($error))
{
echo $val;
echo "<br>n";
}
}

include("list_images.php");

?>

So far, our little application has been kept basic to emphasize the program flow
and not get bogged down in the details. But our next step is to enhance the
functionality of our gallery.

Come back soon as we continue this PHP project!

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured