Viewed   64 times

I have a form which I need to POST to multiple scripts. How can I do this the simplest way?

I know it could be done with Javascript, Curl or Snoopy class, but really which is the most simplest and best way to do this.

One of the scripts sends email and it's a php file, the other is hosted elsewhere.

Need to collect data on both scripts.

 Answers

1

The best way to go about it would be to first submit the form to your local script, then use CURL to POST the (filtered) data that was received to the remote script. Then just watch for the response.

Then simply send the email and process the response from the remote script in your local one.

Monday, December 19, 2022
5

I was able to so solve this problem using GroupSequence, it's explained here :

http://symfony.com/doc/current/validation/sequence_provider.html

Added some code to my Event class and it's all good

use SymfonyComponentValidatorGroupSequenceProviderInterface;

/**
 * @ORMTable(name="event")
 * @ORMEntity(repositoryClass="AppBundleRepositoryEventRepository")
 * @AssertGroupSequenceProvider
 */
class Event implements GroupSequenceProviderInterface
{
......
   /**
    * @var datetime $date
    *
    * @ORMColumn(name="date_debut_inscri", type="datetime")
    * @AssertGreaterThanOrEqual("today UTC", groups = {grp1})
    */
    protected $dateDebutInscri;
......

    public function getGroupSequence(){
            $groups = ['Default', 'Event'];

            if(!$this->getMyCheckBox())
            {
                $groups[] = 'grp1';
            }
            return $groups;
    }
}
Saturday, October 29, 2022
 
abbr
 
4

Try using a separate variable for errors, and not output error messages to the input field.

You could use global variables for this, but I'm not fond of them.

login.php

<?php 
$firstname = '';
$password  = '';
$username  = '';
$emailadd  = '';
$response  = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
    <fieldset>
        <p>Please enter your username and password</p>
    <legend>Login</legend>
        <div>
        <label for="fullname">Full Name</label>
            <input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
        </div>
        <div>
         <label for="emailad">Email address</label>
         <input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
        </div>
        <div>
        <label for="username">Username (between 5-10 characters)</label>
        <input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
        </div>
        <div>            
        <label for="password">Password (between 8-10 characters)</label>
        <input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
        </div>
        <div>            
            <input type="submit" name="" value="Submit" />
        </div>
    </fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
    print $response;         
}     
?>
//Footer stuff

loginprocess.php

//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
    //Here we concatenate the return values of your validation functions.
    $response .= validate_fname();
    $response .= validate_email();
    $response .= validate_username();
    $response .= validate_pw();
}    
//...or footer stuff.

functions.php

function validate_fname() {
    //Note the use of global...
    global $firstname;
    if (!empty($_POST['fname']))    {
        $form_is_submitted = true;
        $trimmed = trim($_POST['fname']);
        if(strlen($trimmed)<=150  && preg_match('/\s/', $trimmed)){
            $fname = htmlentities($_POST['fname']);
            //..and the setting of the global.
            $firstname = $fname;
            //Change all your 'echo' to 'return' in other functions.
            return"<p>You entered full name: $fname</p>";
        } else {
            return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
        }
    }
}

I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.

Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

Tuesday, October 4, 2022
 
4

You can use curl to grab a url and include post data. Once you have the response you can echo this into your div on your page. This link demonstrates curl and post: http://davidwalsh.name/curl-post

Monday, December 19, 2022
 
4

Here's my final working code. My web service needed one file (POST parameter name was "file") & a string value (POST parameter name was "userid").

/// <summary>
/// Occurs when upload backup application bar button is clicked. Author : Farhan Ghumra
 /// </summary>
private async void btnUploadBackup_Click(object sender, EventArgs e)
{
    var dbFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Util.DBNAME);
    var fileBytes = await GetBytesAsync(dbFile);
    var Params = new Dictionary<string, string> { { "userid", "9" } };
    UploadFilesToServer(new Uri(Util.UPLOAD_BACKUP), Params, Path.GetFileName(dbFile.Path), "application/octet-stream", fileBytes);
}

/// <summary>
/// Creates HTTP POST request & uploads database to server. Author : Farhan Ghumra
/// </summary>
private void UploadFilesToServer(Uri uri, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
    httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    httpWebRequest.Method = "POST";
    httpWebRequest.BeginGetRequestStream((result) =>
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            using (Stream requestStream = request.EndGetRequestStream(result))
            {
                WriteMultipartForm(requestStream, boundary, data, fileName, fileContentType, fileData);
            }
            request.BeginGetResponse(a =>
            {
                try
                {
                    var response = request.EndGetResponse(a);
                    var responseStream = response.GetResponseStream();
                    using (var sr = new StreamReader(responseStream))
                    {
                        using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                        {
                            string responseString = streamReader.ReadToEnd();
                            //responseString is depend upon your web service.
                            if (responseString == "Success")
                            {
                                MessageBox.Show("Backup stored successfully on server.");
                            }
                            else
                            {
                                MessageBox.Show("Error occurred while uploading backup on server.");
                            } 
                        }
                    }
                }
                catch (Exception)
                {

                }
            }, null);
        }
        catch (Exception)
        {

        }
    }, httpWebRequest);
}

/// <summary>
/// Writes multi part HTTP POST request. Author : Farhan Ghumra
/// </summary>
private void WriteMultipartForm(Stream s, string boundary, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
    /// The first boundary
    byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "rn");
    /// the last boundary.
    byte[] trailer = Encoding.UTF8.GetBytes("rn--" + boundary + "--rn");
    /// the form data, properly formatted
    string formdataTemplate = "Content-Dis-data; name="{0}"rnrn{1}";
    /// the form-data file upload, properly formatted
    string fileheaderTemplate = "Content-Dis-data; name="{0}"; filename="{1}";rnContent-Type: {2}rnrn";

    /// Added to track if we need a CRLF or not.
    bool bNeedsCRLF = false;

    if (data != null)
    {
        foreach (string key in data.Keys)
        {
            /// if we need to drop a CRLF, do that.
            if (bNeedsCRLF)
                WriteToStream(s, "rn");

            /// Write the boundary.
            WriteToStream(s, boundarybytes);

            /// Write the key.
            WriteToStream(s, string.Format(formdataTemplate, key, data[key]));
            bNeedsCRLF = true;
        }
    }

    /// If we don't have keys, we don't need a crlf.
    if (bNeedsCRLF)
        WriteToStream(s, "rn");

    WriteToStream(s, boundarybytes);
    WriteToStream(s, string.Format(fileheaderTemplate, "file", fileName, fileContentType));
    /// Write the file data to the stream.
    WriteToStream(s, fileData);
    WriteToStream(s, trailer);
}

/// <summary>
/// Writes string to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, string txt)
{
    byte[] bytes = Encoding.UTF8.GetBytes(txt);
    s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Writes byte array to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, byte[] bytes)
{
    s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Returns byte array from StorageFile. Author : Farhan Ghumra
/// </summary>
private async Task<byte[]> GetBytesAsync(StorageFile file)
{
    byte[] fileBytes = null;
    using (var stream = await file.OpenReadAsync())
    {
        fileBytes = new byte[stream.Size];
        using (var reader = new DataReader(stream))
        {
            await reader.LoadAsync((uint)stream.Size);
            reader.ReadBytes(fileBytes);
        }
    }

    return fileBytes;
}

I am very much thankful to Darin Rousseau for helping me.

Thursday, October 20, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :