• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 360
  • Last Modified:

PHP Script to Submit Form Data from a list

I have a simple form that I use to send SMS messages to a system we have developed.  Generally I type the message into the form manually but I would like to set up an automated system.  The system would would automatically send predefined messages at intervals from a list either in a text file or MySql DB.  I would prefer to do this in a text file if possible.  Here's the scenario:

Text File With Messages to Send:

Who is the king of france?
When is the next U.S. Holiday?
Who's on first?

Current Form:

<form method="get" action="http://254.254.254.254/" target="_self" name="">
      <input type="text" name="Data" size="160" value=""><br>
      <input type="submit" name="Submit" size="50" value="Send Query">
      <input type="hidden" name="OriginatorAddress" value="8005551212">
</form>


The idea is to have this page up in a browser and some mechanism to pull the first line from the text file and submit it.  Then it pulls the second line and submits it.  Third line...etc....  All of this would happen at predefined intervals (maybe 20 seconds or so).

A PHP or other easy system would be preferred.  Thanks.


0
dansoto
Asked:
dansoto
  • 16
  • 9
1 Solution
 
AlexanderRCommented:
<?php
session_start();
if(! array_key_exists("MessageNum", $_SESSION)){
   $_SESSION["MessageNum"] = 0;
}
if ($messages = fopen("messages.txt", "rb")) {
   
   $messages = explode("\n", fread($messages, filesize("messages.txt")));
   $Data = $messages[$_SESSION["MessageNum"]];
   fclose($messages);
   $_SESSION["MessageNum"] = $_SESSION["MessageNum"] + 1;
   
   if ($_SESSION["MessageNum"] + 1 > sizeof($messages)) {
      $Data = "No More Messages";
   } else {
      $_SESSION["MessageNum"] = $_SESSION["MessageNum"] + 1;
   }
   


} else {
   echo "Eorror opening text file";
}

?>

<script language="JavaScript">
function reloadFunction() {
    // assuming url of:  test.htm - eanables me to test
    // may need to parse location.href if the url is not fixed
    location.href = '<?php echo $_SERVER['PHP_SELF'];?>';
}
</script>
<body onLoad="setTimeout('reloadFunction()',20000)">
<?php
   // do whatever you want with that data.
   echo $Data;
?>

</body>
0
 
AlexanderRCommented:
Sorry got an extra $_SESSION["MessageNum"] = $_SESSION["MessageNum"] + 1;

take it out after fclose($messages);
<?php
session_start();
if(! array_key_exists("MessageNum", $_SESSION)){
   $_SESSION["MessageNum"] = 0;
}
if ($messages = fopen("messages.txt", "rb")) {
   
   $messages = explode("\n", fread($messages, filesize("messages.txt")));
   $Data = $messages[$_SESSION["MessageNum"]];
   fclose($messages);
   
   if ($_SESSION["MessageNum"] + 1 > sizeof($messages)) {
      $Data = "No More Messages";
   } else {
      $_SESSION["MessageNum"] = $_SESSION["MessageNum"] + 1;
   }
   


} else {
   echo "Eorror opening text file";
}

?>

<script language="JavaScript">
function reloadFunction() {
    // assuming url of:  test.htm - eanables me to test
    // may need to parse location.href if the url is not fixed
    location.href = '<?php echo $_SERVER['PHP_SELF'];?>';
}
</script>
<body onLoad="setTimeout('reloadFunction()',20000)">
<?php
   // do whatever you want with that data.
   echo $Data;
?>

</body>

Little explanation:
Messages are kept in file messages.txt .  Every message must be on a sepparate line.  Depending what OS PHP is running on line separator as well as mode of fopen may change.  On windows its "rb" on linux its just "r". Windows line separator is "\n" but sometimes has to be "\r\n".  Just to keep some things in mind if original doesnt work.

PHP opens the file and goes to needed line that is taken from a session.  If there is more lines to come that number will increment so that next time page loads another message is there.  If there are no messages it will say "No More Messages" and as soon as there is another message in file it will send it.

Javascript reloads the file every 20 seconds (20000 microseconds i think).  This part cannot be done on PHP, because you cannot have PHP scripts hanging in memory.  They will be destroyed from memory by a time limit on the server.  If its loaded in a browser then its not a problem.
0
 
