tags:

views:

120

answers:

2

I'm at my wits end with this one, because I've used very similar code in the past, and it worked just fine.

The following code results in empty $_POST variables on the server. I verified this with:

file_put_contents('log_file_name', "log: ".$word, FILE_APPEND);

the only contents of log_file_name was "log: "

I then verified the PHP with a simple HTML form. It performed as expected.

The Objective-C:

    NSString *word = @"this_word_gets_lost";
    NSString *myRequestString =  [NSString stringWithFormat:@"word=%@",
                                  word];

    [self postAsynchronousPHPRequest:myRequestString toPage:@"http://www.mysite.com/pagefolder/mypage.php" delegate:nil];
}

-(void) postAsynchronousPHPRequest:(NSString*)request toPage:(NSString*)URL delegate:(id)delegate{
    NSData *requestData = [ NSData dataWithBytes: [ request UTF8String ] length: [ request length ] ];
    NSMutableURLRequest *URLrequest = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString: URL ] ]; 
    [ URLrequest setHTTPMethod: @"POST" ];
    [ URLrequest setHTTPBody: requestData ];

    [ NSURLConnection connectionWithRequest:URLrequest delegate:delegate];
    [URLrequest release];
}

The PHP:

$word = $_POST['word'];
file_put_contents('log_file_name', "log: ".$word, FILE_APPEND);

What am I doing wrong in the Objective-C that would cause the $_POST variable to be empty on the server?

A: 

If your code is straight copy-paste, you're missing an @ symbol after NSString *word. If that's not the problem, it might be NSData *requestData = [ NSData dataWithBytes: [ request UTF8String ] length: [ request length ] ];. Instead, try:

NSData *requestData = [request dataUsingEncoding:NSUTF8StringEncoding];  

EDIT: I'm not an expert on HTTP, but I think redirects generally kill POST data, since the data goes directly to the server (see here)--IE will apparently sometimes automatically resubmit the POST, but it's not part of the HTTP spec.

eman
Nice catch on the missing "@" but of course that would be a compile error
SooDesuNe
A: 

Ok, now I really am dumb founded. I found the problem.

On my site the actual URL is: http://www.mysite.com/PageFolder/mypage.php which has a redirect step so that all requests for documents inside http://www.mysite.com/pagefolder/mypage.php are redirected to PageFolder.

when I changed the URL in my Objective-C code to not use the redirect page, my post variables work fine.

I'll undo my accept of this anwser and give credit to anyone who can explain why the redirect might kill the post data.

SooDesuNe