Downloading image from POST

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cnuland
Forum Newbie
Posts: 3
Joined: Fri Jul 08, 2011 11:57 am

Downloading image from POST

Post by cnuland »

Hi,
I'm an iPhone/Android programmer who just recently started using PHP for a project. The app I'm designing sends images over HTTP POST via the iPhone. Currently my server will download and store about 19 out of 20 pictures, however I'm trying to get the most reliability I can, I'd prefer to only see one dud picture out of a few hundred pictures, instead every 20. Is there a reason why sometimes I get these dud pictures? I asked on the iPhone developer forums and they said it wasn't my Objective C programming and that the fault either was the server or the php code. Here's the php code that the iPhone NSUrlConnection sends the photos too,

Code: Select all

<?php
require_once('Includes/connection.php');
$uploaddir = './uploads/';
$file = basename($_FILES['userfile']['name']);
$image =  $_FILES['userfile']['name'];
$info = getImageSize($_FILES['userfile']['tmp_name']);
$name = basename($_FILES['fileName']['name']);
//$date = basename($_FILES['fileDesc']['name']);
$desc = basename($_FILES['fileDesc']['name']);
$picID = basename($_FILES['fileID']['name']);
$gps = basename($_FILES['gps']['name']);
$uploadfile = $uploaddir . $file;
$myFile = "testFile.txt";
$fh = fopen($picID, 'w') or die("can't open file");
$stringData = "{}\n";
fwrite($fh, $stringData);
//$stringData = "{$date}\n";
//fwrite($fh, $stringData);

//////////////////////////////////////////////////

$picQuery=mysql_query("select newPics  from members where username = '$picID'");
			$picCount = mysql_fetch_array($picQuery);
			$newpics =(int)$picCount["newPics"] + 1;
			
echo $newpics;
mysql_query("UPDATE members SET newPics = '$newpics' WHERE username = '$picID'");

$uploadedfile = ($_FILES['userfile']['tmp_name']);
$src = imagecreatefromjpeg($uploadedfile);

list($width,$height)=getimagesize($uploadedfile);

if ($width > $height)
{
$newwidth=150;
$newheight=113;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=150;
$newheight1=113;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
}
else
{
$newwidth=113;
$newheight=150;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=113;
$newheight1=150;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
}
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
 $width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1, 
$width,$height);

$myquery=mysql_query("select max(id) as maxnum from images");
			$myrow = mysql_fetch_array($myquery);
			$myname =(int)$myrow["maxnum"] + 1;
			
$image_name=$file;
$newname = "uploads/". $myname.".jpg";
$newname1 = "uploads/thumbs/". $myname.".jpg";