dansotoAuthor Commented:
Thanks for your help.  The main part of this problem was for it submit each line in the messages.txt in the same manner as I would have done it manually.  How do I accomplish this?

Thanks,

- dan -
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
AlexanderRCommented:
I am not sure i understand the difference between typing the message one by one in the form and dumping all the messages in the text file message-per-line and have the script send each one of them out (those same messages that you normally would type)
What is that manner?

BTW with that script there is no need for a form.

What can happen is where i have // do whatever you want with that data.
you could pass variable $data to your SMS sending system at that poing together with any other info.  That also means that SMS sending code and my script need to be on the same page.
0
 
dansotoAuthor Commented:
Sounds good but this is why I came for help :)
Can you write out what the line needs to be to pass that info on as I do in the form?

<form method="get" action="http://254.254.254.254/" target="_self" name="">
      <input type="text" name="Data" size="160" value=""><br>
      <input type="submit" name="Submit" size="50" value="Send Query">
      <input type="hidden" name="OriginatorAddress" value="8005551212">
</form>

Thanks again..

- dan -
0
 
AlexanderRCommented:
This is a GET type of form. So on your action page (whatever you have instead of http://254.254.254.254), provided that its written in php you should see $_GET["Data"], $_GET["Submit"] and $_GET["OriginatorAddress"]

Once you put my code on top of action page you can either change all the variables mentioned above to $Data, $Submit, $OriginatorAddress. Then in my code you could add in the portion
<?php
   // do whatever you want with that data.
   $Submit = "Send Query";
   $OriginatorAddress = 8005551212;
?>

You can also have an option (which is a bad practice) to do this:
<?php
   // do whatever you want with that data.
   $_GET["Data"] = $Data;
   $_GET["Submit"] = "Send Query";
   $_GET["OriginatorAddress"] = 8005551212;
?>
0
 
dansotoAuthor Commented:
Ok..sorry for being a hassle but here's the deal.  The only page I have access to is the page on which my current, simple form is located. Currently, when I submit via my form, this is the URL that comes up

http://254.254.254.78/?Data=how+old+is+nicole+kidman&Submit=Send+Query&OriginatorAddress=8005551212

Can I make this happen with just your one page?

Thanks,

- dan -
0
 
AlexanderRCommented:
Sorry for the wait.  My laptop is going :(

<html><head>
<?php
session_start();
if(! array_key_exists("MessageNum", $_SESSION)){
   $_SESSION["MessageNum"] = 0;
}
if ($messages = fopen("messages.txt", "rb")) {
   
   $messages = explode("\n", fread($messages, filesize("messages.txt")));
   $Data = $messages[$_SESSION["MessageNum"]];
   fclose($messages);
   
   if ($_SESSION["MessageNum"] + 1 > sizeof($messages)) {
      $Data = "No More Messages";
   } else {
      $_SESSION["MessageNum"] = $_SESSION["MessageNum"] + 1;
   }
   $Data = trim($Data);

} else {
   echo "Error opening text file";
}

?>

<script language="JavaScript">
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
   var xmlHttp;
   if(window.ActiveXObject){
      try
      {
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
         xmlHttp = false;
      }
   } else {
      try
      {
      xmlHttp = new XMLHttpRequest();
      }
      catch (e)
      {
         xmlHttp = false;
      }
   }
   if (!xmlHttp)
      alert("Error creating the XMLHttpRequest object.");
   else
      return xmlHttp;
}
SendMessage();
function SendMessage()
{
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
      var message;
      name = "<?php echo $Data;?>" + "&Submit=Send Query&OriginatorAddress=8005551212";
      name = encodeURIComponent(name);
      xmlHttp.open("GET", "timedresults.php?name=" + name, true);
      xmlHttp.send(null);
   } else {
      setTimeout('process()', 1000);
   }
}

function reloadFunction() {
    location.href = '<?php echo $_SERVER['PHP_SELF'];?>';
}
</script>
</head>
<body onLoad="setTimeout('reloadFunction()',20000)">

</body>
</html>
0
 
AlexanderRCommented:
Sorry.
xmlHttp.open("GET", "timedresults.php?name=" + name, true);
is out to be
xmlHttp.open("GET", "254.254.254.78?name=" + name, true);
0
 
dansotoAuthor Commented:
Doesn't seem to do anything :(  Before at least I could see the messages in the browser as they were retrieved (but never sent).  Is there anyway I can see those again and possible what is sent with each Get so I can confirm what is being sent to 255.255.255.255 ?
Normally the server returns a message back to the browser like:  
===========================================
Received query from phone number 8005551212:
how old is nicole kidman
===========================================

That way I know it was sent successfully...
0
 
AlexanderRCommented:
Thats true, my script doesnt return anything.  However, in using your URL example it should send the values to your SMS.  Is there any way you can check for the arrival of your SMSs?
I got to agree, my program seems scary without any apparent output :)
I will try to modify to capture server output.
0
 
dansotoAuthor Commented:
I did check and our system didn't receive any of the messages...  :(

Thanks again for your continued  help..
0
 
AlexanderRCommented:
This is the way i did the script and it worked for me.
I had a page called timedextract.php with all of that code.  It passed messages from messages.txt on to a page timedresults.php which recorded the messages into a file output.txt with the code
<?php

$filename = 'output.txt';
$somecontent = $_GET["name"];

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}

?>

So in the end all messages from messages.txt were transfered to output.txt
If it doesnt work on yours, then perhaps i got the URL transmition variables wrong somewhere around
name = "<?php echo $Data;?>" + "&Submit=Send Query&OriginatorAddress=8005551212";
      name = encodeURIComponent(name);
      xmlHttp.open("GET", "timedresults.php?name=" + name, true);

For starters, does it at least refresh every 20 seconds?
0
 
AlexanderRCommented:
Yes my URL makes no sense at all.

This will still not produce any confirmation but hopefull contact your SMS, provided that my data, submit and originationaddress are in correct format.

<html><head>
<?php
session_start();
if(! array_key_exists("MessageNum", $_SESSION)){
   $_SESSION["MessageNum"] = 0;
}
if ($messages = fopen("messages.txt", "rb")) {
   
   $messages = explode("\n", fread($messages, filesize("messages.txt")));
   $Data = $messages[$_SESSION["MessageNum"]];
   fclose($messages);
   
   if ($_SESSION["MessageNum"] + 1 > sizeof($messages)) {
      $Data = "No More Messages";
   } else {
      $_SESSION["MessageNum"] = $_SESSION["MessageNum"] + 1;
   }
   $Data = trim($Data);

} else {
   echo "Error opening text file";
}

?>

<script language="JavaScript">
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
   var xmlHttp;
   if(window.ActiveXObject){
      try
      {
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
         xmlHttp = false;
      }
   } else {
      try
      {
      xmlHttp = new XMLHttpRequest();
      }
      catch (e)
      {
         xmlHttp = false;
      }
   }
   if (!xmlHttp)
      alert("Error creating the XMLHttpRequest object.");
   else
      return xmlHttp;
}
SendMessage();
function SendMessage()
{
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
      var data = "<?php echo $Data;?>";
      var submit;
      var OriginatorAddress;
      data = encodeURIComponent(data);
      submit = encodeURIComponent("Send Query");
      OriginatorAddress = encodeURIComponent("8005551212");
      xmlHttp.open("GET", "timedresults.php?Data=" + data + "&Submit=" + submit + "&OriginatorAddress=" + OriginatorAddress, true);
      xmlHttp.send(null);
   } else {
      setTimeout('process()', 1000);
   }
}

function reloadFunction() {
    location.href = '<?php echo $_SERVER['PHP_SELF'];?>';
}
</script>
</head>
<body onLoad="setTimeout('reloadFunction()',2000)">

</body>
</html>
0
 
AlexanderRCommented:
I need to remember to replace xmlHttp.open("GET", "timedresults.php? with
xmlHttp.open("GET", "254.254.254.78?
everytime i post here......
0
 
dansotoAuthor Commented:
Unfortunately, it's still not working correctly.  The URL that gets sent normally, is in this format:

http:/255.255.255.255/?Data=test+query&Submit=Send+Query&OriginatorAddress=8005551212
0
 
AlexanderRCommented:
Looks like JavaScript has a different idea of standard URL encoding.  I did not notice that javascripts's encodeURIComponent returns % signs instead of + signs until i run it in http capturing debugger, so URL looked like http://255.255.255.255/?Data=test%query&Submit=Send%Query&OriginatorAddress=80055
Apache recognises % and + signs the same way so i would always get the right results either way.  But looks like your SMS is more strict.
This time lets make PHP do the work:

<?php session_start();?>
<html><head>
<?php
if(! array_key_exists("MessageNum", $_SESSION)){
   $_SESSION["MessageNum"] = 0;
}
if ($messages = fopen("messages.txt", "rb")) {
   
   $messages = explode("\n", fread($messages, filesize("messages.txt")));
   $Data = $messages[$_SESSION["MessageNum"]];
   fclose($messages);
   
   if ($_SESSION["MessageNum"] + 1 > sizeof($messages)) {
      $Data = "No More Messages";
   } else {
      $_SESSION["MessageNum"] = $_SESSION["MessageNum"] + 1;
   }
   $Data = trim($Data);
   $SMSarray = array('Data'=>$Data,
                'Submit'=>"Send Query",
                'OriginatorAddress'=>'8005551212');
   $SMSstring = http_build_query($SMSarray);

} else {
   echo "Error opening text file";
}

?>

<script language="JavaScript">
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
   var xmlHttp;
   if(window.ActiveXObject){
      try
      {
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
         xmlHttp = false;
      }
   } else {
      try
      {
      xmlHttp = new XMLHttpRequest();
      }
      catch (e)
      {
         xmlHttp = false;
      }
   }
   if (!xmlHttp)
      alert("Error creating the XMLHttpRequest object.");
   else
      return xmlHttp;
}
SendMessage();
function SendMessage()
{
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
      xmlHttp.open("GET", "timedresults.php?<?php echo $SMSstring; ?>", true);
      //xmlHttp.onreadystatechange = handleServerResponse;
      xmlHttp.send(null);
   } else {
      setTimeout('process()', 1000);
   }
}
function reloadFunction() {
    location.href = '<?php echo $_SERVER['PHP_SELF'];?>';
}
function handleServerResponse()
{
   if (xmlHttp.readyState == 4){
      if (xmlHttp.status == 200){
         document.write("inserted");
         setTimeout('reloadFunction()', 1000);
      }
   }
}


</script>
</head>
<body onLoad="setTimeout('reloadFunction()',2000)">

</body>
</html>
0
 
AlexanderRCommented:
That way URL passed on looks exactly as the one you gave me. (just in case avoid characters like ?, it produces system dependant ASCII code that your SMS may not understand), so if it still doesnt work, then there is something else important i dont know about that SMS.
0
 
dansotoAuthor Commented:
Do I need to replace:
      xmlHttp.open("GET", "timedresults.php?<?php echo $SMSstring; ?>", true);

with something this time ?
0
 
AlexanderRCommented:
I never learn.  Yes
xmlHttp.open("GET", "timedresults.php?<?php echo $SMSstring; ?>", true); must be
xmlHttp.open("GET", "255.255.255.255?<?php echo $SMSstring; ?>", true);

This is an IP address you have, so different browsers can go picky about it.  If anything try variations of http://255.255.255.255?  or http://255.255.255.255/? or just IP.  Bottom line is
everything between xmlHttp.open("GET", "  and ?<?php echo $
is your sms address.
0
 
AlexanderRCommented:
Still not working?
0
 
dansotoAuthor Commented:
Sorry but I was never able to get this to work.  I will however award you the points for your hard work and time.

Thanks,

- dan -
0
 
AlexanderRCommented:
Thanks.  I appreciate that, although feel somewhat bad about it, but it helps my record :).

Since it works for me (as it outputs the URL of your requirement), there must be something else about the SMS that we dont know.  Is there anyway you can contact the programmer/administrator in charge of that, and ask what are the requirements, and perhaps show them my code?
0
 
dansotoAuthor Commented:
The problem is not about SMS really.  I can't really verify that the URL is being formatted correctly..unfortunately.
0
 
AlexanderRCommented:
Did you ever try to send messages that do not contain spaces??

Different browsers, OSs could generate different URLs. For example the debugger of PHPed showed me the pluses where they are out to be (making my url look exactly like yours, so i got happy and gave you the code). When i switched the debuggers, OS, and browsers, i get something totally different. Go figure. So i'll try to give you some basic tips on how to figure out how to get the results to work on yours, because its just impossible for me to get the same environment as you are. I wonder what other experts would say about this.

Heres what you can do. Grab a copy of http debugger from http://maxq.tigris.org/
When you configure it and your browser proxy propperly (must read the guide), it will output exactly what and how is being sent and received by the browser (including our troublesome URL).

To set up a testing environment. Make 2 files. First one i called timedextract.php.  Put in the code i gave you.  BTW, i made yet another modification to it. This time i decided not to rely on any automatic URL encoding and did it manually (replace spaces with pluses).  I also added some outputs to help see how data looks at different points.  You can add more by typing echo $varname, if its in php section or document.write(varname) if its JS section.

(check this version on sms first)

<html><head>
<?php
session_start();
if(! array_key_exists("MessageNum", $_SESSION)){
   $_SESSION["MessageNum"] = 0;
}
if ($messages = fopen("messages.txt", "rb")) {
   
   $messages = explode("\n", fread($messages, filesize("messages.txt")));
   $Data = $messages[$_SESSION["MessageNum"]];
   fclose($messages);
   
   if ($_SESSION["MessageNum"] + 1 > sizeof($messages)) {
      $Data = "No More Messages";
   } else {
      $_SESSION["MessageNum"] = $_SESSION["MessageNum"] + 1;
   }
   $Data = trim($Data);
   $Data = str_replace(" ","+",$Data);
   $Submit = str_replace(" ","+","Send Query");
   $OriginatorAddress = str_replace(" ","+","8005551212");
   
   echo $Data;

} else {
   echo "Error opening text file";
}

?>

<script language="JavaScript">
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
   var xmlHttp;
   if(window.ActiveXObject){
      try
      {
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
         xmlHttp = false;
      }
   } else {
      try
      {
      xmlHttp = new XMLHttpRequest();
      }
      catch (e)
      {
         xmlHttp = false;
      }
   }
   if (!xmlHttp)
      alert("Error creating the XMLHttpRequest object.");
   else
      return xmlHttp;
}
SendMessage();
function SendMessage()
{
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
      var data = "<?php echo $Data;?>";
      var submit = "<?php echo $Submit;?>";
      var OriginatorAddress = "<?php echo $OriginatorAddress;?>";
      data = encodeURIComponent(data);
      submit = encodeURIComponent(submit);
      OriginatorAddress = encodeURIComponent(OriginatorAddress);
      xmlHttp.open("GET", "timedresults.php?Data=" + data + "&Submit=" + submit + "&OriginatorAddress=" + OriginatorAddress, true);
      xmlHttp.send(null);
   } else {
      setTimeout('process()', 1000);
   }
}

function reloadFunction() {
    location.href = '<?php echo $_SERVER['PHP_SELF'];?>';
}
</script>
</head>
<body onLoad="setTimeout('reloadFunction()',2000)">

</body>
</html>

Second file will receive the messages so you can see how they arrive. I called it timedresults.php

<?php

$filename = 'output.txt';
$somecontent = $_GET["Data"];
//uncomment next line if you explicitly converted spaces to pluses and dont want to see pluses in the output
//$somecontent = str_replace("+", " ", $somecontent);

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}

?>

check output.txt for results.  Create it manually just in case.

To get the satisfied output from the debugger.  You may want to play around with sections like after $Data = trim($Data);  Either use or dont use http_build_query.
Then play with section above
xmlHttp.open("GET", "timedresults.php?<?php echo $SMSstring; ?>", true);
to use JS to encode automatically or manualy.
Start out by testing messages in the messages.txt that have nothing special in them. No spaces, no questions marks, nothing but a-z.  Once you get the desired results in MaxQ output try to change the "timedresults.php?<?
to  "sms?<?

May be i am just not an expert enough, but i dont know what else to do from here on.  If you feel like going through this, and get anything check back.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 16
  • 9
Tackle projects and never again get stuck behind a technical roadblock.
Join Now