user440096
user440096

Reputation:

When passing values to a php file can you use the same Key more than once?

for example

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"name"];

[request setPostValue:imageData forKey:@"image"]; 
[request setPostValue:imageData1 forKey:@"image"]; 
[request setPostValue:imageData2 forKey:@"image"]; 
[request setPostValue:imageData3 forKey:@"image"]; 
[request startSynchronous];

Is it ok to post these images all using the same named key 'image' or would the php file become confused.

Upvotes: 0

Views: 90

Answers (3)

Abhi Beckert
Abhi Beckert

Reputation: 33369

According to the HTTP specification, it is valid to have the same key in a request more than once. But PHP will loose some of the data, depending how you access it.

You should add square braces to your key, which will be converted to an array in the PHP code:

[request setPostValue:imageData forKey:@"images[]"]; 
[request setPostValue:imageData1 forKey:@"images[]"]; 
[request setPostValue:imageData2 forKey:@"images[]"]; 
[request setPostValue:imageData3 forKey:@"images[]"]; 

And in your PHP:

print_r($_POST['images'])
// array( imageData, imageData1, imageData2, imageData3 )

You can also do an associative array:

[request setPostValue:imageData forKey:@"images[zero]"]; 
[request setPostValue:imageData1 forKey:@"images[one]"]; 
[request setPostValue:imageData2 forKey:@"images[two]"]; 
[request setPostValue:imageData3 forKey:@"images[three]"]; 

Gives:

print_r($_POST['images'])
// array(
//   zero => imageData,
//   one => imageData1,
//   two => imageData2,
//   three => imageData3
// )

And you can also do nested arrays:

[request setPostValue:imageData forKey:@"images[first][]"]; 
[request setPostValue:imageData1 forKey:@"images[first][]"]; 
[request setPostValue:imageData2 forKey:@"images[second][]"]; 
[request setPostValue:imageData3 forKey:@"images[second][]"]; 

Gives:

print_r($_POST['images'])
// array(
//   first => array( imageData, imageData1 ),
//   second => array( imageData2, imageData3 )
// )

Upvotes: 1

lorenzo-s
lorenzo-s

Reputation: 17010

You can. You have to append [] in the key string, and PHP will receive data as if it is an array of values. http://onlamp.com/lpt/a/5091

Upvotes: 0

Quentin
Quentin

Reputation: 944011

You can, but if you try to access them through $_POST and friends then only one result will show up unless the name ends with [].

Upvotes: 1

Related Questions