imagejpeg($tmp,$newname,100);
imagejpeg($tmp1,$newname1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
$copied = copy($_FILES['userfile']['tmp_name'], $newname);
$date = date("F j, Y, g:i a");
//////////////////////////////////////////////////////////////////////

$query = sprintf("insert into images (filename, mime_type, file_size, project_name, image_desc, pictureID, date, gps)
                values ('%s', '%s', %d, '$name', '$desc', '$picID', '$date', '$gps')",
            mysql_real_escape_string($_FILES['userfile']['name']),
            mysql_real_escape_string($info['mime']),
            $_FILES['userfile']['size'],
            mysql_real_escape_string(
               // file_get_contents($_FILES['userfile']['tmp_name'])
            )
        );
mysql_query($query, $connection);
$id = (int) mysql_insert_id($connection);
$stringData = "works\n";
fwrite($fh, $stringData);
fclose($fh);
?>
Now, the dud pictures do store information in the database, so I know that the iPhone is making the connection and the php file is called. However, the picture doesn't download to the uploads folder. So when the site loads the photos it just shows an empty picture for the dud. It might also help to know that when I moved this to another server it improved greatly (from about 3 duds every 20 pictures to 1 dud every 20 pictures).

Is there a more reliable way to handle this? Thanks and let me know if you have any further questions!

-Christopher Nuland (3iD Software Engineer)
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Downloading image from POST

Post by McInfo »

The script is disorganized.
  • There are variables that are set but have no effect on the script.
  • Some of the variables that are set at the top of the script are read only at the bottom, making it difficult to know what value they hold when they are finally read.
  • Some of the variable values that go into the queries are escaped, others are not.
  • An image is stored in the $newname file by imagejpeg(), but the file is overwritten by copy() a few lines later.
  • How many files are uploaded? I see 'userfile', 'fileName', 'fileDesc', 'fileID', and 'gps'. Those represent five distinct files.
  • Incrementing a database field should be done by MySQL in one query, not in two queries with PHP in the middle.
  • Writing to the file (fopen, fwrite, fclose) seems to have no purpose in this script.
cnuland
Forum Newbie
Posts: 3
Joined: Fri Jul 08, 2011 11:57 am

Re: Downloading image from POST

Post by cnuland »

Thanks! The only thing I don't understand is this line,

"How many files are uploaded? I see 'userfile', 'fileName', 'fileDesc', 'fileID', and 'gps'. Those represent five distinct files."

It should only send one file with more then one set of information, am I sending more then one file instead..? I don't know if you are familiar with xcode, but maybe the tags speak for themselves here.

Code: Select all

NSMutableData *body = [NSMutableData data];
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 	
			[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileName\"; filename=\"%@\"\r\n",image.name] dataUsingEncoding:NSUTF8StringEncoding]];  
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 	
		
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 	
			[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileID\"; filename=\"%@\"\r\n",userName2] dataUsingEncoding:NSUTF8StringEncoding]];  
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
		
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 	
			[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileDesc\"; filename=\"%@\"\r\n",image.gps] dataUsingEncoding:NSUTF8StringEncoding]];  
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
		
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 	
			[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"gps\"; filename=\"%@\"\r\n",image.gps] dataUsingEncoding:NSUTF8StringEncoding]];  
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 	
		
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
			[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n",image.name] dataUsingEncoding:NSUTF8StringEncoding]];
Thank you for your help so far,

Christopher Nuland
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Downloading image from POST

Post by McInfo »

The request should look something like this.

Code: Select all

POST /receiver.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://localhost/sender.php
Content-Type: multipart/form-data; boundary=---------------------------6865409446945890651613238502
Content-Length: 1234

-----------------------------6865409446945890651613238502
Content-Disposition: form-data; name="fileName"

def.jpg
-----------------------------6865409446945890651613238502
Content-Disposition: form-data; name="fileID"

345
-----------------------------6865409446945890651613238502
Content-Disposition: form-data; name="fileDesc"

abc de fghi jklmn op qrs t uv wxyz
-----------------------------6865409446945890651613238502
Content-Disposition: form-data; name="gps"

12.34567 8.90123
-----------------------------6865409446945890651613238502
Content-Disposition: form-data; name="userfile"; filename="abc.jpg"
Content-Type: image/jpeg

JFIF[...snip...]
-----------------------------6865409446945890651613238502--
Having a "filename" attribute in the Content-Disposition header means that the content is a file.

You probably already know this, but I'll state it just to be clear. PHP will put strings into the $_POST array which can be accessed using the keys 'fileName', 'fileID', fileDesc', and 'gps'. An array of attributes for 'userfile' will go into $_FILES['userfile']. (If there was a second file named 'second', its attributes would go into $_FILES['second'].) The actual file data will be stored in a temporary file whose path can be found in $_FILES['userfile']['tmp_name'].
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: Downloading image from POST

Post by cpetercarter »

Have you considered the possibility that the images which fail to upload are simply too big? Test the value of $_FILES['filename']['error'] - details of error codes are at http://www.php.net/manual/en/features.f ... errors.php
cnuland
Forum Newbie
Posts: 3
Joined: Fri Jul 08, 2011 11:57 am

Re: Downloading image from POST

Post by cnuland »

Thanks for both of your help! It was a mix of everything McInfo mentioned and the size, I've been playing around with the server, website, and iPhone app and finally optimized to the point there has been zero failed uploaded pictures out of 400. First off, the file size was to large, I set it to 50% full jpeg quality, instead of the 70% it was set up as.

I also cleaned up the php code and it worked perfectly from there, thank you again!
Post Reply