whit3hawks
whit3hawks

Reputation: 439

Redirect to a POST Route using PHP

What I am trying to do is send the username and the password to a GET route in larval, and then redirect to a post route with username,password, client_secret and client ID so that I can protect the client ID and the secret, because the request is send from an Android Application.

Please keep in mind that the API that I am trying to communicate with is explicitly build for my application.

Upvotes: 0

Views: 270

Answers (1)

Rakesh Gopal
Rakesh Gopal

Reputation: 590

To the best of my knowledge, it isn't possible to redirect to a POST request, along with POST variable, using the HTTP protocol (and so, PHP too can't do it). But, you can achieve the same effect using a set of work-arounds. I'm listing three of them here. You can choose the one that suits you.

1. Use Curl api to make the post request from PHP itself and send the required response

Instead of redirecting (note that client_id and client_secret might be secure info that you don't want to transmit to unknown client). So, you could make the POST request right from the PHP script and send the response given by the second URL/API.

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.secondsite.com/api.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=$uname&password=$pass&client_id=$c_id");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);
curl_close ($ch);

echo $server_output; // echo the output from the second server
// You might even require to get the headers from the response and send them too

?>

2. Using HTML & Javascript to make the POST request.

<form action='api.php' method='post' name='frm'>
<?php
    echo "<input type='hidden' name='username' value='$username'>";
    echo "<input type='hidden' name='password' value='$pass'>";
    echo "<input type='hidden' name='client_secret' value='$client_sec'>";
    echo "<input type='hidden' name='client_id' value='$client_id'>";
?>
</form>
<script language="JavaScript">
    document.frm.submit();
</script>

The idea is simple. The PHP page responds with a form containing all the fields you intend to post as a hidden-input. Then some in-line Javascript to submit the form, immediately.

3. If both the script are running on the same host, use SESSION Variables

And redirect for a GET request to the second URL. Note that it's essential for both the scripts to be on the same server for this to work. You can read on how to use PHP Sessions, here: How to use PHP Sessions

Upvotes: 2

Related Questions