?
Solved

Php/ MySQL unable load blobs over the internet

Posted on 2009-02-08
33
Medium Priority
?
515 Views
Last Modified: 2013-12-12
I am trying to put up a web page whereby photographs may be uploaded over the net.
The code works  through the browser on my computer at home - My home computer and my server run on the same systems.
The database on my server will accept all input except the image (set at mediumblob),
The database shows input into each filed except the Blob.

On the otherhandt the database will accept the image if loaded normally (other than through the web)

The Warning message that I get is
Warning: filesize() [function.filesize]: stat failed for C:\WINDOWS\TEMP\php4E.tmp in C:\Inetpub\ftproot\LocalUser\Sean\Fikawe\tribalstuff\filestore.php on line 52

Warning: fread() [function.fread]: Length parameter must be greater than 0 in C:\Inetpub\ftproot\LocalUser\Sean\Fikawe\tribalstuff\filestore.php on line 52

Warning: Cannot modify header information - headers already sent by (output started at C:\Inetpub\ftproot\LocalUser\Sean\Fikawe\tribalstuff\filestore.php:52) in C:\Inetpub\ftproot\LocalUser\Sean\Fikawe\tribalstuff\filestore.php on line 66

There is no php4E tmp file, but I see other ones in the Windows Temp folder so I assume it is not there because it failed. The permissions on the temp folder seem to be normal.

I presume that the fread and the header warning are a result of the filesize() failure.

The php file I append below - renamed "Text.txt"

I would appreciate your assistance.
TEXT.txt
0
Comment
Question by:Misafi
  • 18
  • 12
  • 3
33 Comments
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23587280
Well, first of all, unless I am mistaken, you cannot use the syntax that you're using in many of your if() conditions.

You need to go through you code and anywhere that you're using an 'or' you should replace it with || and anyplace you're using an 'and' you need to replace it with &&

Perhaps that will clean things up enough for it to work for you.

Hope that helped
0
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23587320
Additionally, you're getting the following error;
Warning: Cannot modify header information - headers already sent by (output started at C:\Inetpub\ftproot\LocalUser\Sean\Fikawe\tribalstuff\filestore.php:52) in C:\Inetpub\ftproot\LocalUser\Sean\Fikawe\tribalstuff\filestore.php on line 66

because something above those header() functions is printing something out to the browser which forces the server to generate a default header even if what is being rendered to the browser is just a space. It counts enough as sent information for the server to feel it has to create default headers and thus when you use the header() functions, they will be trying to do what the server has already done ahead of time due to the existence of whitespace or an echo or print being performed.

Perhaps your database connection failed or something in the code prior to those header() function calls failed or is trying to print/echo something. Also, be 100% sure that you don't have any blank spaces or lines prior to your <?php opening tag.
0
 

Author Comment

by:Misafi
ID: 23587408
adrian_brooks - many thanks for your advice.
I shall certainly change the syntax as you suggested, but then, why is the code working perfectly well on my home computer when viewed in the browser yet not on the server?
As far as I can see all the conditions are the same.

I have recently had a problem with whitespace and headers (Question ID 24116913) and this was solved by your experts - the file was being saved in UTF format within the application -. I have overcome that particular issue, but now it seems that possibly the failure of one of these functions is inserting whitespace - Could that happen?

rgds

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 12

Expert Comment

by:Richard Davis
ID: 23587587
I am not entirely sure why it would work on your home system unless earlier versions of PHP used to allow for such syntax. My educated guess here about the syntax is that the PHP engine will allow it, but possibly not treat the and keyword the same as the ternary && symbol.

As for the header issue, yes...that is highly possible.

I cannot confirm this, but perhaps try prepending your mysql database function calls with the @ symbol as this will disable error reporting. Additionally, if this file is an included file in another php file...then it's entirely possible that that other file could also be the whitespace culprit.

