1

I have a method that should post some data to a PHP file:

-(void)submitForm { NSLog(@"name=%@", formName.text); // returns correct value NSString *post = [NSString stringWithFormat:@"name=%@&", formName.text]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"http://path/to/file"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLResponse *response = NULL; NSError *requestError = NULL; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSLog(@"%@",responseString); } 

Note: I'm not actually using @"http://path/to/file". I've omitted the URL for privacy.

I believe it's connecting to the PHP script correctly, since I'm receiving the response I expect. The problem is that if I echo out $name, I get an empty string. Here's the script:

<?php include("config.php"); // Handles DB connection $name = mysql_escape_string($_POST["name"]); mysql_query("insert into objects(name) values('$name')") or die(mysql_error()); echo $name; // returns empty string 

All I expect is some sort of syntax/logic error in the Obj-C code, but I can't spot it.

6
  • there is no problem in the php side. i can't help you in Obj-c anyway. Commented Sep 14, 2012 at 8:11
  • Does formName.text contain any strange characters? Technically this should be URL-encoded before putting into the POST data. Commented Sep 14, 2012 at 8:54
  • No, just a simple alphanumerical string; no punctuation or whitespace. Commented Sep 14, 2012 at 8:56
  • Can you try removing this line? [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; Then tell me about the result. Commented Sep 14, 2012 at 11:27
  • Turns out, my path was incorrect. I had something like http://example/register, when it was expecting http://example/register/index.php. Commented Sep 14, 2012 at 12:23

2 Answers 2

1

I've got a feeling that your request is missing some mandatory data, a boundary and content-type, which might lead to your POST request being half complete.

I'll show you what I've done for uploading an HTML file to a webserver and then explain underneath.

Objective-C

NSString* str = formName.text; NSData* theData = [str dataUsingEncoding:NSUTF8StringEncoding]; NSString *urlString = @"http://whereyouarepostingto.com"; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"---------------------------14737809831466499882746641449"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"file\"; filename=\"%@.html\"\r\n", self.fileName]] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:theData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"%@", returnString); 

PHP

 <?php echo "Connection made to server"; move_uploaded_file($_FILES["file"][tmp_name], "uploads/" . $_FILES["file"]["name"]); ?> 

You'll need to change a few things around to fit your SQL insert and strip out my file stuff, but it's a start.

This is the part I think you're missing.

NSString *boundary = @"---------------------------14737809831466499882746641449"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 

The boundary can be a series of random numbers, but it has to exist.

Also, watch out when constructing the body of the request, especially the slashes. Make sure you escape any " ".

Sign up to request clarification or add additional context in comments.

Comments

1

Man you are not encoding all your Variables. You should make URL-Encode for your variable. The sample of Encoding function you can find here:

+(NSString *)urlEncode:(NSString *)unencodedString{ return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[NSHelper string:unencodedString], NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 ); } 

And by the way remove '&' character in the end of POST string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.