-1

Can anybody please help me. I want to create php script for sms gateway, but something is wrong with foreach command. I cannot find what...

Here is my code:

<?php 

    $url = 'http://www.freesmsgateway.com/api_send';
    $post_contacts = array('381645391312', '0646395732', '99381625597222'); //phone numbers  xxxxxxxxxx format
    $json_contacts = json_encode($post_contacts); //encode them to json 

    $fields = array(
                'access_token'=>'53f86041s38544544e482b956bcac006',
                'message'=>urlencode('Test sms poruka'),
                'send_to'=>'post_contacts', //existing_contacts or post_contacts
                'post_contacts'=>urlencode($json_contacts),
                );

    $fields_string = '';
    foreach($fields_string as $key=>$value) { $fields_string .= $key.'='.$value.'&';}
    //rtrim($fields_string,'&');

    //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,count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); //optional

    //execute post
    $result = curl_exec($ch);

    //close connection
    curl_close($ch);

    print $result; //optional


    ?>

And I have this error

Warning: Invalid argument supplied for foreach() in /home/user/public_html/sms/smsfreegateway.php on line 15
 The message was blank.
leppie
  • 115,091
  • 17
  • 196
  • 297
Aleksandar
  • 501
  • 3
  • 10
  • 21

1 Answers1

0
foreach($fields_string as $key=>$value)

$fields_string is a string, not an array, and you've just initialized it to be empty. Perhaps you're meaning to iterate over $fields here?

  • I'm not expert with php, but script must use $fields array and get variables separately. And use $post_contacts to send message to number(s). This is code from developer section for api. How to make this code to work? – Aleksandar Sep 07 '13 at 21:09
  • Er… right! Indeed, `$fields` is probably what you want to iterate over, not `$fields_string`. –  Sep 07 '13 at 21:26
  • `$fields_string = ''; foreach($fields as $key=>$value) { $fields .= $key.'='.$value.'&';}` No errors. Is this correct? – Aleksandar Sep 07 '13 at 21:39
  • No. Think about what you've written a little more carefully… –  Sep 07 '13 at 21:40