Something like this, perhaps;
<?php
$dbcnx = mysql_connect('localhost', 'user', 'password');
@mysql_select_db('generaldata');
$action = '';
if (isset($_GET['action'])) $action = $_GET['action'];
if (($action == 'view' || $action == 'dnld') && isset($_GET['id'])) {
	$id = $_GET['id'];
	// User is retrieving a file
$sql = "SELECT FileName, MimeType, FileData FROM USERTABLE WHERE ID = '$id'";
$result = @mysql_query($sql);
if (!$result) die('Database error: ' .mysql_error());
$file = @mysql_fetch_array($result);

Open in new window

0
 

Author Comment

by:Misafi
ID: 23587678
Adrian_brooks
Many thanks - within the next hour I shall settle down and rewrite the code.
One thing I can tell you - if it helps
There are Five fields in the database
ID - Filename - MimeType - Description - FileData.
All the first four are populated when I run the enquiry
The last field - FileData (mediumblob) shows 0 - and of course the warning messages appear.
It has nothing to do with the size of the file I'm trying to upload because I have gone right down to 1kb.

rgds

0
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23587763
Okay...in your HTML form...I noticed that you don't have the required hidden tag that is needed for file uploads. Go have a look at this page to see what I am referring to.

http://us2.php.net/manual/en/features.file-upload.post-method.php

This is likely to fix your upload issue. As for the error messages, I will still attempt to hammer those out also.
0
 

Author Comment

by:Misafi
ID: 23587921
adrian_brooks
I have changed the form to the following
<form action="<?$_SERVER['PHP_SELF']?>?action=ulfile"
            method="post"  enctype="multipart/form-data">
      <p>Upload File: <br>
      <input type="file" name="uploadfile"></p>
      <p>File Description <br>
      <input type="text" name="desc" maxlength="255">
      </p>
<p><input type="hidden" name="MAX_FILE_SIZE" value="30000" /></p>
      <p>
      <input type="submit" name="go" value="upload"></p>
      </form>
This works without a problem on my home computer but not the server, where I still get the same response.
I still have not completed the re-coding as per your suggestions - let me do that - test it and then I will report back to you.

Many thanks
rgds
0
 

Author Comment

by:Misafi
ID: 23588001
adrian_brooks
OK - I've substituted || for "or" and && for "and". Works fine on my home computer but not on the server.
The initial page loads - the first 3 fields load into the db - but nothing into the blob field and the same wrnings appear as usual.

So - in essence - the advice that you have been giving me is accurate but there is something on the server that prohibits the image from loading into the  Blob field (and it's not necesarily an image - I have tried loading a text file with the same negative result)

rgds

0
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23588299
This line;
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />

HAS to be placed right after your form tag...like this;

<form action="<?$_SERVER['PHP_SELF']?>?action=ulfile"
            method="post"  enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />

But have a look at this example...what you're going to see is a better way to perform exactly what it is you want to do. You're sorta on the right track, but there's a few things that you're doing a bit wrong...pay close attention to the move_uploaded_file() function usage...this moves the file from the server's designated upload directory to a safe directory where you can then change the permissions on the image to 755 prior to processing if need be.

http://www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html
0
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23588319
This home versus server thing is bugging me.
1) What OS is your server running?
2) What version of PHP are you running on your server, btw?
3) What web server are you running?
4) Do you have administrative access to the webserver?
0
 

Author Comment

by:Misafi
ID: 23588427
Home
MS Windows Server 2003 for Small Business Server SP2
MySql Server 5.0
Php 5.1.2

Server
MS Windows Server 2003 Standard Edition SP2
MySQl Server 5.0.45
PHP 5.1.6

I see that the applications are not quite the same.

I have attached the php info files for the home and server setups
0
 

Author Comment

by:Misafi
ID: 23588436

sorry -
Herewith files

rgds
Serverphpinfo.pdf
Homephpinfo.pdf
0
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23588626
Misafi, I encourage you to try out the example I sent you in the link above.
With a little tweaking, it will do precisely what you are hoping to achieve.

Here's the link again;

