Passing String array to PHP as POST

25,317

Solution 1

To pass an array to php in query string, you should add [] to identifier and add every item as separate entry, so something like this should work:

nameValuePairs.add(new BasicNameValuePair("devices[]", device1));
nameValuePairs.add(new BasicNameValuePair("devices[]", device2));
nameValuePairs.add(new BasicNameValuePair("devices[]", device3));

now, $_POST['devices'] on php side will contain an array.

Solution 2

I think you should json encode your devices array so you get a string which you can pass it to BasicNameValuePair(...). In your php code, you just've to use json_decode to get back an array.

JSONArray devices = new JSONArray();
devices.put(device1);
devices.put(device2);
devices.put(device3);

String json = devices.toString();
nameValuePairs.add(new BasicNameValuePair("devices", devices));

In your php code:

$devices = $_POST['devices'];
$devices = json_decode($devices);

Solution 3

First, you are missing single quotes when accessing the $_POST array in PHP. Change the line

$registrationIDs = array($_POST[devices]);

to:

$registrationIDs = array($_POST['devices']);

You should enable error logging or the output of PHP error messages for debugging using the ini value display_errors, log_errors, error_reporting to get noticed of such errors.


But even array($_POST['devices']) will not do what are may expecting. array(...) is an array initialization construct in php. Meaning that you just wrap ($_POST['devices']) into another array.

... Would like to see the output of var_dump($_POST);. This would give me a chance to help further..

Share:
25,317
TomSelleck
Author by

TomSelleck

Updated on July 21, 2022

Comments

  • TomSelleck
    TomSelleck almost 2 years

    I am trying to pass a string array to a PHP script as POST data but am unsure of what to do.

    Here is my code for executing PHP scripts so far:

    Where I am trying to pass the array:

    nameValuePairs.add(new BasicNameValuePair("message",message));
    String [] devices = {device1,device2,device3};
    nameValuePairs.add(new BasicNameValuePair("devices", devices));// <-- Can't pass String[] to BasicNameValuePair
    callPHPScript("notify_devices", nameValuePairs);
    

    Call PHP script:

    public String callPHPScript(String scriptName, List<NameValuePair> parameters) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://localhost/" + scriptName);
        String line = "";
        StringBuilder stringBuilder = new StringBuilder();
        try {
            post.setEntity(new UrlEncodedFormEntity(parameters));
    
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() != 200)
            {
                System.out.println("DB: Error executing script !");
            }
            else {
                BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
                line = "";
                while ((line = rd.readLine()) != null) {
                    stringBuilder.append(line);
                }
            }
    
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("DB: Result: " + stringBuilder.toString());
        return stringBuilder.toString();
    }
    

    And the PHP script in question:

    <?php
    include('tools.php');
    // Replace with real BROWSER API key from Google APIs
    $apiKey = "123456";
    
    // Replace with real client registration IDs 
    $registrationIDs = array($_POST[devices]); <-- Where I want to pass array to script
    
    // Message to be sent
    $message = $_POST['message'];
    
    // Set POST variables
    $url = 'https://android.googleapis.com/gcm/send';
    
    $fields = array(
                    'registration_ids'  => $registrationIDs,
                    'data'              => array( "message" => $message ),
                    );
    
    $headers = array( 
                        'Authorization: key=' . $apiKey,
                        'Content-Type: application/json'
                    );
    
    // Open connection
    $ch = curl_init();
    
    // Set the url, number of POST vars, POST data
    curl_setopt( $ch, CURLOPT_URL, $url );
    
    curl_setopt( $ch, CURLOPT_POST, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
    
    // Execute post
    $result = curl_exec($ch);
    
    // Close connection
    curl_close($ch);
    
    print_as_json($result);
    ?>
    

    Any ideas? Thanks !

    Edit

    I am trying the following but still no joy:

    public void notifyDevices(Message message) {
    
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        List<String> deviceIDsList = new ArrayList<String>();
        String [] deviceIDArray;
    
        //Get devices to notify
        List<JSONDeviceProfile> deviceList = getDevicesToNotify();
    
        for(JSONDeviceProfile device : deviceList) {
            deviceIDsList.add(device.getDeviceId());
        }
    
        //Array of device IDs
        deviceIDArray = deviceIDsList.toArray(new String[deviceIDsList.size()]);
        for(String deviceID : deviceIDArray) {
    
            nameValuePairs.add(new BasicNameValuePair("devices[]", deviceID));
    
        }
    
        //Call script
        callPHPScript("GCM.php", nameValuePairs);
    }
    

    This is all the "Error reporting" I have...

            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() != 200)
            {
                System.out.println("DB: Error executing script !");
            }