Images Are Just Files PHP Help

The big glaring omission in your work with users is that pesky pr~file image that you worked. You probably remember that the user’s profile is pretty incomplete right now. The difference between your mock-up from that and where your actual code is easy to spot: it’s all in that image

Images Are Just Files

Images Are Just Files

Images Are Just Files

Images Are Just Files

To place a user image on the page, turn to the good old HTML <img> tag:

<img src=”images/ darvish.jpg” class=”user_pic” />

The value of the are attribute is a reference to a file, although you don’t have any image files yet. You have the user’s name and information in your user”, table, but there’s no image on your web server to which you can point. You need both a file and then a reference to that file.

It’s a new PHP challenge: how do you get something other than text information from a user, and then what do you do with that information once you have it? (For more information on how files appear to PHP, see the box .)

Files, File Systems, and Client Versus Server

This might be the first time you’ve needed to get a clear understanding of the difference between what’s on your user’s computer and what’s on the web server. You know what a file is: it’s just a collection of bits and bytes that your computer knows how to handle. Your scripts, HTML,(SS, and JavaScript are ultimately just text: characters strung together. and interpreted by a web browser or the PHP program. In the case of PHP, your web server (and specifically, the PHP interpreter interacting with your web server) interprets that PHP,turns it into HTML,(SS, and JavaScript for your browser, and then lets the browser take over. For the browser, it takes HTML,(SS, and JavaScript-whether in a static file or returned
by a web server that’s processor a PHP script-and renders those to your user’s screen Images, on the other hand, are binary data. The same bits and bytes that make-up your text files are used to indicate location and color of pixels. You need a different type of interpreter to read a binary file. Fortunately, web browsers are perfectly capable of taking an image file-be it a JPEG(jpg), GIF(o;!),or PNG and displaying it. Still, the process of getting a binary file is a bit different.

When users type the URL of your web application into their browser, they’re running your program, which resides on a web server, somewhere, and is available via the Internet. They’re running that program by using their web browser, which is a program that resides on computer. There’s a big difference between what’s on their computer, and what’s on your web server. Your web server can’t reach into their computer and grab images, for example. The users-if they want to see one of their images in your program-have to upload that image to your web server. Your web server stores that image and can display it to whomever needs to see it. Of course, most users don’t know how to upload a file by using a program like FTP.It’s up to you to get their file from their computer onto your file system. A fite  is just a fancy word for the collection of files on your web server. It can also refer to the files on a user’s computer.

Put another way, the user’s computer is a (iii:!it-a computer that’s accessing your program. Your program runs on the .eve. This relationship is called a interaction.

Your job is to get an image file from the client to the server. Then, your server can give your PHP scripts access to that image file to be used in your programs (and, most important, in the user profile ).

HTML Forms Can Set the Stage

In this situation, your HTML is critically important to your PHP program. You need to ensure that the HTML form with which your user is working is set up correctly. Not only does that form need to give the user a place to select an image, but it needs to set up the process by which that image is uploaded correctly.
in which you’re working now. Here’s where you left things;
HTML Forms Can Set the StageThe key parts here are the enc type attribute on the dorm> tag, and input type= “file” for the user_pic. This code configures the form to upload not just text but also a binary image file.

Figure 9-3 shows that the user can already select an image now. But, there’s something else this HTML needs: a size limit on the image. At one time or another, you’ve probably received that email from a friend that has a 22 MB picture of a cat blown up to 100 times its normal size, right? You want to avoid that in your forms. a single MB or two is plenty for any reasonable profile picture.

You can limit the size of an uploaded file by adding a hidden input element, and give it the name “MAX_FILE_SIZE.” For the value, set it to the maximum size of the uploaded image you’ll allow, in bytes. If you want to allow a 1 MB image, that’s 1,000,000 bytes. Here’s the HTML to permit a 2 MB image:

HTML Forms Can Set the Stage

The form doesn’t look any different with this input element, but now you’re ready

FIGURE 9-3

FIGURE 9-3

Try this out: select an image and then click Join the Club. Even though there’s no PHP script waiting to receive this information, you’ll see your browser slowly uploading something.a bit by indication of how the upload is progressing.

FIGURE 9-4

FIGURE 9-4

Uploading a User’s Image to Your Server

It’s time to grab that image and do something with it. Start by copying your old version of create user out: into your current directory. Your script should look like this

Uploading a User's Image to Your Server

Uploading a User’s Image to Your Server

SET UP SOME HELPER VARIABLES

First, you need to add some basic information that you’ll use for getting at the file, and for storing it.

One new element is HOST_WWW_ROOItTl.books a bit like the SITE_ROOT you defined in

SET UP SOME HELPER VARIABLES

HOSTWWW_RooT hasn’t been defined yet. Right now, you have a SITE_ROOT,which is the web-specific path to your site’s root, so if your website is hosted without any directory prefix, your SITE_ROOT is probably just”: If you’re running within a L directory, for example, your site root might be· The takeaway here is that the SITE ROOT is defined in terms of what a web server and a browser connected to that server see

But what the browser sees isn’t the complete (or absolute) path to that file on your host’s server. A hosting server has tons of directories and sub-directories. Your directory, for example, might be  and then within there, you might have a ‘,T’ . or =u: -r» directory. It’s in that directory that your web files reside.

What this means is that your SITE_ROOT maps to a different path-on; in terms of what your host’s file server looks like-that represents the absolute path of a file. Here, you’re calling this new constant that path to ‘!X)

SET UP SOME HELPER VARIABLES

Of course, your HOST_WWW_ROOwTill look different than the one  this example. If you’re unsure how to get this path, see the box on page 263. You’re using this root-and not SITE_ROOT-because the process of uploading and moving around files is going to involve your host’s file server, not the browser. The uploaded user file is going to be stored on the host’s file system, so you must deal with paths with respect to your host’s file system. The browser will eventually show the file, at which • point SITE_ROOT will come back into play. However, the upload process has nothing to do with what the browser sees. You need to look at things from the file system’s perspective, which is just the sort of base path that HOSTWWW_ROOprTovides.

Create that directory on your web server by using a terminal shell, command-line tool, or your FTP client. lf your

Just as users can type the wrong information into your text fields, they can mess things up when uploading an image. Time for some error handling. The next variable- $php_errors-adds an array of potential errors:

SET UP SOME HELPER VARIABLES

You’ve used arrays before, but there’s something new about this one. You’re creating a new array by using the array keyword and then defining the values that go in that array.

SET UP SOME HELPER VARIABLES

SET UP SOME HELPER VARIABLES

Because an array is basically a list of values, you could do something like this just
as easily:

SET UP SOME HELPER VARIABLES

In this array, each value is automatically numbered, starting at O. Thus,  php_ errors [a} has the value “Maximum file size in php.in exceeded”, for instance.

So, what are those numbers and funny arrows (=»? They’re there because PHP arrays are c15S(y”I”‘[i.e an avs, That’s why you can say, for example, $_REQUEST [ , user_pic’ ]. The $_REQUEST array doesn’t just have values, it also has an dissociation between those values (the information in an HTML form, usually) and the name of the fields in which those values appeared. You can think of the mapping between the field name user_pic and the value of that field-something like {Jioflfe_pic.jI)Q, for example-as being defined like this:

SET UP SOME HELPER VARIABLES

Going back to your array of PHP errors:

SET UP SOME HELPER VARIABLES

In this case, you’re taking numbering into your own hands, rather than letting PHP define its own numbers. As such, sphp errorsj i] is now “‘Maximum file size in php.in exceeded rather than letting PHP’s zero-based numbering assign that string’s value to $php_errors [0].

Tampering with PHP’s numbering is generally a bad idea because you’re changing behavior that all PHP programmers expect. In this case, though, it’s for a worthy cause. That’s because PHP does more than give you a $_REQUEST array. When there are files involved, it gives you a $JI LES array. That array, just like $_REQUEST is, keyed to your field. Thus, $_FI LES[$image _field name] is associated with the image uploaded (hopefully) from your form. (Remember, you defined $image_field name nearer the top of Furthermore, $FILES[$image _field name] is itself an array, with information about the uploaded file, and any errors that might have occurred in the process. One of those pieces of information is $FILES [$image _field name][ ‘error ‘]. This field returns a number: 0 for “Everything went OK,” and non-zero for problems. Those non-zero numbers are none other than:

SET UP SOME HELPER VARIABLES

You can see why renumbering the $php_errors array makes sense: you’ve got a map of error codes that $FILES [$image _field name] [ , error’ ] might return, and the human-readable errors that go with them. At this juncture, you’ve got all the information you need; time to start using it.

DID THE FILE UPLOAD WITH ANY ERRORS?

Next, you need to check that $ FILES[$image field name][‘error’] piece of the $FILES array and see whet-er any errors occurred. If the value is non-zero, something went wrong, and you need to handle the problem. Luckily, you have a handy-dandy function for just that: handle_error.

SET UP SOME HELPER VARIABLES

If the error field ($FILES[$image _field name 1[ ‘error’ 1) is zero, things are great; just keep going. If it’s non-zero, you want to show your user an error, using the error code to look up the exact problem in your $php _errors associative array-and display that, too, if debugging is on

There’s also a new wrinkle in here that you might have just skipped right over: This line is basically an if statement without the if. PHP will evaluate the following line:

SET UP SOME HELPER VARIABLES

If that line is true, it will continue. If the line isn’t true, it runs the or part of the code on the next line; in this case, that’s handle_error. Essentially, the preceding example does the same thing as the following cod-e:

321 DID THE FILE UPLOAD WITH ANY ERRORS.

But the code without the if is shorter and cleaner. Every bit helps. This is a nice trick to add to your growing PHP tool kit. You can check your code out in action at this point. Visit create__user.ntmi and find an image file that’s bigger than 2 MB. Photos that come straight from your camera are likely to be large. (If you’re on a Mac, you can export a full-size photo from iPhoto.) Select that image and then try and submit your form. You should see something like Figure 9-5. This page is the result of your code finding an error code, and that error code being matched up to an error in $php_errors-in this case, your image was larger than your HTML file allowed.

DID THE FILE UPLOAD WITH ANY ERRORS

DID THE FILE UPLOAD WITH ANY ERRORS

Breathing and Sleeping Matter

Any good programmer will tell you stories of at least a few all-night hacking sessions. And odds are, those stories will be tinged rosy. full of victories and excitement. But the truth of the matter is that fatigue slows the brain down, and no programmer is aseffective on two hours of sleep as he is on six.

Why is this relevant? Because a tired brain isn’t as useful as a rested one. And, because if you’ve been swimming in the pool of PHP programming for eight chapters before this one. by now you’re well into the deep end. Chancesare that you’re having to read at least a few things twice, and some of this new code introduces not just one or two new things, but three, or four, or five. There’s nothing at all wrong With this, but if you’re getting worn out, nobody wins by you plowing ahead. Take a few hours off, ride your bike, jog a mile, or just set PHP aside for the night. You’ll be stunned at how much clearer things seem after a bit of rest from programming. Don’t think that rest and taking a few moments to breathe out of sight of the keyboard are a Sign of  weakness; in fact, it’s just the opposite.

IS THIS REALLY AN UPLOADED FILE

At this point, despite whether you have a real file, what your program needs to work with is a file. That name is controlled entirely by what your users put into their file input box. This means that if a user is tricky, malicious, and thoroughly dishonest, he might try to put in a file name that does upload a file on the host provider’s system, but also just so happens to match one of the special files on web servers

that control things like, say, the user passwords (that file is usually You need a ‘way to stop that from happening. (More PHP books and tutorials than you can imagine leave this step out, but it’s critical.) You might think you’re about to use regular expressions and check for all kinds of fancy file name characters, but there’s an easier way. PHP gives you a function called is _uploaded _file whose purpose it is to ensure that for a given name, that name references a file uploaded with HTTP (the language of web browsers and HTML forms). In other words, if the supplied name targets a file on your web server, this function will return false, and you know that something’s fishy. Here’s what you want to do:

IS THIS REALLY AN UPLOADED FILE

This code uses another property of $FILES[$image_field name): the temporary name of the file. This gives you the name of the file as it currently stands and lets you make sure it’s an uploaded file. But, there’s a problem here: is_uploaded _file fires off an error if the file isn’t uploaded. That sounds good, except that you’ve done a lot of work to handle errors your own way. You don’t want is_uploaded _file to generate an error; you just want its return value, even if there’s a problem. You can instruct PHP to run a function but suppress errors by inserting the @ character directly before the function, and that’s exactly what you need here:

IS THIS REALLY AN UPLOADED FILE

If there’s a problem when the function runs, handle_error takes over, rather than your script throwing out some unintelligible error of its own. You’ve avoided a nasty security hole. One more hacker thwarted.

Suppress Errors at Your Own Peril

There’s perhaps no more intriguing operator in PHP than @. With one keystroke, all the problems that might come about from a user entering invalid data, or a Sol-query having an incorrect column, or even just a poorly formed URL can be banished. Your code can continue without having to check for every possible mistake your users, you, and your code might make …and that’s a lot of potential mistakes. But @is an atomic bomb waiting to turn your code into a smoldering slag heap. Use it frequently, and you’ll quickly find that your code is riddled with potential problems. You’ll never be sure if your problem is something your user did, something you did, or a legitimate bug you  need to fix. Regardless of wilt’s causing the error, if you snick around it with @,you have a legitimate bug. Make a rule for yourself: when you use @(as in the very next line), pair it with a~ or ~ and explicit error handling. You’ll be much better off for the discipline. But-there’s always a but, isn’t there?-high-volume, production websites often use @because they simply c;or crash or stop working. In those cases, you should usually go with some sort of hybrid solution. On the one hand, use@, but then pair it with or  that is triggered by a flag, like your debugging mode flag (page 238). Thus, in “normal” mode, things run without spewing tons of errors (or perhaps by on-lye logging those errors). Then, by flipping on debugging mode, you can see what’s really going on and track down problems and fix them.

IS THE UPLOADED FILE REALLY AN IMAGE?

You have a file uploaded, and you know it’s not some fake file that has a name that points at a protected file on your server’s file system. It’s finally time to move on and show the image, right? Well, unfortunately, not quite. You have a file, but is it an image? There’s nothing preventing a user from .accidentally uploading a Word document, or a malicious user uploading some JavaScript or an executable file. Remember, you can’t assume that your users are going to do the right thing. Thankfully, PHP offers the legitimatize function, which checks the size of a given image file. And, best of all, this function kicks out an error if what it’s evaluating is a non image file. Add the following function to your script:

IS THE UPLOADED FILE REALLY AN IMAGE

IS THE UPLOADED FILE REALLY AN IMAGE

MOVE THE FILE TO A PERMANENT LOCATION

You’re almost to the big finish .•You have a valid HTTP upload that’s an image. All that’s left is to move this image from the temporary location that browsers use for uploaded files to someplace permanent. Here’s where your image _field name variable

MOVE THE FILE TO A PERMANENT LOCATION

At this point, it’s important to understand what’s happened to your user’s uploaded file. When the server uploads this file, it uses a preconfigured location. It’s also likely to use a name that isn’t identical to what the user’s file was originally called. Sometimes the name is completely changed; other times something is prepended (added before it) or appended to it. Additionally, the file isn’t in a place you want to leave it. It’ll often be stuck into some sort of temporary storage, and that storage is probably cleared out every so often. You need to not only assign the file a name, but you also need to move it somewhere more permanent-for that, you can use $upload _dir. There are lots of different approaches to naming a file. You could come up with something related to the user who uploaded the file, but often, ,i.t’s just easiest to give the file a unique numeric name. And the easiest way to do this is to create the name based on the current time-a near surefire way to end up with a unique file name.

Once you create a unique name, you can finally move the file from its current location to a permanent one. First, figure out a name for the soon-to-be permanent image:

MOVE THE FILE TO A PERMANENT LOCATION

Here’s the step-by-step breakdown:

1. Create a new variable called $now and assign it the current time by using .PHP’s time function

2. Start a loop by using while.This instructs PHP that while a certain condition is true, keep doing the loop. As soon as that condition;” true, stop loopin

3. As part of the while condition, assign a value to $upload_file name: the $upload _dir plus the current time, a dash (-), and then finally the name of the original file. This is a combination of a part that will be unique (the time) and the original name of the user’s file (which is in $FILES [$image _field name 1[ ‘name’ j).

4. Complete the while condition by passing that calculated filename to file_exists. If that file exists, the while loop runs. If not, you have a unique file name, so the loop will not run (or, run anymore, if it’s already been looping).

5. Within the loop, you need to change the file name.Because the while loop is only going to run if you have a file name that’s already in use, just add to $now and try again.

Here’s the beauty of PHP: you can do all of that in just a few lines of code, and when this code completes, you’ll have a unique file name for the user’s file.NOW, move the file from its old temporary location to the permanent one:

Within the loop, you need to change the filename

Within the loop, you need to change the filename.

It’s been a lot of work, but you should finally have your file in a permanent location and you know that the file is a valid image. Your code should look something like this:

Within the loop, you need to change the filename

Within the loop, you need to change the filename

Within the loop, you need to change the filename

 

FIGURE 9-6

FIGURE 9-6

Now (finally’), you can click one of those file names, and you should get a glorious image uploaded from your computer to your web ever, as demonstrated in Figure 9-7.

FIGURE 9-7

FIGURE 9-7

Storing the Image Location in the Database

It’s taken some time, but you’re finally ready to save this image-or at least its location- in your database table. You already have a query built

Storing the Image Location in the Database

CREATE A NEW DATABASE COLUMN

All you need to do, then, is add a column in which you can store the image location. This is a matter of using the ALTER command something with which you’re already comfortable: ALTER_TABLE users ADD user_pie_path var char(200);

Run this statement to test it, and then DESCRIBE your users table just to make sure the change was applied:

CREATE A NEW DATABASE COLUMN

CREATE A NEW DATABASE COLUMN

This user tic _path field is just a text column. This is because all you’re storing is the pat~ to the image rather than the image itself.

INSERT THE IMAGE PATH INTO YOUR TABLE

The update to the INSERT query isn’t difficult at all, now:

INSERT THE IMAGE PATH INTO YOUR TABLE

Things are definitely starting to flow quickly. With all your existing work already in place, adding a new column is simple. But. before you dive back into your HTML, there’s one more thing that remains to be done.

CHECK YOUR WORK

Before you go any further, verify that things work. If you were just a PHP programmer, you’d have to try this code out and then either write a new script to select data from the users table, or jump right back into nonuser X)c. But why go to all that trouble? You know SOL and how to interact with My Sol.

First, create a new user, and use a name you haven’t used before. Then, jump back into your SQL command-line tool and check the results of your work for yourself. Just SELECT the user you just inserted, focusing on the picture path:

CHECK YOUR WORK

As you can see, the image is on your server, and now you’ve got the path to that image stored in your database. ! Ie v, you’re ready to show your users their glorious images. If you’ve had any issues, you might want to check out the completed version of – – ‘(0 i? ,-,11) that follows. There have been a ton of additions, so check that everyothing is right where it belongs:

CHECK YOUR WORK

CHECK YOUR WORK CHECK YOUR WORK

CHECK YOUR WORK

Images Are for Viewing

Finally! It’s time to show your users the fruits of all your hard work. They’ll probably never realize how long you slaved to get one single image showing up-and protecting all their other information in the process. Ensure that you have a copy of  alongside You need to update  to select the user’s picture path from the er: table and then display that picture.

Selecting the Image and Displaying It

This step turns out to be easy. First, you already have a SELECT that grabs everything for a particular user:

SELECTing the Image and Displaying It

Next, you can just add a line that grabs the image path in the code that you already have pulli”ng information out of the result of running this SQL INSERT:

SELECTing the Image and Displaying It

Be sure to remove this old code entirely:

SELECTing the Image and Displaying It

Finally. you already have a place in this script’s HTML that references the $user_image variable:

SELECTing the Image and Displaying It

Time to try things out again. Go to your page with an existing user’s 10 in the URL bar of your browser, or create a new user with a picture and let redirect you. You should see something similar to Figure 9-8. To figure out why you can’t see the image you uploaded, vi~w the source for this page, and see what path was used for the image. You’ll probably see something li)<eFigure 9-9 .

 

FIGURE 9-8

FIGURE 9-8

FIGURE 9-9

FIGURE 9-9

You checked earlier to ensure that this is a valid image (page 269). This time, check to see if the path to the image is causing the problem.

Converting File System Paths to URLs

Currently, you have a path on your web server’s file system (page 277) but what you need is a path that a web server recognizes. Remember the difference between SITE_ ROOT-which is a path from a web server’s perspective-and HOST_WWW_ROOT which is from the perspective of a server’s file system. That’s exactly the issue here: your script provides a path on the file system to the web server. Every web server has something called a acquirement ‘OC!’. That’s the directory into which you place files so that a web server and a browser can see them. That’s also the directory you’ve already identified in anp .._c()nri~rp!w with OSTJ’lv.JW_ROOT(page 263).

To establish what your document root is, close show user php and create a new script called tesr.,:’110. Type a single command between the opening and closing PHP syntax:

Converting File System Paths to URLs

$_SERVER is another one of those helpful associative arrays that PHP provides. The DOCUMENT_ROOT key reveals your web server’s document root.

Using a browser, go to this script. You’ll get something like Figure 9-10: that’s your document root. In this example, the root is  There fore, the web path! is mapping to the file system path

Now, you have the sort of hook you need: a mapping that relates a file system path to an actual web path. It’s a pretty easy mapping, too. For any file path, you want to strip away everything from the beginning of the path up to and including / I!C,,’ld9JlW(iia_, om (or whatever the end of your document root is). To put that into action, start by adding a sample image path that you’re currently storing in your database to your script:

Converting File System Paths to URLs

Next, use st  replace, a handy function you know quite well by now. You simply want to replace the file path equivalent of the document root with …well, nothing. You want to remove it:

Converting File System Paths to URLs

FIGURE 9-11

FIGURE 9-11

Take this path and drop it directly into your browser, following the slash after your domain name, and then press Enter. If all is well, you’ll see that image you’ve been after for so long. Figure 9-12 shows the magic in action.

FIGURE 9-12

FIGURE 9-12

At this stage, you can turn the code in :r;st r.l, ‘,) into yet another helpful utility function. Open up your old friend  and create a generic version of the code from

Converting File System Paths to URLs

Pretty streamlined, isn’t it? Here’s what this short bit of code does:

1. Defines a new function by using function that you can call from any script that requires or includes app config.php.

2. Names the function get_web_path.

3. Defines a single piece of information that the function gets from whatever script calls it: $file system path.This will be the complete path on the web server’s file system t~ the file that needs to be converted into a web-accessible path.

4. Takes $file..:system_path and replaces the document root in the path with nothing (‘ ‘).

5. Returns the result of running str_replace by using return.

The only thing new here is return. return is a part of the PHP language, and it does just what you’d expect: it returns something to the program or script that called this function. So, if you passed in usr /bbentley /web/images/profile. jpg, and your document root was the string images/profile .jpg would be returned from a call to get_web_path .

Prototype with Simple Scripts

Some languages and frameworks-Ruby on Rails, in particular- offer a means to run commands within the context of your programming or web environment. This is sort of like a command-line-plus, where you get all the benefits of a running web server, logging, your scripts loaded, and even a few additional bells and whistles.

Unfortunately, PHP isn’t one of those languages. When it comes to testing out a bit of new functionality, your choices are typically to either just start coding in one of your existing scripts or to create a simple script like test.php and work with it until you get your functionality figured Out.

Although using a simple command-line script can seem like a bit of a drag compared to a nice (SS-styled web environment, it’s often the better choice. You can test things and get your code just right without having to worry about HTML or interactions across scripts. Then, once you have your code the way you want it, it’s an easy drop-in to your full-blown web scripting environment.

 

Displaying Your User’s Image: Take Two

It’s time to turn back to show_ user.php. This time, though, you’re armed with a utility function. Use that function to convert the absolute path stored in your database into a web-safe path for viewing:

Displaying Your User Image Take Two

It doesn’t get much easier than that. Fire up your browser and try either creating a user again (with create_user php) or visiting show _user. php and supplying a user _id parameter as part of the URL string. You should see .show_user.php the way it’s always been intended:

FIGURE 9-13

FIGURE 9-13

Don’t Store Paths in Your Database

Every Single time you load an image from the database, you’ll have to call get _web _path on that image path-at least if you want to show the image on the Web. Given that you’re writing web applications, isn’t that sort of the paint? It might seem as though you could just cut that conversion step out and simply store the image in the database as a web path from the beginning.

There are a couple of reasons that’s not a great idea, though. First. an absolute path is just that: it’s absolute. Your web server software can change; your home directory can change; you can switch from PHP to Ruby to Perl and back to PHP; but short of you actually moving an image, its absolute path remains unchanged. Most importantly, you can change the entire document root of your site, and an a bsolute path will still work. Why is that so significant? Because you might need to change the document root of your site at some point. If you stored a web path in the database-a path related to your document root-and then your document root changed, all of your Image paths would be invalid. You’d have to change every single one of them from being relative to your old document root to relative to your new document root. What a mess.

On top of that, a web path is a relative path, even if it begins with a /. That’s because it’s relative to your document root. An absolute path is fixed in relation to a specific computer. regardless of that computer’s software. And as a general rule. you want to store things in a database that are as absolute and fixed as possible. Given the choice between a piece of information in an absolute form and one in a relative form, always go for the absolute form. It’s usually easy to change from one form to the other, so store the more “reliable” one.You won’t regret it.

And Now for Something Completely
Different

Everything works now. Your users can upload images. You can get those images securely into a permanent location of your choice. You have a way to store the location in a database and to convert that location into a URL that works with your website and your personal document root. And then, to top it all off, you can showy our users their images when they visit show_user.php So, what’s next?

Suppose that you’re using multiple web servers that share a Single database. Are you really going to store the same image on each of those web servers?

Or suppose you’re using a temporary computer for a web server, or think you might change to a higher-end hosting solution as your business expands. Do you want to have to copy not just your site-which might only be 10 or 20 MB zipped up+but all of your user’s images, each one perhaps 1 or 2 MB in size?

These are just a few reasons why the solution you have in place might not be the best one for your particular web application. And there is another option, equally
complex, but just as useful: you can store images not on the file system, but directly in your database.

This is one of the most common things you’ll encounter in programming: you’ve got a solution that works, but there might be a better solution around the corner. In this case, there’s a different solution, and it’s in the next chapter. So turn the page, and ” see why you might just want your entire image stored in the database rather than just the path to that image.

 

 

Posted on January 12, 2016 in Handling Images and Complexity

Share the Story

Back to Top