http://www.wellho.net/solutions/php-example-php-form-image-upload-store-in-mysql-database-retreive.html
0
 

Author Comment

by:Misafi
ID: 23588681
I have just tried it.
This time the blob fails in both the home and Server setup but the interesting thing is that whereas before the filed showed 0
now it shows  ÿØÿà in each time a try to upload
Have we got a language issue her?

rgds

0
 

Author Comment

by:Misafi
ID: 23588723
Just to summarise with the wellho.net solution.
I have created a php named Ellis.php
Does it load up OK - yes except for his original jpgs which assume inconsequential
Does it create a table in the db  - yes
Does it create the fields  in the db - yes
Does it populate the fields - yes Except for the fact that the blob fields shows up in the db as ÿØÿà
Does it show the graphics on the page - No
Does it show any error or warnings - No - other than the usual gif sign denoting error in loading graphic.

So we are definitely getting somewhere

rgds
0
 

Author Comment

by:Misafi
ID: 23588812
Sorry - my last was misleading.
The blob does load in the server it does not show up on the web page but the jpg file is sitting in the db .
somewhere along the line it doesn't like  - fopen("latest.img","rb"); - but I can probably tweak that.

Now the home server is the problem there is no jpg file in the Blob field - only Martian swear words.

Seems to me that without a doubt I have a conflict with either my PHP or MySql releases.

rgds
0
 
LVL 12

Accepted Solution

by:
Richard Davis earned 2000 total points
ID: 23589263
The place I would start debugging would be to look in the C:\PHP\uploadtemp directory and confirm that the file is in fact saving properly there first. The next step would be to check the fopen & fread directories permissions. Be sure that both directories have read & write access for the IIS or Apache webserver user.

In Windows, I believe this is the IUSR_SOMETHING user.

It's entirely possible that the permissions are not permitting the file to be accessed properly.
As for the "Martian swear words" (totally had me cracking up with that line!!!), what I would do is try doing this instead of the fread stuff;

mysql_real_escape_string(file_get_contents("/path/to/this/file/latest.img"))

What this function will do is read the file's contents while passing it through that mysql function that will ensure that the data is database safe. I actually am using that exact line to build my INSERT statement for my database query and it works like a charm.

Side note recommendation for you though...you will increase performance both on your web server and your database server if you actually store the files on the hard drive and just store the names of the files in the database. You can then create a variable that will be the static path to the directory where the files are stored and make just the name of the file dynamically retrieved from the database. :)
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 23590142
@Misafi: Please consider an alternative to storing a BLOB in your data base.  Upload the images using the standard PHP mechanism and store them in the file system.  Put a pointer to the image into the data base.  If you put images into your data base, it will slow the thing down to a crawl and will be difficult to back up.  Not to mention the escaping and encoding issues that you're running into - those are unnecessary impediments to your progress!  Data bases are made for high-speed indexed data, and the file system is made for storing files of all sizes.

I would be glad to show you  an example of how I do this for my clients.  It is from a UNIX server, but the principles are applicable to Windows as well.

Standing by, ~Ray
0
 

Author Comment

by:Misafi
ID: 23590240
adrian_brooks
Sorry - this is where my ignorance really shows.

This is what I have after connecting to the db
>>>>>>>>>>>
CREATE;
@mysql_query($q);
// 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'],"latest.img");
        $instr = fopen("latest.img","rb");
        $image = addslashes(fread($instr,filesize("latest.img")));
        if (strlen($instr) < 149000) {
                mysql_query ("insert into pix (title, imgdata) values (\"".
                $_REQUEST[whatsit].
                "\", \"".
                $image.
                "\")");
        } else {
                $errmsg = "Too large!";
        }
}
// Find out about latest image
$gotten = @mysql_query("select * from pix 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";
        // Put up a picture of our training centre
        //$instr = fopen("Family1.jpg","rb");
        //$bytes = fread($instr,filesize("Family1.jpg"));
}
// If this is the image request, send out the image
if ($_REQUEST[gim] == 1) {
        header("Content-type: image/jpeg");
        print $bytes;
        exit ();
        }
