I'm testing something. I would like to redirect my website (http://mywebsite.com) to a Landing Page (http://landingpage.com) ONLY when I pass a GET value. For example: id=23. So when it exists the page redirects.
My questions is that is there any script with the I can capture the list where I got redirected? I want the full link, like: http://mywebsite.com/index.php?id=23
Is there any possibility to capture that?
Also is there any possiblity to do the same with POST and capture that POST value on the Landing Page?
FOR GET:
You can simply attach $_SERVER['QUERY_STRING'] to the landingpage:
<?php
$get = ($_SERVER['QUERY_STRING']) ? "?".$_SERVER['QUERY_STRING']: "";
$url = 'http://landingpage.com'.$get;
header("Location: $url");
?>
FOR POST: use CURL
if($_POST){
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "http://landingpage.com",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $_POST,
);
curl_setopt_array($ch, $curlConfig)
$result = curl_exec($ch);
curl_close($ch);
}
Why not just store the data in a session variable? All you have to do is start the session again on the redirected page, and retrieve the session variables there.
Tutorial if you're not already aware of it: http://www.tizag.com/phpT/phpsessions.php
For example, on mywebsite.com:
session_start();
if (isset($_REQUEST['id'])) {
$_SESSION['id'] = $_REQUEST['id'];
$_SESSION['url'] = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
}
on landingpage.com:
session_start();
$url = $_SESSION['url'] . '?id=' . $_SESSION['id'];
echo $url;
Although pretty sure this won't work if the pages are stored on two different servers, so I may be misunderstanding the question. If it's between servers, you could use a cookie instead.
Related
I have two sites one is a.com another is b.com i am passing data using curl from a.com to b.com ,i am successfully able to pass data but the problem is i want to make it more secure so that site b.com responses after ensuring that the post was from site a.com.How to obtain this?
Code in site a.com
<?php
$some_data = array(
'message' =--> 'Hello World',
'name' => 'Chad'
);
$curl = curl_init();
// You can also set the URL you want to communicate with by doing this:
// $curl = curl_init('http://localhost/echoservice');
// We POST the data
curl_setopt($curl, CURLOPT_POST, 1);
// Set the url path we want to call
curl_setopt($curl, CURLOPT_URL, 'http://localhost/b.com');
// Make it so the data coming back is put into a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Insert the data
curl_setopt($curl, CURLOPT_POSTFIELDS, $some_data);
// You can also bunch the above commands into an array if you choose using: curl_setopt_array
// Send the request
$result = curl_exec($curl);
// Free up the resources $curl is using
curl_close($curl);
echo $result;
?>
Code in B.com
//I want to check here that the request was from a.com ,if it is ensured then i want to do //the rest of the work
echo 'Your message was: ' . $_REQUEST["message"] . ' and your name is: ' . $_REQUEST["name"];
?
You could check the $_SERVER['REFERER'] property, but it's very unreliable / unsafe.
A better approach would be to set up the B site with Basic Auth, or something similar, that you can authenticate against when you make the request from site A. Then you can add basic auth to your curl request from A to B. B checks the authentication, and if correct proceeds with the rest of the processing.
$_SERVER['REMOTE_ADDR'] would be the solution
if($_SERVER['REMOTE_ADDR']=="IP OF A.com"){
//exec code
}else{
log_error($_SERVER['REMOTE_ADDR'] has tried to access B.com at date());//that's an ex .
}
The simplest way to achive this, would be to create a Key that site a.com know and site b.com knows.
Then you could pass the key from one server to the other via curl, and as long as know one else knows what the key is they won't be able to access it (assuming you program it that way).
This is how most API's work, such as Facebook, Twitter, Linkedin, etc.
Your post data would then look like this for example (a.com):
$some_data = array(
'message' =--> 'Hello World',
'name' => 'Chad',
'key' => '4h9rj8wj49tj0wgj0ejwrkw0jt0ekv0ijspxodxk9rje0rg9tskvep9rrgt9wkrgte'
);
Then on b.com you would just do this:
if(!isset($_POST['key']) && $_POST['key'] != '4h9rj8wj49tj0wgj0ejwrkw0jt0ekv0ijspxodxk9rje0rg9tskvep9rrgt9wkrgte'){
die("Invalid Key");
}
You can use a public/private pair system. A simple version would be like this:
//a.com
$keys = array(
'publicKey1' => 'privateKey1',
'publicKey2' => 'privateKey2',
//...
'ksjdlfksjdlf' => '989384kjd90903#kjskdjdsd'
);
$publicKeys = array_keys($keys);
//get a random key from pool
$publicKey = $publicKeys[rand(0, count($publicKeys))];
$privateKey = $keys[$publicKey];
//your data...
$some_data = array(
'message' => 'Hello World',
'name' => 'Chad'
);
/*generate a verification code from data...*/
//add public key to data
$some_data['key'] = $publicKey;
//sort data (to always generate same verification code regardless of params order)
uksort($some_data);
//generate code with your private key
$verificationKey = sha1($privateKey . http_build_query($some_data) . $privateKey);
//add verification code to sent data
$some_data['verification_code'] = $verificationKey;
//send data
curl_exec(...);
and on b.com:
$keys = "same keys that exist on a.com";
if (!isset($_POST['key']) || !isset($_POST['verification_code']) || !isset($keys[$_POST['key'])) {
//do something to handle invalid request
}
$verificationKey = $_POST['verification_code'];
$privateKey = $keys[$_POST['key']];
//remove verification code from data
unset($_POST['verification_code']);
//sort data
uksort($_POST);
$checkKey = sha1($privateKey . http_build_query($_POST) . $privateKey);
//validate key
if ($checkKey != $verificationKey) {
//handle invalid data
}
//verified. do something with $_POST
Here's my problem. A few months ago, I wrote a PHP script to get connected to my account on a website. I was using CURL to get connected and everything was fine. Then, they updated the website and now I am no longer able to get connected. The problem is not with CURL, as I do not get any error from CURL, but it is the website itself which tells me that I am not able.
Here's my script :
<?php
require('simple_html_dom.php');
//Getting the website main page
$url = "http://www.kijiji.ca/h-ville-de-quebec/1700124";
$main = file_get_html($url);
$links = $main -> find('a');
//Finding the login page
foreach($links as $link){
if($link -> innertext == "Ouvrir une session"){
$page = $link;
}
}
$to_go = "http://www.kijiji.ca/".$page->href;
//Getting the login page
$main = file_get_html($to_go);
$form = $main -> find("form");
//Parsing the page for the login form
foreach($form as $f){
if($f -> id == "login-form"){
$cform = $f;
}
}
$form = str_get_html($cform);
//Getting my post data ready
$postdata = "";
$tot = count($form->find("input"));
$count = 0;
/*I've got here a foreach loop to find all the inputs in the form. As there are hidden input for security, I make my script look for all the input and get the value of each, and then add them in my post data. When the name of the input is emailOrNickname or password, I enter my own info there, then it gets added to the post data*/
foreach($form -> find("input") as $input){
$count++;
$postdata .= $input -> name;
$postdata .= "=";
if($input->name == "emailOrNickname"){
$postdata.= "my email address ";
}else if($input->name == "password"){
$postdata.= "my password";
}else{
$postdata .= $input -> value;
}
if($count<$tot){
$postdata .= "&";
}
}
//Getting my curl session
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $to_go,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postdata,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEJAR => 'cookie.txt'
));
$result = curl_exec ($ch);
curl_close ($ch);
echo $result;
?>
CURL nor PHP return any error. In fact, it returns the webpage of the website, but this webpage tells me that there's an error that occurred, as if there was missing some post data.
What do you think can cause that ? Could it be some missing curl_setopts ? I've got no idea, do you have any ?
$form = $main -> find("form") finds first occurrence of element
and that is <form id="SearchForm" action="/b-search.html">
you will need to change that into $form = $main->find('#login-form')
Most likely the problem is that the site (server) checks cookies. This process mainly consists of two phases:
1) When you visit the site first time on some page, e.g. on the login page, the server sets cookies with some data.
2) On each subsequent page visit or POST request the server checks cookies it has set.
So you have to reproduce this process in your script which mean you have to use CURL to get any page from the site, including the login page which should be getting by CURL, not file_get_html.
Furthemore you have to set both CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE options to the same absolute path value ('cookies.txt' is a relative path) on each request. This is necessary in order to enable cookies auto-handling (session maintaining) within entire series of requests (including redirects) the script will perform.
i write some code in php.
I wanna get last redirecting adress on this is site:
fluege.de
I posting this is;
$dep= "sFlightInput[accDep]=ZRH";
$arr= "sFlightInput[accArr]=VIE";
$depregion= "sFlightInput[accDepRegion]=";
$arrregion= "sFlightInput[accArrRegion]=";
$multidep= "sFlightInput[accMultiAirportDep]=ZRH";
$multiarr= "sFlightInput[accMultiAirportArr]=ZRH";
$ftype = "sFlightInput[flightType]=RT";
$depcity = "sFlightInput[depCity]=Zürich+-+Flughafen+(ZRH)+-+Schweiz";
$arrcity = "sFlightInput[arrCity]=Wien+-+Internationaler+Flughafen+(VIE)+-+Österreich";
$sdate = "sFlightInput[departureDate]=29.03.2014";
$srange = "sFlightInput[departureTimeRange]=2";
$rdate ="sFlightInput[returnDate]=05.04.2014";
$rrange = "sFlightInput[returnTimeRange]=2";
$adt = "sFlightInput[paxAdt]=1";
$chd ="sFlightInput[paxChd]=0";
$inf = "sFlightInput[paxInf]=0";
$cabin = "sFlightInput[cabinClass]=Y";
$airline = "sFlightInput[depAirline]=";
$send = $dep.$arr.$depregion.$arrregion.$multidep.$multiarr.$ftype.$depcity.$arrcity.$sdate.$srange.$rdate.$rrange.$adt.$chd.$inf.$cabin.$airline;
I using this ;
echo getLastEffectiveUrl("http://www.fluege.de/flight/wait/".$send);
And there is function
function getLastEffectiveUrl($url)
{
// initialize cURL
$curl = curl_init($url);
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
));
// execute the request
$result = curl_exec($curl);
// fail if the request was not successful
if ($result === false) {
curl_close($curl);
return null;
}
// extract the target url
$redirectUrl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
curl_close($curl);
return $redirectUrl;
}
They code must give this url;
www.fluege.de/wait/?accDep=&accArr=&accDepRegion=&accArrRegion=&accMultiAirportDep=&accMultiAirportArr=&flightType=RT&depCity=Z%FCrich+-+Flughafen+%28ZRH%29+-+Schweiz&arrCity=Wien+-+Internationaler+Flughafen+%28VIE%29+-+%D6sterreich&departureDate=04.04.2014&departureTimeRange=2&returnDate=20.04.2014&returnTimeRange=2&paxAdt=1&paxChd=0&paxInf=0&cabinClass=Y&depAirline=
But i need ;
http://www.fluege.de/flight/encodes/sFlightInput/5f8ccad612bafb69e7693f04cfaf1458/ (etc)
The code you provided does not handle cookies, so if the site you are query'ing requires this, your code won't work.
I checked http://php.net/manual/en/function.curl-setopt.php, but it seems like cURL cannot store cookies in memory. By adding the following line under curl_setopt_array, cookies are kept in a temporary file:
CURLOPT_COOKIEJAR => tempnam(sys_get_temp_dir(), 'cookiejar'),
However, I did not get your specific case to work. I noticed that the URL you create does not contain a question mark, and that the URL that your script creates does not redirect at all; it returns with 200 OK. I checked this using the following shell command:
curl -LI 'http://www.fluege.de/flight/wait/sFlightInput\[accDep\]=ZRHsFlightInput\[accArr\]=VIEsFlightInput\[accDepRegion\]=sFlightInput\[accArrRegion\]=sFlightInput\[accMultiAirportDep\]=ZRHsFlightInput\[accMultiAirportArr\]=ZRHsFlightInput\[flightType\]=RTsFlightInput\[depCity\]=Zürich+-+Flughafen+(ZRH)+-+SchweizsFlightInput\[arrCity\]=Wien+-+Internationaler+Flughafen+(VIE)+-+ÖsterreichsFlightInput\[departureDate\]=29.03.2014sFlightInput\[departureTimeRange\]=2sFlightInput\[returnDate\]=05.04.2014sFlightInput\[returnTimeRange\]=2sFlightInput\[paxAdt\]=1sFlightInput\[paxChd\]=0sFlightInput\[paxInf\]=0sFlightInput\[cabinClass\]=YsFlightInput\[depAirline\]='
If it's unclear what the URL should look like, you should contact fluege.de to ask them how to use their API.
I want to loginto a site using curl and then get resulting page. for example i want to run a script and see my yahoo mail page. i wrote something like this.
//set POST variables
$url = 'http://localhost/test/login';
$fields = array(
'username'=>'abc',
'password'=>'def'
);
$fields_string='';
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result;
login.php
echo $_POST['username'];
echo $_POST['password'];
header('Location: http://www.xyz.com/');
script posts data to login.php but contents of xyz.com are not shown.
By logging into a Website you normaly generate a Session ID which is stored in a Session. By logging in with CURL you didn't save this cookie in your Client Browser, you maybe logged in with your server, but there is no way to be logged in with your client.
And of course change this line:
echo $_POST['username'];
echo $_POST['password'];
header('Location: http://www.xyz.com/');
to the following:
header('Location: http://www.xyz.com/');
echo $_POST['username'];
echo $_POST['password'];
or use ob_start(); on the beginning of your script.
...which doesn't make sence because you'll never see that content ;)
Your problem is the two echo calls before the call to header.
According to the documentation header must be called before any other output is sent.
http://php.net/manual/en/function.header.php
I have an online gateway which requires an HTML form to be submitted with hidden fields. I need to do this via a PHP script without any HTML forms (I have the data for the hidden fields in a DB)
To do this sending data via GET:
header('Location: http://www.provider.com/process.jsp?id=12345&name=John');
And to do this sending data via POST?
You can't do this using PHP.
As others have said, you could use cURL - but then the PHP code becomes the client rather than the browser.
If you must use POST, then the only way to do it would be to generate the populated form using PHP and use the window.onload hook to call javascript to submit the form.
here is the workaround sample.
function redirect_post($url, array $data)
{
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function closethisasap() {
document.forms["redirectpost"].submit();
}
</script>
</head>
<body onload="closethisasap();">
<form name="redirectpost" method="post" action="<? echo $url; ?>">
<?php
if ( !is_null($data) ) {
foreach ($data as $k => $v) {
echo '<input type="hidden" name="' . $k . '" value="' . $v . '"> ';
}
}
?>
</form>
</body>
</html>
<?php
exit;
}
A better and neater solution would be to use $_SESSION:
Using the session:
$_SESSION['POST'] = $_POST;
and for the redirect header request use:
header('Location: http://www.provider.com/process.jsp?id=12345&name=John', true, 307;)
307 is the http_response_code you can use for the redirection request with submitted POST values.
Another solution if you would like to avoid a curl call and have the browser redirect like normal and mimic a POST call:
save the post and do a temporary redirect:
function post_redirect($url) {
$_SESSION['post_data'] = $_POST;
header('Location: ' . $url);
}
Then always check for the session variable post_data:
if (isset($_SESSION['post_data'])) {
$_POST = $_SESSION['post_data'];
$_SERVER['REQUEST_METHOD'] = 'POST';
unset($_SESSION['post_data']);
}
There will be some missing components such as the apache_request_headers() will not show a POST Content header, etc..
It would involve the cURL PHP extension.
$ch = curl_init('http://www.provider.com/process.jsp');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John");
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL
$resp = curl_exec($ch);
/**
* Redirect with POST data.
*
* #param string $url URL.
* #param array $post_data POST data. Example: array('foo' => 'var', 'id' => 123)
* #param array $headers Optional. Extra headers to send.
*/
public function redirect_post($url, array $data, array $headers = null) {
$params = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data)
)
);
if (!is_null($headers)) {
$params['http']['header'] = '';
foreach ($headers as $k => $v) {
$params['http']['header'] .= "$k: $v\n";
}
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if ($fp) {
echo #stream_get_contents($fp);
die();
} else {
// Error
throw new Exception("Error loading '$url', $php_errormsg");
}
}
Use curl for this. Google for "curl php post" and you'll find this: http://www.askapache.com/htaccess/sending-post-form-data-with-php-curl.html.
Note that you could also use an array for the CURLOPT_POSTFIELDS option. From php.net docs:
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. This can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.
Your going to need CURL for that task I'm afraid. Nice easy way to do it here: http://davidwalsh.name/execute-http-post-php-curl
Hope that helps
Alternatively, setting a session variable before the redirect and test it in the destination url, can solve this problem for me.
You have to open a socket to the site with fsockopen and simulate a HTTP-Post-Request.
Google will show you many snippets how to simulate the request.
I used the following code to capture POST data that was submitted from form.php and then concatenate it onto a URL to send it BACK to the form for validation corrections. Works like a charm, and in effect converts POST data into GET data.
foreach($_POST as $key => $value) {
$urlArray[] = $key."=".$value;
}
$urlString = implode("&", $urlArray);
echo "Please <a href='form.php?".$urlString."'>go back</a>";
An old post but here is how I handled it. Using newms87's method:
if($action == "redemption")
{
if($redemptionId != "")
{
$results = json_decode($rewards->redeemPoints($redemptionId));
if($results->success == true)
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml?a=redemptionComplete';
// put results in session and redirect back to same page passing an action paraameter
$_SESSION['post_data'] = json_encode($results);
header("Location:" . $redirectLocation);
exit();
}
}
}
elseif($action == "redemptionComplete")
{
// if data is in session pull it and unset it.
if(isset($_SESSION['post_data']))
{
$results = json_decode($_SESSION['post_data']);
unset($_SESSION['post_data']);
}
// if you got here, you completed the redemption and reloaded the confirmation page. So redirect back to rewards.phtml page.
else
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml';
header("Location:" . $redirectLocation);
}
}
Yes, you can do this in PHP e.g. in
Silex or Symfony3
using subrequest
$postParams = array(
'email' => $request->get('email'),
'agree_terms' => $request->get('agree_terms'),
);
$subRequest = Request::create('/register', 'POST', $postParams);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
A workaround wich works perfectly :
In the source page,, start opening a session and assign as many values as you might want.
Then do the relocation with "header" :
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
$_SESSION['val1'] = val1;
...
$_SESSION['valn'] = valn;
header('Location: http//Page-to-redirect-to');
?>
</head>
</html>
And then, in the targe page :
<!DOCTYPE html>
<?php
session_start();
?>
<html>
...
<body>
<?php
if (isset($_SESSION['val1']) && ... && isset($_SESSION['valn'])) {
YOUR CODE HERE based on $_SESSION['val1']...$_SESSION['valn'] values
}
?>
</body>
</html>
No need of Javascript nor JQuery..
Good luck !