2

I have a .php file with this inside it:

<?php print_r($_POST); ?>
<?php

//create short variable names
$message_txt=strip_tags($_POST['message_txt']."\n\n".json_encode($_POST), "<p>");

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: thing<[email protected]>' . "\r\n";
$headers .= 'From: Website <[email protected]>';

mail($toaddress, "THING Website", $message_txt, $headers);

I would like to take text from a textView and send it through this php. Any ideas on how I can accomplish this? Thanks

2
  • That is not quiet simple but I can give yo an answer;) Commented Jan 31, 2016 at 11:26
  • Write me back if you got any questions, I can help you Commented Jan 31, 2016 at 11:52

1 Answer 1

1

Firstly you need this code in swift in order to parse the variables to the php file. I will show you the code and will explain it to you afterwards step by step.

Here the code for Swift:

func HttpRequest() {
    let myUrl = NSURL(string: "http://yourUrl.de/yourPhpScript.php");
    let request = NSMutableURLRequest(URL: myUrl!);
    request.HTTPMethod = "POST";

    let postString = "Message=\(textView.text)";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }


        do {
        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary



        if let parseJSON = json {
            var resultValue = parseJSON["status"] as? String
            print("result: \(resultValue)")

            if(resultValue=="Success")
            {
                // If result from php is success, do something...
            }


            else
            {
                // if result from php failed, do something...
            }


            dispatch_async(dispatch_get_main_queue(), {


                //Display alert with confirmation.
                let myAlert = UIAlertController(title: "Alert", message: "Your message", preferredStyle: UIAlertControllerStyle.Alert);

                let OkAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default){ action in


                }

                myAlert.addAction(OkAction)
                self.presentViewController(myAlert, animated: true, completion: nil);

            });

        }

        } catch {
            // report error
        }

    }
    task.resume()

}

Lets start with the explanation:

  1. In the first line you have a string referring to your .php file which might be on the server
  2. request.HTTPMethod is set to POST because you want to post something to the php file
  3. Now the postString: From my example there is a variable called "Message" in the php file and with the "=" you simply assign it a value which is "textView.text" in my case, you can append other variables as well by putting and "&" directly after it
  4. Then there is a bit of code, the request is ASYNC of course because you don't want to block your main thread, this is very important
  5. In the if let parseJSON will be the values of the re-parsed values from the php script, which will be available if the ASYNC returned a value, don't put it before it won't be available
  6. In your php file you could simply parse back a variable named "status" to show on success or on failure and you can handle that back in swift then

Now the php file:

<?php 

// If you want to connect to a server you have to do that
$servername = "";
$username = "";
$passwordServer = "";
$dbname = "";


// Create connection
$conn = mysqli_connect($servername, $username, $passwordServer, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

if (isset ($_POST["Message"]){
    $YourMessageFromSwift = $_POST["Message"];
}

// do what you want using php

$returnValue["status"] = "Success";
echo json_encode($returnValue);

mysqli_close($verbindung);
?>

Explanation:

  1. Firstly create the connection to your server (this is optional)
  2. Then use isset to evaluate if the variable is passed correctly
  3. Remember that the $_POST["Message"] are the same as in the swift file
  4. In the last step you could parse the status with json_encode

Hope this helps all of you:)

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks so much for this reply. Do I need to add a line in the .php to email the message to me? Do I combine me original php with this new one or should I just replace it?
I didn't try out your php code but if it was working you can combine them of course. You can add whatever you want in your php file.
normally when I use my old php file the only text I get in the email is []. I haven't tried your code with it yet though. @Anokrize
Yeah can't seem to get it to work. Could just be me though.
Do you have problems with my answer or your php script?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.