?>
>>>>>>>>>>>>

Where do so suggest I should  place your recommended

mysql_real_escape_string(file_get_contents("/path/to/this/file/latest.img"))


I hear your recommendation to create a variable with a static path to another directory - but frankly that is well beyond my expertise.

rgds

Sean
0
 

Author Comment

by:Misafi
ID: 23590331
Ray_Paseur
Thank you - as you see from my last to adrian I am out of my depth and your help would be much appreciated.
I don't think that it would be fair to adrian or you for me to work both these queries together - although they are definitely linked.
Can I post another question that covers the database question?

rgds
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 23590415
Of course!  We are here to help.  Here is my standard "upload example" script.  I will look for your question, and I will post an example of the data base portion in response to that Q

Best to all, ~Ray
<?php // RAY_upload_example.php
// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php
// http://docs.php.net/manual/en/function.getimagesize.php
 
// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'uploads';
 
// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT
$max_file_size = '8192000';  // EIGHT MEGABYTE LIMIT ON UPLOADS
 
// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array('jpg', 'gif', 'png', 'txt');
 
// ESTABLISH THE NUMBER OF FILES WE CAN UPLOAD
$nf = 3;
 
 
 
// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$errors	= array(
	0=>"Success!",
	1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
	2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
	3=>"The uploaded file was only partially uploaded",
	4=>"No file was uploaded",
	6=>"Missing a temporary folder",
	7=>"Cannot write file to disk"
);
 
 
 
// IF THERE IS NOTHING USEFUL IN $_POST, PUT UP THE FORM FOR INPUT
if ( (empty($_POST['p'])) && (empty($_POST['MAX_FILE_SIZE'])) )
{
	?>
	<h2>Upload a file</h2>
 
	<!-- ENCTYPE -->
	<form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
	<input type="hidden" name="p" value="1" />
	<!-- MAX_FILE_SIZE must precede the file input field -->
	<input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
	<!-- INPUT NAME= IN TYPE=FILE DETERMINES THE NAME FOR ACTION SCRIPT TO USE IN $_FILES ARRAY -->
	<p>
	Find the file(s) you want to upload and click the "Upload" button below.
	</p>
 
	<?php for ($n = 0; $n < $nf; $n++)
		{
			echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
		}
	?>
	<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
	<input type="submit" name="_submit" value="Upload" />
	</form>
	<?php
	die();
}
else // WE HAVE GOT SOMETHING IN $_POST
{
 
// THERE IS POST DATA - PROCESS IT
	echo "<h2>Results: File Upload</h2>\n";
	echo "<p>\n";
 
// ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
//	echo "<pre>"; var_dump($_FILES);
 
// ITERATE OVER THE CONTENTS OF $_FILES
	foreach ($_FILES as $my_uploaded_file)
	{
 
// SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
		$error_code	= $my_uploaded_file["error"];
		if ($error_code == 4) continue;
 
// SYNTHESIZE THE NEW FILE NAME
		$f_type	= trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
		$f_name	= trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
		$my_new_file	= getcwd() . '/' . $uploads . '/' . $f_name .'.'. $f_type;
		$my_file	= $uploads . '/' . $f_name .'.'. $f_type;
 
// TEST FOR ALLOWABLE EXTENSIONS
		if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");
 
// IF THERE ARE ERRORS
		if ($error_code != 0)
		{
			$error_message = $errors[$error_code];
			echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
			die('Sorry');
		}
 
// MOVE THE FILE INTO THE DIRECTORY
		$overwrite	= $_POST['overwrite'];
		$file_size	= number_format($my_uploaded_file["size"]);
 
// IF THE FILE IS NEW
		if (!file_exists($my_new_file))
		{
			if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
			{
				$upload_success = 1;
			}
			else
			{
				$upload_success = -1;
			}
 
// IF THE FILE ALREADY EXISTS
		}
		else
		{
			echo "<b><i>$my_file</i></b> already exists.\n";
 
// SHOULD WE OVERWRITE THE FILE? IF NOT
			if (empty($overwrite))
			{
				$upload_success = 0;
 
// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
			}
			else
			{
				$now	= date('Y-m-d');
				$my_bak = $my_new_file . '.' . $now . '.bak';
				if (!copy($my_new_file, $my_bak))
				{
					echo "<b>Attempted Backup Failed!</b>\n";
				}
				if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
				{
					$upload_success = 2;
				}
				else
				{
					$upload_success = -1;
				}
			}
		}
 
// REPORT OUR SUCCESS OR FAILURE
		if ($upload_success == 2) { echo "It has been overwritten.\n"; }
		if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
		if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }
 
		if ($upload_success > 0)
		{
			echo "$file_size bytes uploaded.\n";
			chmod ($my_new_file, 0755);
		}
 
		echo "</p>\n";
		echo "<p><a href=\"$my_file\">See the file</a></p>\n";
// END ITERATOR
	}
}
?>

