Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
Uploading images to a website using PHP

Posted by JimL (JimL), 24 February 2004
I am trying to develop a website for a friend who knows nothing about HTML.

Therefore to make things easy for him, I am going to write the site in PHP and store his content in a MySQL database.

Using simple admin pages, he can type his content into textboxes, and this information can then be inserted into the MySQL database.  The PHP pages will then automatically assemble his content from the MySQL database into the main structure of the webpages.

Fairly simple, and I know how to do this.

However, how can I handle his images?

Ideally I would like to write a script which would upload his images from his harddisk to the webserver. The PHP pages would then read the contents of the "images" folder on the webserver and insert the appropriate code into his web pages automatically.

Can PHP do this? Can it do the job of FTP? Can it read the contents of the "images" folder on the webserver? What about logins to get access to the web space on the webserver?

Alternatively is it possible to store the images in the MySQL database and somehow access them from the HTML code? (This sounds extremely unlikely to me).

Cheers,  Jim

Posted by admin (Graham Ellis), 24 February 2004
Yes - you can do this with PHP.

I have some sample scripts back in the office; I'll be there towards the end of the week and I can post a follow up then.  Please let me know if you find an example elsewhere in the meantime  

Posted by JimL (JimL), 25 February 2004
Excellent!

I'll look forward to seeing them!

Just to make the problem one stage harder, his photos will be quite large (they are shots taken during motor races). Could PHP be able to manipulate those images to produce thumbnails?

Cheers,  Jim

Posted by admin (Graham Ellis), 5 March 2004
Hope to have a full answer / sample here within the next 24 hours - will answer you on "thumbnails" too but that one's not so straightforward!


Posted by admin (Graham Ellis), 7 March 2004
Sample code to upload an image - tested and it works!

Code:
<head>
<title>Simple file upload script</title>
</head>
<body>
<?php
if ($_REQUEST[completed] == 1) {
       $source = "demo";
       move_uploaded_file($_FILES['filename']['tmp_name'],
               "../$source/".$_FILES['filename']['name']);
// Following code to fix line ends
       if (! eregi ('(gif|jpg|pdf)$',$_FILES['filename']['name'])) {
       $fi = file("../$source/".$_FILES['filename']['name']);
       $fi2 = fopen("../$source/".$_FILES['filename']['name'],"w");
       foreach ($fi as $lne) {
               $n = rtrim ($lne);
               fputs ($fi2,"$n\n");
               }
       }
//
?>
Your file has been uploaded.
<?php } else { ?>
This page allows you to upload a file to the demo directory on our
server.<br><br>
<form enctype=multipart/form-data method=post>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
Choose file to send: <input type=file name=filename> and
<input type=submit></form><br>
<?php  } ?>
</body>
</html>


Notes:

One page to both provide the offering form, and also to do the upload.  

All files that are likely to be ASCII are "fixed" for Unix to Windows and vice versa line ends.  

Limit applied to file upload size

Encoding type

You need to be VERY CAREFUL what you allow people to upload - this script is NOT on our live server

Posted by admin (Graham Ellis), 7 March 2004
On Thumbnails ... I learn something new every day.  There's a function called imagecopyresized (and another called imagecopyresampled) that will do the job for you - see the PHP manual pages for details.   Here's a sample piece of code I used to test with

Code:
<body>
This page resizes ie.jpg and generates thumb.jpg
<?php
$out = ImageCreate(72,150);
$in = ImageCreateFromJPEG("ie.jpg");
$white = ImageColorAllocate($out,255,255,255);
ImageCopyresized($out,$in,0,0,0,0,72,150,144,300);
ImageJPEG($out,"thumb.jpg");
?>
<hr>
<img src=ie.jpg> <img src=thumb.jpg>
<hr>
Done!
</body>

and you can run it and see a thumbnail via http://www.wellho.net/demo/thumb.php4

Posted by JimL (JimL), 8 March 2004
Fantastic!

I'll heed your warning and make sure that the upload script is restricted only to the owner of the website.

Regarding the thumbnails, I'll give that script a test too!

Thanks very much!

Cheers,  Jim



Posted by Razit (Razit), 2 January 2007
Hello.

I started writing PHP and using MySQl fairly recently and have no prior experience in programming other than HTML, so my knowledge and understanding of it is still very limited.

Before I continue, I'd like to thank you for this site. I only just found it two days ago, but so far it has been far greater than most other I've found, which has been either too old or too complicated for a beginner.


I found your scripts for image upload and dynamic viewing, both this one and the one found at http://www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html

I did manage to get that one working, but it does not do exactly what I want it to do, and I can't figure out a way to change it. I tried this one as well, but I couldn't even get it to work.

What I want it to do is simply to enable me to upload images, and then display not only the latest one but all the others, as well. A fairly simple idea, but not quite as simple to execute on my level of expertise, which is basically far below where you can start saying you have a level of expertise.

Currently, my version of your script looks like this:
Code:
<?php

// Insert any new image into database

if ($_REQUEST[completed] == 1) {
       // Need to add - check for large upload. Otherwise the code
       // will just duplicate old file ;-)
       // ALSO - note that latest.img must be public write and in a
       // live appliaction should be in another (safe!) directory.
       move_uploaded_file($_FILES['imagefile']['tmp_name'],"../image/latest.img");
       $instr = fopen("../image/latest.img","rb");
       $image = addslashes(fread($instr,filesize("../image/latest.img")));
       if (strlen($instr) < 149000) {
               mysql_query ("insert into uploadedImages (title, imgdata) values (\"".
               $_REQUEST[whatsit].
               "\", \"".
               $image.
               "\")");
       } else {
               $errmsg = "Too large!";
       }
}

// Find out about latest image

$gotten = @mysql_query("select * from uploadedImages order by pid desc limit 1");
if ($row = @mysql_fetch_assoc($gotten)) {
       $title = htmlspecialchars($row[title]);
       $bytes = $row[imgdata];
} else {
       $errmsg = "There is no image in the database yet";
       $title = "no database image available";
}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
       header("Content-type: image/jpeg");
       print $bytes;
       exit ();
       }
?>


And the form:

Code:
<h2>Latest image uploaded:</h2>
<font color=red><?php echo $errmsg ?></font>
<center><img src="?gim=1" width=144><br />
<b><?php echo $title ?></center>
<br />
<br />
<hr />
<h2>Image upload</h2>
<form enctype=multipart/form-data method=post>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
<table class="content">
<tr height="10">
<td align="right" width="100" height="10">Image to upload:</td>
<td height="10"><input type=file class="post" name=imagefile /></td>
<td width="10" height="10"></td>
<td rowspan="3" valign="top">This part of the project is still on a very experimental stage, and because of this only JPEG's are allowed to be uploaded, and they cannot exceed 149Kb.</td>
</tr>
<tr height="10">
<td align="right" width="100" height="10">Title:</td>
<td height="10"><input name=whatsit class="post" /></td>
<td width="10" height="10"></td>
</tr>
<tr>
<td width="100"></td>
<td valign="top"><input type=submit class="blue" value="Submit" /></td>
<td width="10"></td>
</tr>
</table>
</form>



(I chose to leave out the connecting part, but there is one, so don't bother with that part)
What I would like now is a document that don't use the latest.img but is capable of viewing the last uploaded picture and uploading new ones, and another that displays every image in the database.
How would I go about to create that?

Posted by admin (Graham Ellis), 2 January 2007
You may have noticed that the article you referred to links to a running script which shows you the three latest pictures.   We publish the source code of that here and it should give you some pointers.

A slightly more complex example - allowing you to search our database of images that are in our own MySQL database - is available too - source code and you can also try it out here

There are also further examples under "using MySQL and PHP together" here

Thanks for your comments ... this particular topic is quite a difficult one, as you need to use a lot of technologies in quite a short script, and if it doens't work it won't always be too easy to find out what's going wrong.


Posted by Razit (Razit), 2 January 2007
Thank you, you have given me a lot to read through and try out.

I'll give it a go  

Posted by Razit (Razit), 2 January 2007
Just one more question for now...

How would I set up the database table to work with the code found here? :
http://www.wellho.net/resources/ex.php4?item=h113/picclim.php

Posted by admin (Graham Ellis), 3 January 2007
Excellent question - a vital piece of information for the example  

Here's the table description off the live table:

Code:
mysql> describe im_library;
+------------+----------+------+-----+---------+----------------+
| Field      | Type     | Null | Key | Default | Extra          |
+------------+----------+------+-----+---------+----------------+
| iid        | int(11)  |      | PRI | NULL    | auto_increment |
| filename   | text     | YES  |     | NULL    |                |
| imgdata    | longblob | YES  |     | NULL    |                |
| descriptor | text     | YES  |     | NULL    |                |
+------------+----------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

mysql>


So to create the table (from, say, a mysql client) you would use

Code:
mysql> create table im_library (
   ->      iid int primary key not null auto_increment,
   ->      filename text,
   ->      imgdata longblob,
   ->      descriptor text);
Query OK, 0 rows affected (0.02 sec)


The same command could be coded into a script, the table could be created through phpmyadmin or another tool ...

Posted by Razit (Razit), 4 January 2007
Quite often when I try out a script of this kind (I now have four or five different ones I am trying out or just trying to get it to work) I get a blank white page with the adress of the script - like this:  websiteroot.com/directory/script.php  - instead of any result.
Can you by this alone give a clue or three what might be wrong?

An example of a piece of script:
Code:
$query = "select * from uploadedImages order by pid desc limit 3";
$result = mysql_query($query);
for ($i = 0; $i < mysql_num_rows($result); $i++)
{
     $image = mysql_result($result, $i, "imgdata");
     $title = mysql_result($result, $i, "title");
     header("Content-type: image/jpeg");
     exit();
}


Posted by admin (Graham Ellis), 5 January 2007
Sounds like you have some odd error settings and your code might be outputting something before the header.   Unless you have a syntax error in your code reproduced below, the clue will be elsewhere.  Does your <?php start on row 1, colum 1 of the script?   A single space or a blank line in front of it could be the cause.

Posted by Razit (Razit), 5 January 2007
No spaces, no new lines. The <?php tag starts right away.

I just remembered another piece of code that gives that result; the piece of your feeder script that should get the filename.
I'd really like to get that part working, and I hoped that this might help further?

Code:
<?php

$error = 0;
$image = $_REQUEST[image];
$filename = "$image.jpg";
if (preg_match('/^-A-Z0-9_/i',$image)) {
     $error = 1;
} else {

if (file_exists($filename)) {
     $instr = fopen($filename,"rb");
       $imagebytes = fread($instr,filesize($filename));
       echo $imagebytes;
       }
      }
?>


Posted by admin (Graham Ellis), 5 January 2007
Perhaps you're using an extension that isn't configured to be processed through PHP?  And that latest script will certainly need a header(...) added.

Posted by Razit (Razit), 5 January 2007
Yes, very true. The script that I posted doesn't even work, it has the header(Content-Type: image/jpeg) missing.
Extension is *.php...

I don't know, maybe this is the kind of thing that can't be solved just like that over a forum. Or maybe it is, only I don't give the right information.
Oh yes, I forgot to mention that it seems to be every time I add the header info that it does the blanky. The only time it doesn't is in the first script I talked about and posted.

Posted by admin (Graham Ellis), 5 January 2007
It's probably one of those things I would spot when I saw the system and it would be easier in real life.   But looking at the IP address you're posting from, you're not living nearby to pop over, are you?

One of the next tests I would do at this stage is to browse the URL that's giving the problem via telnet - cut out the browser - so that I could see more about what's really happening. Is that a technique you've come across?


Posted by Razit (Razit), 5 January 2007
Uhm... no, not really. Not unless you're prepared to pop on a plane first. I'll just have to try and solve it as best I can by experimenting with what you have suggested  

I have heard of it, certainly, but never actually used it, or even got a good grasp of exactly what it does. I use a client  to connect to my server via SSH, which I have been told is something similar, but that is as far as my knowledge goes.
Could you perhaps give a suggestion of a good client to use?

Posted by Razit (Razit), 5 January 2007
Actually, I think I'm on to the problem now, I just can't figure out a solution.
The thing is that most of these scripts have been put on pages with a lot of html in them as well. Usually that isn't a problem, but whenever I try to put in a header(...) in the script it starts acting up in the way I desribed. I tried a number of different ways to output the html now, and nothing seems to work.
Here is the full code of a page (or at least one of my attempts at it) with a script that I know work without any html, but as soon as I put it in it does the blank page instead (am I wrong in supposing that the headers collide in som way?):

Code:
<?php

   $cur_img = $_REQUEST[gim];
   header("Content-type: image/jpeg");

?>
<html>

     <head>
           <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
           <link href="../styles.css" type="text/css" rel="stylesheet" media="all" />
           <title>A clever thing to say</title>
     </head>

     <body>
<div class="bg_color">
<div id="menu">
     <div id="menu_content">
           <span class="inset"><a href="../index.php">Main page</a><a href="../postform.php">Submit a post</a><a href="../talk.php">Talk</a><a href="../upses/imgae_ups.php">Up an image</a><a href="../upses/three.php">View images</a></span>
     </div>
     <div id="menu_contact"><a href="../contact.php">Contact</a></div>
</div>
                 <div class="roundbottom">
                       <div class="r5"></div>
                       <div class="r4"></div>
                       <div class="r3"></div>
                       <div class="r2"></div>
                       <div class="r1"></div>
                 </div>
                 <div class="roundtop">
                       <div class="r1"></div>
                       <div class="r2"></div>
                       <div class="r3"></div>
                       <div class="r4"></div>
                       <div class="r5"></div>
                 </div>
<div id="header">
     <div id="header_content">
           <div style="display: block; z-index: 1; visibility: visible; position: absolute; margin-top: -15px; margin-left: 185px;">
                 <span style="font-family: georgia; font-size: 35pt; color: #eee; font-weight: bold;">A clever thing to s</span>
           </div>
           <div style="display: block; z-index: 2; visibility: visible; position: absolute; margin-top: 10px; margin-left: 110px;">
                 <span style="font-family: georgia; font-size: 30pt; color: #bbb; font-weight: bold;">A clever thing to say</span>
           </div>
           <h1>A clever thing to say</h1>
     </div>
</div>
                 <div class="roundbottom">
                       <div class="r5"></div>
                       <div class="r4"></div>
                       <div class="r3"></div>
                       <div class="r2"></div>
                       <div class="r1"></div>
                 </div>
                 <div class="roundtop">
                       <div class="r1"></div>
                       <div class="r2"></div>
                       <div class="r3"></div>
                       <div class="r4"></div>
                       <div class="r5"></div>
                 </div>
     <div id="body_content">
           <div class="content">
<?php
       $query = mysql_query("SELECT * FROM uploadedImages WHERE pid = $cur_img");
       if (! $query)
       {
           echo "Couldn't select an image; either the database is empty or the reference is broken.";
       }
       else
       {
             if ($row = mysql_fetch_assoc($query))
             {
                   $img = $row[imgdata];
                   
                   echo $img;
                   exit ();
             }
       }
?>

     </div>
</div>

                 <div class="roundbottom">
                       <div class="r5"></div>
                       <div class="r4"></div>
                       <div class="r3"></div>
                       <div class="r2"></div>
                       <div class="r1"></div>
                 </div>
                 </div>
     </body>

</html>



Do you have any thoughts on that?

Posted by admin (Graham Ellis), 6 January 2007
Ah!

A URL can serve out either an image, or a piece of HTML and not both, at a single call.  You need to use two different URLs or, you could if your're clever about it, use the same page name with different parameters.

In the HTML output, include an img tag with the src pointing to the second URL.

Posted by Razit (Razit), 6 January 2007
Thanks!
After a little bit of trixing around I made it work.
Now maybe I can make some of my other attempted scripts work as well!

I have yet to make your feeder.php script work, though  But that's another story; I'm not entirely sure my server is correctly configured for it.

Again, thanks for the help!



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2024: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho