2-way MMS with a PHP Script (HTTP File Upload Post)

2-way MMS with a PHP Script (HTTP File Upload Post) SearchSearch
Author Message
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 6778
Registered: 10-2002
Posted on Monday, November 06, 2006 - 05:33 pm:   

A maintenance release update for NowSMS 2006 is now available for download.

This release contains numerous updates and enhancements for the NowSMS product.

Full details about this new release can be found on-line at http://support.nowsms.com/discus/messages/53/15129.html.

But we also wanted to draw attention to one of the more interesting new features, the ability to route received MMS messages directly to a PHP script.

I will provide more information in this posting, but want to also advise that you can download complete information at http://www.nowsms.com/download/php2waymms.zip, or view this information in a more readable format at http://www.nowsms.com/download/php2waymms.pdf.




Receiving MMS Messages with a PHP Script:
HTTP File Upload Post


NowSMS has long been a popular tool for enabling rapid development of interactive SMS applications and services. Within the NowSMS product, we refer to this as 2-way SMS. Through the 2-way SMS facility, when NowSMS receives an SMS message, it can be configured to dispatch that message to a script running on an HTTP server, to a local executable program, or local script or batch file. This provides a simple way to get received messages into an application, so that the application can perform custom processing on the message. The application can generate a simple reply back to the received message, or perform more advanced application specific logic. The scripts that process the received message can be written in popular web server scripting languages such as PHP, ASP and Perl, making the development of these scripts a relatively simple process for web developers.

NowSMS also supports the ability to route received MMS messages to an application. However, historically, it has been considerably more difficult to develop an application to support receiving MMS messages, as compared to SMS. The primary reason for this increased level of complexity is that the content of an MMS message is considerably more complex than that of an SMS text message, as a single MMS message can contain multiple content objects of different types.

NowSMS has historically supported three different techniques for delivering received MMS messages to an application:

  • A File/Directory based interface where newly received MMS messages are placed in a directory on the NowSMS server. A header file contains a text version of the header of the MMS message, as well as pointers to separate files that contain the MMS message content (text, images, video, etc.).
  • An XML/SOAP interface over HTTP POST where the MMS message content is packaged according to the MM7 format defined by the 3GPP.
  • An e-mail based interface where the MMS message content is repackaged into an e-mail message format and routed to a specified e-mail address.


Receiving MMS via HTTP File Upload Post

A new technique for 2-way MMS has been added, beginning with the October 30, 2006 (2006.10.30) release of NowSMS 2006. This technique uses HTTP POST to transmit the received MMS message content to a script file running on another web server. The HTTP POST format that is used is the same format that is used for “HTTP File Upload” (multipart/form-data) from an HTML form, with particular considerations to make it easier to process the HTTP POST using the PHP scripting language. This technique is not specific to PHP, and we hope to provide examples for other scripting languages in the future.

When an MMS message is received, NowSMS can be configured to perform an HTTP File Upload Post to a configurable URL. The format of the HTTP File Upload POST is similar to the Now SMS/MMS Proprietary URL Submission Format that is used by the “Send MMS Message” form in the NowSMS web interface, as described at the following link:
http://www.nowsms.com/documentation/ProductDocumentation/mms_notifications_and_c ontent/Submitting_MMS_Messages_URL.htm

There are two important differences that should be noted when comparing this HTTP File Upload Post to the Now SMS/MMS Proprietary URL Submission format:

  • An MMSText variable is not present in the HTTP File Upload Post. Any text parts of the MMS message will be posted as file components with a MIME type of “text/plain”.
  • The MMSFile variable is replaced by MMSFile[] in the HTTP File Upload Post in order to allow the variable to be processed as an array by PHP scripts. (Effective with the 2006.10.30 release, NowSMS will also accept MMSFile[] as an alias for MMSFile when using the Proprietary URL Submission Format.)


The raw HTTP File Upload Post will look similar to the following:

POST /mmsreceive.php HTTP/1.0
Host: x.x.x.x
Content-type: multipart/form-data; boundary="--boundary-border--"
Content-length: xxxxx (size of content part of post, everything after HTTP header)
Connection: close
Authorization: username:password (base64 encoded)

----boundary-border--
Content-Disposition: form-data; name="PhoneNumber"

+44123456789

----boundary-border--
Content-Disposition: form-data; name="MMSFrom"

+44987654321
----boundary-border--
Content-Disposition: form-data; name="MMSSubject"

Message Subject
----boundary-border--
Content-Disposition: form-data; name="MMSFile[]"; filename="original-filename.ext"
Content-type: Mime/Type

File data goes here
----boundary-border--
Content-Disposition: form-data; name="MMSFile[]"; filename="original-filename2.ext"
Content-type: Mime/Type

The MMSFile[] part may be repeated for multiple objects within the MMS message.
----boundary-border----



The URL to which the data is posted (http://x.x.x.x/mmsreceive.php in the above example) is configurable.

The actual MIME “boundary=” value will vary.

The “Content-Length:” header refers to the size in bytes of the content part of the HTTP POST (that is, all content that follows the HTTP header).

The “Authorization:” header will only be present if a username/password are configured for the POST within the NowSMS configuration.

The “PhoneNumber” variable contains the message recipient phone number (usually the phone number associated with the GSM/GPRS modem if messages are being received over a modem interface).

The “MMSFrom” variable contains the message sender address.

The “MMSSubject” variable contains the subject of the MMS message.

The “MMSFile[]” variable contains the raw file content of individual objects within the MMS message, and may be repeated multiple times.

The URL to which the data is posted (http://x.x.x.x/mmsreceive.php in the above example) is configurable.
The actual MIME “boundary=” value will vary.
The “Content-Length:” header refers to the size in bytes of the content part of the HTTP POST (that is, all content that follows the HTTP header).
The “Authorization:” header will only be present if a username/password are configured for the POST within the NowSMS configuration.
The “PhoneNumber” variable contains the message recipient phone number (usually the phone number associated with the GSM/GPRS modem if messages are being received over a modem interface).
The “MMSFrom” variable contains the message sender address.
The “MMSSubject” variable contains the subject of the MMS message.
The “MMSFile[]” variable contains the raw file content of individual objects within the MMS message, and may be repeated multiple times.

PHP Processing of MMS HTTP File Upload Post (mmsreceive.php)

PHP provides built-in functionality for processing an HTTP File Upload Post. This functionality is described in the PHP manual in the chapter titled “Handling HTTP File Uploads”, which is currently accessible on-line at http://php.net/manual/en/features.file-upload.php.

The global $_FILES array provides access to the file uploads, and the move_uploaded_file function allows you to save a copy of an uploaded file to another location. Pay particular attention to the example in the PHP manual that shows uploading an array of files, as this is the technique that is used for processing the multiple “MMSFILE” components of an MMS message.

The following is an example PHP script that processes received MMS messages and produces a simple HTML blog containing all images and other content submitted by remote users, with each user having their own blog. This PHP script (mmsreceive.php) can be downloaded as part of a ZIP file at http://www.nowsms.com/download/php2waymms.zip.



<?php

/* Replace the directory below with the directory that you wish to store received MMS messages in */
$upload_path = "c:\upload\";

/* By default, the script will return an HTTP 500 error if there are any internal processing errors,
such as a problem creating a directory or file. Returning an error in this way can signal the submitting
application that there is a problem and that it may need to retry. However, it can make it difficult
to debug problems when testing submissions via a web form. Set this variable to False to disable the
returning of an HTTP 500 error code. */
$returnHttp500OnError = True;

/* Variables used by script */
$errorFlag = False; /* Set to True if an error has occurred */
$dateString = date("YmdHis"); /* MMS images will be stored in a temporary directory name based upon current date/time */
$savedImageFile = False; /* If an error occurs, or the message is text only, delete the temporary directory */

/* MMSFrom variable contains the sender phone number - REQUIRED */
if (!isset($_REQUEST['MMSFrom']) || !$_REQUEST['MMSFrom']) {
echo "ERROR: MMSFrom variable (sender) is not set";
$errorFlag = True;
}

/* MMSSubject variable contains the message subject - if not set, use default text */
if (!isset($_REQUEST['MMSSubject']) || !$_REQUEST['MMSSubject']) {
$MMSSubject = "Multimedia Message";
}
else {
$MMSSubject = $_REQUEST['MMSSubject'];
}


/* Validate that there is one or more HTTP file upload in the MMSFile[] array */
if (!$errorFlag) {
$errorFlag = True; /* Default to returning an error, unless we find a valid HTTP file upload */
if ($_FILES["MMSFile"] && is_array($_FILES["MMSFile"]) && count($_FILES["MMSFile"])) {
foreach ($_FILES["MMSFile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$errorFlag = False; /* reset error condition, found a valid HTTP file upload */
}
}
}
if ($errorFlag) {
echo "ERROR: Request does not include any uploaded files!";
}
}

/* Build a directory for each user beneath the $upload_path, verify that we have rights to create a temporary file in this user directory */
if (!$errorFlag) {
$user_path = $upload_path . $_REQUEST['MMSFrom'];
if (!@file_exists ($user_path)) {
@mkdir ($user_path);
}
$user_path = $user_path . "\";
$tmp_filename = $user_path . "temp.tmp";
$tmp_handle = @fopen ($tmp_filename, "w+");
if (!$tmp_handle) {
if ($returnHttp500OnError) header("HTTP/1.0 500 Internal Error");
echo "ERROR: Cannot create files in upload directory " . $user_path;
$errorFlag = True;
}
else {
fclose ($tmp_handle);
@unlink ($tmp_filename);
}
}

/* Build a temporary directory beneath the user directory for storing image files associated with this MMS message */
if (!$errorFlag) {
$image_path = $user_path . $dateString;
if (!@file_exists ($image_path)) {
@mkdir ($image_path);
}
$image_path = $image_path . "\";
$tmp_filename = $image_path . "temp.tmp";
$tmp_handle = @fopen ($tmp_filename, "w+");
if (!$tmp_handle) {
if ($returnHttp500OnError) header("HTTP/1.0 500 Internal Error");
echo "ERROR: Cannot create files in upload directory " . $image_path;
$errorFlag = True;
}
else {
fclose ($tmp_handle);
@unlink ($tmp_filename);
}
}

if (!$errorFlag) {
/* msglog.txt contains previous messages posted by this user in HTML format, without HTML headers.
If this file exists, we copy it to msglog.tmp, so that we can create a new
msglog.txt file with this new message at the top. */
$msglogTxt = $user_path . "msglog.txt";
$msglogTmp = $user_path . "msglog.tmp";
if (@file_exists ($msglogTmp)) {
@unlink ($msglogTmp);
}
if (@file_exists ($msglogTxt)) {
if (!@copy ($msglogTxt, $msglogTmp)) {
if ($returnHttp500OnError) header("HTTP/1.0 500 Internal Error");
echo "ERROR: Cannot create temporary file in upload directory " . $user_path;
$errorFlag = True;
}
}
if (!$errorFlag) {
$msglogTxt_handle = @fopen ($msglogTxt, "w+");
if (!$msglogTxt_handle) {
if ($returnHttp500OnError) header("HTTP/1.0 500 Internal Error");
echo "ERROR: Cannot create temporary file in upload directory " . $user_path;
$errorFlag = True;
}
}

if (!$errorFlag) {
/* This is where we take the MMS message content, and convert it to simple HTML */
fwrite ($msglogTxt_handle, "<!-- Begin message block -->\r\n");
fwrite ($msglogTxt_handle, "<h2>" . $MMSSubject . "</h2>\r\n");
fwrite ($msglogTxt_handle, "<p><small>" . date("F j, Y, H:i") . "</small></p>\r\n");

/* Repeat for each object/file within the MMS message */
foreach ($_FILES["MMSFile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["MMSFile"]["tmp_name"][$key];
/* If the content is text, put it directly into the HTML */
if (!strcmp (strtolower($_FILES["MMSFile"]["type"][$key]), "text/plain")) {
fwrite ($msglogTxt_handle, "<p>" . file_get_contents ($tmp_name) . "</p>\r\n");
echo "The file ". basename( $_FILES["MMSFile"]["name"][$key]). " has been uploaded<br/>";
}
/* If the content is SMIL, ignore it */
else if (!strcmp (strtolower($_FILES["MMSFile"]["type"][$key]), "application/smil")) {
echo "The file ". basename( $_FILES["MMSFile"]["name"][$key]). " has been skipped<br/>";
}
else {
/* If content is an image, reference it with an img tag, otherwise include an a href */
$new_name = $image_path . basename( $_FILES["MMSFile"]["name"][$key]);
if (@move_uploaded_file($tmp_name, $new_name)) {
$savedImageFile = True;
echo "The file ". basename( $_FILES["MMSFile"]["name"][$key]). " has been uploaded<br/>";
if (!strncmp (strtolower($_FILES["MMSFile"]["type"][$key]), "image/", 6)) {
fwrite ($msglogTxt_handle, "<p><img src=\"" . $dateString . "\" .
basename($_FILES["MMSFile"]["name"][$key]) . "\"/></p>\r\n");
}
else if (!strncmp (strtolower($_FILES["MMSFile"]["type"][$key]), "video/", 6)) {
fwrite ($msglogTxt_handle, "<p>Video attachment: <a href=\"" . $dateString . "\" .
basename($_FILES["MMSFile"]["name"][$key]) . "\">" .
basename($_FILES["MMSFile"]["name"][$key]) .
"</a></p>\r\n");
}
else {
fwrite ($msglogTxt_handle, "<p>File attachment: <a href=\"" . $dateString . "\" .
basename($_FILES["MMSFile"]["name"][$key]) . "\">" .
basename($_FILES["MMSFile"]["name"][$key]) .
"</a></p>\r\n");
}
}
else {
echo "Error uploading file ". basename( $_FILES["MMSFile"]["name"][$key]) . "<br/>";
}
}
}
}
fwrite ($msglogTxt_handle, "<!-- End message block -->\r\n");

/* If we saved previous message entries to msglog.tmp, we need to add them back to this file */

if (@file_exists ($msglogTmp)) {
fwrite ($msglogTxt_handle, file_get_contents ($msglogTmp));
@unlink ($msglogTmp);
}
fclose ($msglogTxt_handle);
}

/* If we didn't save any images (message is text only), then delete the temporary directory */
if (!$savedImageFile && $image_path) {
@rmdir ($user_path . $dateString);
}

}

/* Now we put the HTML footers in place, creating index.html in the user directory */

if (!$errorFlag) {
$htmlFile = $user_path . "index.html";
$htmlFile_handle = @fopen ($htmlFile, "w+");
if (!$htmlFile_handle) {
if ($returnHttp500OnError) header("HTTP/1.0 500 Internal Error");
echo "ERROR: Cannot create file in user upload directory " . $user_path;
$errorFlag = True;
}
else {
fwrite ($htmlFile_handle, "<html>\r\n<head>\r\n<title>MMS Message Log for " . $_REQUEST['MMSFrom'] .
"</title>\r\n</head>\r\n<body>\r\n");
fwrite ($htmlFile_handle, "<h1>MMS Message Log for " . $_REQUEST['MMSFrom'] . "</h1>\r\n");
fwrite ($htmlFile_handle, file_get_contents ($user_path . "msglog.txt"));
fwrite ($htmlFile_handle, "</body>\r\n</html>\r\n");
fclose ($htmlFile_handle);
}

}



The script begins by performing some parameter validation.

The script tests to ensure that the “MMSFrom” variable is present and non-blank, which includes the phone number of the message sender. If this variable is not present or blank, the script returns an error.

The script tests to see if the “MMSSubject” variable is present. If this variable is not present, or blank, a default subject of “Multimedia Message” is used.

The script tests the “MMSFile” array to determine if there are any uploaded files associated with the request. An error is returned if there are no uploaded files included in the request.

The script creates a directory for the user if one does not already exist. User directories are created beneath the directory specified by the $upload_path variable.

The script verifies that it has the ability to create files in the user directory. If there is an error creating the user directory, or creating a temporary file in the user directory, the script returns an error.

The script creates a subdirectory beneath the user directory to contain content associated with the current MMS message. A separate subdirectory is created for each message because over time it is possible that the user may send in multiple files with the same name, and for this example we want to preserve both the new and old content, while also preserving the original file name. Creating a separate directory for each received MMS message is a simple way of accomplishing these ends. The script verifies that it can create this directory and that it can create temporary files in the newly created directory.

Within the user directory, the script maintains two files: msglog.txt and index.html

index.html is an HTML file that contains a log of all previously received MMS messages, converted into an HTML format. Messages are listed in this file in an order of newest to oldest.

msglog.txt contains a log of all previously received MMS messages, similar to index.html. However, this file does not contain the complete HTML, it contains only the converted messages without all necessary HTML headers. The script maintains this file, in addition to index.html to simplify the processing required to regenerate index.html each time a new MMS message is received.

After the script has validated the input parameters, it creates a backup of the msglog.txt file named msglog.tmp.

It then creates a new msglog.txt file, looping through the content of the MMS message and reformatting the MMS message into a simple block of HTML. The block of HTML begins with the subject line of the MMS message as a header, followed by a date/time stamp. The script then loops through the content of the MMS message. Text files that are part of the MMS message content are included directly in the HTML content. Image files are included as a direct image reference within the HTML content. SMIL files are skipped and discarded. Other content is included via a link within the HTML content.

After completing the processing of the MMS message, the script appends the previously received messages that were backed up to the msglog.tmp file to the msglog.txt file. The script then inserts the necessary HTML headers to create index.html based upon the content of the msglog.txt file.

Notes about installing/configuring PHP and testing the PHP script

Use of the mmsreceive.php script assumes that you have some familiarity with PHP. You can find more information about PHP at http://www.php.net.

If you are installing PHP on a Windows platform, an installation guide at http://www.iis-resources.com/modules/AMS/article.php?storyid=615 can be quite useful. The only real flaw in that installation guide is that when it registers the “.PHP” extension with IIS, it assumes that PHP is the only type of dynamic content that will be served by your web server. To manually register the “.PHP” extension with IIS, right click on “Web Sites” in the IIS Manager, select “Properties”, go to the “Home Directory” page, press the “Configuration” button, and here you can register the “.PHP” extension to use the “php5isapi.dll” executable.

Another potential headache in setting up PHP is that the web server needs to be configured to allow your script to write to the $upload_path directory in which you will place the received MMS message content. There are user contributed notes to the section of the PHP manual that documents “Handling HTTP File Uploads”, which is currently accessible on-line at http://php.net/manual/en/features.file-upload.php, which are quite helpful in this regard. Essentially, you must give the IIS user account (IUSR_yourservername) read, write and directory browse access to your upload directory.

These issues are outside the scope of NowSMS. To help you troubleshoot your script, we recommend that while developing and testing your script, instead of testing it initially with live MMS content, you test with simulated MMS content. A simple HTML web form can be deployed to test performing an HTTP File Upload Post to your PHP script. We have included an example simple HTML web form (mmsreceive.html) in the ZIP file download that contains the PHP script described by this document (http://www.nowsms.com/download/php2waymms.zip).

This web form is shown below. As you can see, this is a very simple form that allows you to input values for the MMSFrom and MMSSubject variables, as well as up to 12 uploaded files to be passed to your script as the MMSFile[] array.


<html>
<head>
<title>File Upload Test for MMSReceive.php Script</title>
</head>
<body>
<form enctype="multipart/form-data" action="mmsreceive.php" method="POST">
<h1>File Upload Test for MMSReceive.php Script</h1>
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
Sender Phone Number: <input name="MMSFrom" type="text" /><br />
Message Subject: <input name="MMSSubject" type="text" /><br />
Choose one or more files to upload:
<br/>
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input name="MMSFile[]" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>



Configuring NowSMS to call your PHP Script

It should be noted that we left this important detail to be covered last. The reason for this decision is simple. You should thoroughly test your script before configuring NowSMS to connect to it. Even if you are only using the test script that we have provided in this example, you should test the script with the sample web form before configuring NowSMS to connect to it. The reason we recommend this is because it is much easier to test and debug problems with the script, or with your PHP configuration in this manner. It is more difficult to test and debug problems when NowSMS is generating automated posts that are delivering actual MMS messages.

The first step of configuring NowSMS to connect to your PHP script is to define a connection to the script on the “MMSC Routing” page of the NowSMS configuration dialog. Press “Add” to add a routing.

The connection to a PHP script is defined as an external connection from the NowSMS MMSC, and it is defined similar to the process of defining an MM7 connection.

The “Account Name” and “Account Description” parameters can contain any value (use letters and numbers only). These values are used only for identifying the connection to the PHP script within NowSMS.

“Default Sender Address” should be left blank, and “Allow Sender Address Override” should be checked.

“Route messages to this account for recipient phone number(s)” should be left blank in most configurations.

“Route messages to VASP via” should be set to MM7.

“Server Address” should contain the URL for your PHP script (e.g., http://server/mmsreceive.php).

“Login Name” and “Password” should be left blank unless your script or server requires user authentication. If these parameters are non-blank, NowSMS will use them to build a basic authentication “Authorization:” header to be used when connecting to your PHP script.

“VASP ID”, “VAS ID”, “Service Code”, “Use Reverse Charging”, “Connection Type”, “3GPP MMS Version”, “MM7 Schema” and “Remove White Space from MM7 XML” can all be left at blank or default values as they will be ignored for this type of connection.

“Max Connections” should be left blank or set to 1 if you are using our example script. (Our example script may become confused if it is being run multiple times simultaneously.)

“Non-Standard MM7 Variations” should be set to “PHP Multipart File Upload”.

The above definition only tells NowSMS how it can connect to your PHP script. However, it does not configure NowSMS to actually call the PHP script for the processing of received MMS messages. Completing this process will vary based upon how you receive MMS messages. There are three different configuration alternatives:

1.)MMS messages are received via a GSM/GPRS modem. In this configuration, there is an “MMS Settings” option under “Properties” for your GSM/GRPS modem definition in the “SMSC” list of NowSMS. The “MMS Settings” dialog includes an option titled “MMSC Routing for Received Messages” which should be set to “Route to MM7” with the name assigned to your PHP script selected (from the “MMSC Routing” definition that we completed in the previous step).

2.)MMS messages are received via a direct connection to an operator MMSC using one of the supported protocols, including MM7, MM4 or EAIF. When any of these protocols are used, the operator MMSC will automatically connect to your Now SMS/MMS Gateway to deliver messages. An “MMSC VASP” account is defined for the mobile operator connection on your NowSMS installation. The “MMSC VASP” definition includes an option titled “MMSC Routing for Received Messages” which should be set to “Route to MM7” with the name assigned to your PHP script selected (from the “MMSC Routing” definition that we completed in the previous step).

3.)NowSMS is the MMSC. In this case, you can use the “Route messages to this account for recipient phone number(s)” option in the “MMSC Routing” definition to route messages to your PHP script based upon the recipient phone number. (For example, define 1234 in this field, and if any of your MMSC users send an MMS message to 1234, it will be routed to your PHP script.)

For more information on operator MMSC connections and GSM/GPRS modems, please see the section entitled “Connecting to an Operator MMSC” in the NowSMS manual. (Also available on-line at http://www.nowsms.com/documentation/ProductDocumentation/mms_notifications_and_c ontent/Connecting_to_operator_MMSC.htm.)
Nelson
New member
Username: Nelson

Post Number: 12
Registered: 01-2006
Posted on Tuesday, November 07, 2006 - 02:47 pm:   

Hi Bryce,

This looks interesting. But there's one thing that seems to be missing.

With 2-way SMS, I can define different commands to be triggered for different recipient phone numbers. So a message that comes in for one number (or a particular modem) can get routed to a different command than a message that comes in for a different number (or different modem).

How do I something like this for 2-way MMS, where I want to have messages that come in via different modems to different scripts?

Thanks,

-nelson
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 6791
Registered: 10-2002
Posted on Tuesday, November 07, 2006 - 04:59 pm:   

Hi Nelson,

Define separate "MMSC Routing" definitions for each of the different scripts that you want to use.

Each of your modems will have unique "MMS Settings", so you can define messages received on that modem to get routed to a different "MMSC Routing" ... which in turn routes them to different scripts.

The only flexibility that you don't have is that if you have a direct connection to an operator MMSC, and you are receiving MMS messages for multiple short codes, you can't route the received messages to different scripts based upon the short code if the messages are all being received over a single "MMSC VASP" definition. This shouldn't be a big issue, however, as generally speaking the real-world implementations that I have seen thus far use a separate "MMSC VASP" definition for each short code.

-bn
Adam Block
New member
Username: Ablock

Post Number: 14
Registered: 10-2006
Posted on Tuesday, November 07, 2006 - 11:54 pm:   

Bryce, this is great. For your customer using Ruby on Rails, this change makes processing incoming MMS extremely simple.

The server will get a "params" hash passed to it that contains the recieiving phone number (params["PhoneNumber"]), sender phone number (if override is checked; params["MMSFrom"]), subject line (params["MMSSubject"]), and an array of things that look like filehandles (params["MMSFile"][]).

I do have one question. What is the server expecting in response to indicate successful processing? In the normal MM7 mode I would send an MML DeliverRsp file. But that takes a transaction ID, which is missing from the multipart form post. Any suggestions?

Thanks!

/afb
dwi widayana
New member
Username: Dwi

Post Number: 6
Registered: 09-2006
Posted on Wednesday, November 08, 2006 - 01:21 am:   

Hi, Mr. Bryce..
can i do the same thing (bout directory to store received SMS, default & the variables used by script) with mmsreceive.php for receiving an SMS?
thanx for advance
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 6803
Registered: 10-2002
Posted on Thursday, November 09, 2006 - 05:31 pm:   

Hi Adam,

I've never used Ruby on Rails, but that looks to be something worth learning.

The server just wants to see an HTTP 200 OK response, it doesn't care what the content is. So basically, "HTTP/1.1 200 OK" followed by a blank line would be a sufficient response.

-bn
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 6804
Registered: 10-2002
Posted on Thursday, November 09, 2006 - 05:43 pm:   

Hi dwi widayana,

Receiving and processing SMS messages is a lot simpler than MMS.

MMS is complicated because an MMS message contains one or more files as its content, so we have to post this file content to a script. Getting these files posted to a script so that a script can understand them is tricky ... which is why we have this somewhat complex example.

But with SMS, we only have to pass some text.

The following thread has some links to some simple 2-way SMS examples: http://support.nowsms.com/discus/messages/1/4520.html

You'll notice in the example PHP script, the script receives the text of the SMS message in the following variable: $_REQUEST['text']

And it receives the sender address in this variable: $_REQUEST['sender']

If you want to write the message to a directory, it is just a matter of having the script open up a file, and writing these variables out to the file.

-bn
dwi widayana
New member
Username: Dwi

Post Number: 7
Registered: 09-2006
Posted on Tuesday, November 28, 2006 - 01:13 am:   

Hi, Mr. Bryce...

I badly need your help this time
I had tried the 2way-4011.php
on the gateway, I run the SMS and MMS as a service.
I use itegno 3000 GSM/GPRS modem & it's successfully tested.
I put my SIM card number, checked "Receive SMS msgs", storage is default, checked "support any outbound msg traffic".
On 2 way, I checked "Process Received SMS msg", use '*' for command prefix, & I write:
http://127.0.01:8800/2way-4011.php?sender=@@SENDER@@&text=@@FULLSMS@@&id=@@MESSAGEID@@&time=@@MSGTIME@@&date=@@MSGDATE@@
for command to execute.
that's all, i dun configure anything anymore.
then I try to send SMS but the reply is "Command not completed. Request return invalid content type:text/html".
is it because the script or I missed something to configure in the gateway?

on the sendsms-1057.php, you use port 81, why?

when i want to process incoming SMS so the gateway returned MMS, i don't have to check "process received MMS msg" right?
but should i configure the MMSC, SMS users, MMSC users, MMSC VASP, MMSC routing (i'm not intend to use the gateway as MMSC)?


i want to display the incoming &outgoing msg in html form. usually, i just use PHP for MySQL to take the data from database & display it. Since the gateway perform the incoming & outgoing msg in CSV, do you have the PHP script to take the data from there so ican display it???

really thanx for ur help ^_^
dwi widayana
New member
Username: Dwi

Post Number: 8
Registered: 09-2006
Posted on Thursday, November 30, 2006 - 07:57 am:   

anyone???
really need a big help right now...
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 6863
Registered: 10-2002
Posted on Monday, December 04, 2006 - 07:24 pm:   

Hi dwi widayana,

Do you intend your PHP script to return a response back to the sender?

If no, then UNcheck "Command returns response text".

If yes, then you need to modify your PHP script so that it returns a text response. Take a look at http://support.nowsms.com/discus/messages/1/3991.html for a simple example ... particularly note the header ("Content-Type: text/plain"); statement.

-bn
Rizki Gunawan
New member
Username: Mgunawan

Post Number: 4
Registered: 11-2006
Posted on Tuesday, December 05, 2006 - 05:14 am:   

NowSMS/inSMS.asp?sender=%2B628161152605&text=asdfasdfasdf%20asdfasd%20asdf%0D%0D PLG%20INDOSAT%20KTK%20REG%20FUN%20KRM%20KE%203949 &date=20061205&time=083105
08:31:06:678 [4] RetrieveURL: GET /NowSMS/inSMS.asp?sender=%2B628161152605&text=asdfasdfasdf%20asdfasd%20asdf%0D%0 DPLG%20INDOSAT%20KTK%20REG%20FUN%20KRM%20KE%203949 &date=20061205&time=083105 HTTP/1.1
User-Agent: Now SMS/MMS Gateway v2006.10.30
Accept: */*
Connection: Close
Host: localhost


08:31:06:678 [4] HttpResponseWait: Ok
08:31:06:678 [4] RetrieveURL: got http error response
08:31:06:678 [4] RetrieveURL: text/html
08:31:06:678 [4] ThreadProcessInboundSMS: HTTP response indicates error
08:31:06:678 [4] ThreadProcessInboundSMS: HTTP/1.1 400 Bad Request
Server: Microsoft-IIS/5.1
Date: Tue, 05 Dec 2006 01:31:06 GMT
Content-Type: text/html
Content-Length: 87

That message coming from SMSDEBUG.LOG, i have try to ask to other's but there no answer. i have ASP script, when I direcly run from web-browser that's OK. does any body know what's wrong with that?
dwi widayana
New member
Username: Dwi

Post Number: 9
Registered: 09-2006
Posted on Friday, December 08, 2006 - 01:36 am:   

do i have to configure the MMSC? because the reply of the SMS is MMS.
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 6874
Registered: 10-2002
Posted on Monday, December 11, 2006 - 08:00 pm:   


quote:

do i have to configure the MMSC? because the reply of the SMS is MMS.




You have to have MMS settings configured sufficiently that you can send an MMS message via the NowSMS web interface.

So, yes, this does mean that the MMSC must be configured and activated ... although the outbound route for MMS message delivery might be via a GSM/GPRS modem.

See http://www.nowsms.com/howmmsworks.htm for more information on "How MMS Works", and setup options.

-bn

Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 6875
Registered: 10-2002
Posted on Monday, December 11, 2006 - 08:05 pm:   


quote:

That message coming from SMSDEBUG.LOG, i have try to ask to other's but there no answer. i have ASP script, when I direcly run from web-browser that's OK. does any body know what's wrong with that?




This is the URL that NowSMS is trying to fetch:

http://localhost/NowSMS/inSMS.asp?sender=%2B628161152605&text=asdfasdfasdf%20asd fasd%20asdf%0D%0DPLG%20INDOSAT%20KTK%20REG%20FUN%20KRM%20KE%203949&date=20061205 &time=083105

(If there are any spaces in the above, they were inserted by the discussion board software here, and you should remove them.)

Try issuing that same request from your web browser, and see if it returns an error.

If you're using IIS, IIS might not be configured to accept "localhost" as a valid host name for your service if you have IIS configured as being a multihomed web server.
Terri O'Sullivan
New member
Username: Terri

Post Number: 11
Registered: 04-2006
Posted on Tuesday, January 23, 2007 - 12:04 am:   

Question to Bryce or other NowSMS support:
I'm trying to receive MMS using the mmsreceive.php as described above. I have the script running fine when posting to it using the sample mmsreceive.html. My version of NowSMS is 2006.10.31.

I'm using a Siemens MC35i + a Vodafone Ireland sim card, on which I am able to successfully send & receive SMS.

I tried sending an MMS to the number. Judging from the smsdebug.log, it did receive the message, or at least the SMS part of it. I've attached the smsdebug file (renamed to smsdebug_mms.txt).
text/plainsmsdebug_mms log file
SMSDEBUG_mms.txt (87.6 k)


There are a couple of normal SMS messages earlier in the log file so you can see that they were processed ok. The MMS one starts at 17:29.

It seems to have got the message ok and was attempting to process it at least. I disconnected the modem about 10 minutes after that, hence the failure messages.

I followed the instructions at http://www.nowsms.com/support/bulletins/tb-nowsms-016.htm (as repeated in this thread above) and also used the information in the manual in the section about Connecting to an Operator MMSC, pg. 125.
I haven't looked at sending MMS yet, might do that after but want to receive first.
So I have an MMS Routing set up. Screen shot showing the settings is attached.
MMSC Routing - settings screen shot
I'm not clear as to whether this is necessary for receiving - can you tell me if I do need it?

I think I also need it if I want to send MMS anyway.

I named the routing 'MMS Received' and as you can see on the other attached screen shot, I have selected that routing in the MMS Settings for my SMSC connection's properties.


MMS Settings screen shot
In my MMS Received routing, I set the Server Address to be http://localhost...../mmsreceive.php. I can't find mmsreceive.php in the smsdebug file, leading me to believe it hasn't been posted to at all.

A possible relevant issue:
As per the documentation, I also created a dial-up networking connection for my modem. But I noticed that NowSMS has also created its own dial-up connection, named NowSMS - Standard 19200 bps Modem (as I am using the standard Windows XP modem driver). On MMS Settings, I am using Modem:Standard 19200 bps Modem, as that's what I understood from the documentation.




Malcolm - Now Support
Moderator
Username: Malcolm

Post Number: 136
Registered: 12-2006
Posted on Tuesday, January 23, 2007 - 10:21 pm:   

Hi Terri,

It looks like the MMS message was successfully received.

You might want to try selecting the "Receive to MMS-IN Directory" setting first, and verify that the MMS messages you send to the modem get dumped as files into the "MMS-IN" directory.

That way we can determine if the problem is with MMS message reception, or routing to the script.

I'm guessing that the MMSC service is not activated, or that it is not properly starting because of a port conflict. When you use a GSM modem, because the MMS message notification is triggered by an inbound SMS, the SMS Gateway service retrieves the MMS message, but it then queues it for processing by the MMSC service. (If this is the case, you would see files in the VASPQ subdirectory.)

Make sure that the MMSC service is activated, and after activating it, go to the "MMSC" page of the NowSMS configuration, and see if any errors are reported about port conflicts. You might need to change a port number to get the MMSC service to run properly (even if you won't actually be connecting to any of the ports of the MMSC).

--
Malcolm
Now Wireless Support
Terri O'Sullivan
New member
Username: Terri

Post Number: 12
Registered: 04-2006
Posted on Thursday, January 25, 2007 - 11:40 pm:   

Malcolm,
Thanks for the reply. I need to try out your suggestions over the next day or two.
It could well be the port for the MMSC service - I have a local web host running as well.

I'll report back as to how it goes.
Thanks again.
Terri O'Sullivan
New member
Username: Terri

Post Number: 13
Registered: 04-2006
Posted on Sunday, January 28, 2007 - 04:44 pm:   

All working now, thanks.

I first changed the setting to 'Receive to MMS-in Directory' and that worked, the messages were coming in.
After that, it was the port number for the MMSC service.
All running well now.
Thanks again.
Terri
Terri O'Sullivan
New member
Username: Terri

Post Number: 14
Registered: 04-2006
Posted on Thursday, March 08, 2007 - 12:49 am:   

I'm back....
experiencing a problem with encoding of the text part of an MMS message received via the PHP script.

I'm sending an MMS from an Xda II phone, using an O2 Ireland sim card. The sim in my Siemens MC35 GPRS modem is a Vodafone Ireland prepay sim.

The MMS is received and processed ok but the text part of the message has ? characters where there should be spaces, also 2 extra characters at the start of each message, like this. For example, with the message 'white flowers' in the text part, I get this in the text file that the PHP script creates:
ÿþw h i t e f l o w e r s

I've modified the PHP script to also store the text in a MySQL database, where it has those two characters at the start and the spaces are replaced with question marks.
Note that the original message did not have spaces between the letters and it's always the same two characters at the start of the message.

If I send the MMS to another O2 sim in another XDA hadnset, the text is fine.

I'm attaching my MMSCWAP debug log - the last several messages received in it are MMS messages with one image and a text part, all of which have this problem.

Is this something to do with encoding of the MMS message or maybe it's PHP and nothing to do with NowSMS.
I tried checking the option to remove white space from the MM7 XML on my MMS routing, but no difference.


application/octet-streamMMSC WAP Debug log
MMSWAPDEBUG.LOG (441.4 k)
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 6961
Registered: 10-2002
Posted on Thursday, March 08, 2007 - 05:30 pm:   

Hi Terri,

Those two bytes (FF FE) are a Unicode signature, indicating that the text is Unicode. So each character is 16-bits (2 bytes), with standard ASCII text giving you the regular character followed by a null byte.

Another common signature at the start of a text file is EF BB BF, which indicates that the text is UTF-8 encoded. Standard ASCII text is encoded as a single byte, while extended characters are encoded in a multi-byte algorithm.

Normally, there would also be a "charset" parameter passed to the content-type header that would indicate the character set. But for some reason we don't pass that in the PHP multi-part post ... not that I think it would make any difference to PHP.

Hmm...

As a quick fix, I'd suggest looking for those signature bytes in a text file to determine the character set. (And assume UTF-8 if there are no signature bits, as that is the default character set used by most MMS clients, and the UTF-8 signature bytes will not always be present ... just skip them if they are present.)

For the future, most likely, we will need to convert any text components of a character set other than UTF-8 to UTF-8 before passing them to a script.

-bn
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 6988
Registered: 10-2002
Posted on Thursday, March 15, 2007 - 09:56 pm:   

Follow-up to Terri's message above.

We've put out an update that automatically converts MMS text parts that are in formats other than UTF-8 (including 16-bit Unicode) into UTF-8 ... when routing to this PHP script multipart file upload interface.

The update is currently available at http://www.nowsms.com/download/20070315.zip. (And this feature will be carried forward in releases after 2007.03.15.)

-bn
Terri O'Sullivan
New member
Username: Terri

Post Number: 15
Registered: 04-2006
Posted on Monday, April 23, 2007 - 11:56 pm:   

That sounds good, will try it out.

Bryce, I have another problem with using a PHP script to handle a received MMS message.

I want to send a text message in response when an MMS is received, as an acknowledgement of receipt.
So I put in a PHP location header to redirect to my existing PHP script that sends a message.
What happens then is that when it gets to the redirect, a HTTP 302 Object Moved response is received (as it should be), which seems to trigger a failure response to NowSMS so it sets a retry period for the MMS, thinking the receiving has failed.
The result of that is that it keeps processing the message and failing each time.

I tried changing the locatio header to a refresh header. WIth that, it doesn't fail but it doesn't seem to have done the refresh either.

So I'm wondering is there some setting somewhere to tell NowSMS MMSC Routing what to expect from the handling PHP script, so it doesn't barf when the location header is sent?
I think it's that because I have the same thing running on a PHP script I have to process received SMS, and I can see a RetrieveURL logged after it gets the 302 Object Moved.

Excerpt from my MMSCDebug.log is below - see where it says Object Moved to see the failure point.

22:52:45:750 [1] ParseMM1Recips: TO:+353879635887
22:52:45:750 [1] ThreadProcessVASPQ: mm1RecipArray count = 1
22:52:45:750 [1] ThreadProcessVASPQ: recipArray count = 1
22:52:45:765 [1] InetServerConnect: Connected to localhost (127.0.0.1:80)
22:52:45:765 [1] ThreadProcessVASPQ: POST /tcd_tosulli/portfolio/dissertation/handlereceivedmmsmsg.php HTTP/1.1
Host: localhost
Content-Length: 18918
Content-Type: multipart/form-data; boundary="---mime-boundary-03412429.A9F8836A---"
Connection: close


22:52:45:765 [1] ThreadProcessVASPQ: -----mime-boundary-03412429.A9F8836A---
Content-Disposition: form-data; name="MMSFrom"

+353862147949
-----mime-boundary-03412429.A9F8836A---
Content-Disposition: form-data; name="PhoneNumber"

0879635887
-----mime-boundary-03412429.A9F8836A---
Content-Disposition: form-data; name="MMSSubject"

Multimedia Message

-----mime-boundary-03412429.A9F8836A---
Content-Type: image/jpeg
Content-location: 1.jpg
Content-Disposition: form-data; name="MMSFile[]"; filename="1.jpg"
Content-Length: 17496

ÿØÿà
22:52:45:781 [1] HttpResponseWait: 100 Continue
22:52:46:171 [1] HttpResponseWait: ioctlsocket indicates end of request
22:52:46:171 [1] ThreadProcessVASPQ: mm7 - PHP Post - got unknown response
22:52:46:171 [1] ThreadProcessVASPQ: HTTP/1.1 302 Object Moved
Server: Microsoft-IIS/5.1
Date: Mon, 23 Apr 2007 21:52:45 GMT
Connection: close
Content-Type: text/html
X-Powered-By: PHP/5.1.4
Location: http://localhost/tcd_tosulli/portfolio/dissertation/handlersendmsg.php?txtToNumb er=+353862147949&selRecipient[]=33&txtMessage=MMS+Message+received+%28MsgID%3D30 7%29.&intFromUserID=28&txtFromNumber=+353879635887

<head><title>Document Moved</title></head>
<body><h1>Object Moved</h1>This document may be found <a HREF="http://localhost/tcd_tosulli/portfolio/dissertation/handlersendmsg.php?txt ToNumber=+353862147949&selRecipient[]=33&txtMessage=MMS+Message+received+%28MsgI D%3D307%29.&intFromUserID=28&txtFromNumber=+353879635887">here</a></body>
22:52:46:187 [1] ThreadProcessVASPQ: Outbound route MMS Received: setting retry for 462D1E82.mms
22:52:51:187 [1] ParseMM1Recips: TO:+353879635887
22:52:51:187 [1] ThreadProcessVASPQ: mm1RecipArray count = 1
22:52:51:187 [1] ThreadProcessVASPQ: recipArray count = 1
22:52:51:203 [1] InetServerConnect: Connected to localhost (127.0.0.1:80)
22:52:51:203 [1] ThreadProcessVASPQ: POST /tcd_tosulli/portfolio/dissertation/handlereceivedmmsmsg.php HTTP/1.1
mark
New member
Username: Drdoot

Post Number: 1
Registered: 05-2007
Posted on Monday, May 28, 2007 - 01:31 pm:   

Hi Bryce I have successfully implemented your example inbound MMS script into my website it works like a treat - great work :-)

Problem is now my device (siemens mc35) is out of storage space and cant accept any new MMS, haha ... does nowsms have a way I can overcome this?

Cheers
mark
New member
Username: Drdoot

Post Number: 2
Registered: 05-2007
Posted on Wednesday, May 30, 2007 - 04:49 pm:   

2 days left of the trial... id love to buy ... if i can make this last minor thing work!!
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 7168
Registered: 10-2002
Posted on Friday, June 15, 2007 - 07:12 pm:   

Hi Terri,

I apologise for the delay in response. Unfortunately, our logic can't handle a "3xx" redirect response when performing an HTTP POST.

The HTTP specification itself says that a user agent should not automatically redirect for a POST request in response to a 301 or 302 response code. (But notes that it is ok to do so for a 303 response code ... and notes that most existing user agents treat a 302 the same as a 303.)

In any event, it's not something that we can easily work into our logic.

Then again, maybe we could.

It's been 6 weeks since you posted this, so you've probably moved on or worked around this issue. If you're still working on it, let me know and I'll see what we can do.

-bn
Bryce Norwood - NowSMS Support
Board Administrator
Username: Bryce

Post Number: 7169
Registered: 10-2002
Posted on Friday, June 15, 2007 - 07:32 pm:   

Hi Mark,

I think you spoke with Keith Norris about this issue. I remember talking to him about it ... so if it wasn't you, someone else asked him a similar question.

The question perplexes me because even if the modem is configured to temporarily store the SMS messages before NowSMS retrieves them, NowSMS always deletes the message from the modem after processing.

The only way that it could fill up is if you were using another application.

But maybe you've been trying some different things ... or maybe moving the SIM back and forth between a phone and the modem.

The only suggestion I can offer would be to access the modem via HyperTerminal and manually delete the messages.

When you connect to the modem, type AT and press Enter ... make sure you get an OK response.

If you don't see what you are typing while you type, then enter the ATE1 command to tell the modem to echo back to the screen.

Issue the command AT+CMGF=0 to init the modem for PDU mode (you could do this in text mode, but I'm more familiar with guiding you through PDU mode).

Issue the command AT+CMGL=4

If there are any messages, the modem will respond back with something like the following:

+CMGL: x,#,,##
###############################################

+CMGL: y,#,,##
###############################################

We are interested in the "x" and "y" values right after the "+CMGL:" in the response. These are message numbers.

To delete a message, issue the command AT+CMGD=x, where "x" is one of the message numbers returned in the AT+CMGL=4 response.

When you're done, there should be no messages left, and AT+CMGL=4 should simply return OK.

If you need a trial extension, give us a call. Or, e-mail me at nowsms@now.co.uk ... put "Attention: Bryce" in the subject line, and include the "Installation Reference Code" reported on the "serial #" page of your NowSMS install. Also remind me of this thread and that I asked you to send me the e-mail (otherwise, I tend to get confused).

-bn