Open in new window

0
 

Author Comment

by:Misafi
ID: 23591076
Ray_Paseur
Question posted.


adrian_brooks - I hope that you are happy with that - I am finding your input invaluable and do not wish to detract from it.

rgds
0
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23593102
Ray is a great help here and I consider his stepping in just another of the fine resources here on EE.
Not a  problem, Misafi.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 23593142
@adrian_brooks: Thanks for your kind words!  I have learned a lot here and I am glad to be able to give back some of that to my colleagues.

@Misafi: Can you please post a link to the new Q - I looked, but it escaped me.

Best to all, ~Ray
0
 

Author Comment

by:Misafi
ID: 23593543
Thank you both.
I must say that it is this sort of spirit that keeps  pawpaws like me attached to Experts Exchange

Ray the QI is 24125952

Adrian - I hope we can still work on the differences with my two systems

rgds

Sean Minogue
(Misafi)
0
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23626958
Misafi,

After having looked over your PHP settings, I must say that I really didn't see anything that stood out as a possible cause. One of the questions I did ask you though was what web server software you are running?

I'm assuming it's IIS, but I know that if I were running on a windows server, I would surely be using Apache 2.x myself.
0
 

Author Comment

by:Misafi
ID: 23630030
Thanks
I am using IIS.
How complicated would a switchover be?
I am also using JMail.
rgds
0
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23645021
Switching over would probably be a rather involved process due to directory permissions and numerous other details. That was more of a recommendation rather then a suggested plan of action.

As for the differences between the two systems, I'm going to assume that Ray was able to assist you with the upload help. Is this correct or are you still having issues with the blob being martian swear words?
0
 

Author Comment

by:Misafi
ID: 23645788
Yes
Ray's system  involves storing the images elsewhere - that seems a lot more sensible that what I was trying to do and that is the way that I shall go.
But just out of curiousity I should really like to know why I am getting different results from similar steups.
Why can I see the jpg files on one yet only Martian swear words on the other?

Most perplexing...

rgds
0
 

Author Closing Comment

by:Misafi
ID: 31544208
Thanks for all your work Adrian.
I have accepted this solution but would be interested to carry on the discussion (in English not Martian) should should you have any furher ideas.

rgds
Sean
0
 
LVL 12

Expert Comment

by:Richard Davis
ID: 23645936
Perhaps you have your MIME types setup differently on your IIS server. I can't imagine how or why they would be different as those are VERY typical MIME types, but it's the only thing that seems to be ringing through as the likely culprit at the moment.
0
 

Author Comment

by:Misafi
ID: 23645985
Thankls - I'll have a look at that
0

Featured Post

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, I’ll talk about multi-threaded slave statistics printed in MySQL error log file.
This holiday season, we’re giving away the gift of knowledge—tech knowledge, that is. Keep reading to see what hacks, tips, and trends we have wrapped and waiting for you under the tree.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month17 days, 3 hours left to enroll

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question