Send $_POST to 2 php files at once - php

i have no idea how to solve a problem with sending $_POST. I want to fill a form at example.com
//at example.com
<form action="foo.php" method="post" >
<input name="bar1" type="text" />
<input name="bar2" type="text" />
<input name="bar3" type="text" />
<input value="Send" type="submit" />
</form>
and then it goes to foo.php :
<?php //foo.php
echo 'added: <p>'.$_POST['bar1'].'<br />'.$_POST['bar2'].'<br />'.$_POST['bar3'];
?>
and in the same time it also send
$_POST['bar1'], $_POST['bar2'], $_POST['bar3']
to exampledomain.com/foobar.php where it can be saved to a file - that's not a problem.
I don't know how to send info to both php scripts at once - one is external one. I guess i have to send it somehow inside foo.php
There is kind of solution - redirecting to exampledomain.com/foobar.php inside foo.php but it isn't acceptable in my case - I want to do it without making user exit example.com
Thanks in advance and hope you can undestand my problem - if not just ask a comment
EDIT: Based on Pete Herbert Penito's answer:
<?php //inside foo.php
$url = 'http://exampledomain.com/foobar.php';
$fields_string='';
foreach($_POST 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($_POST));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
?>

I would use CURL to construct a post request:
<?php
// these variables would need to be changed to be your variables
// alternatively you could send the entire post constructed using a foreach
if(isset($_POST['Name'])) $Name = $_POST['Name'];
if(isset($_POST['Email'])) $Email = $_POST['Email'];
if(isset($_POST['Message'])) $Message= htmlentities($_POST['Message']);
$Curl_Session = curl_init('http://www.site.com/cgi-bin/waiting.php');
curl_setopt ($Curl_Session, CURLOPT_POST, 1);
curl_setopt ($Curl_Session, CURLOPT_POSTFIELDS, "Name=$Name&Email=$Email&Message=$Message");
curl_setopt ($Curl_Session, CURLOPT_FOLLOWLOCATION, 1);
curl_exec ($Curl_Session);
curl_close ($Curl_Session);
?>
From Link:
http://www.askapache.com/php/sending-post-form-data-php-curl.html

In your foo.php:
<?php
include 'http://exampledomain.com/foobar.php';
Note: you need to enable allow_url_fopen in your php.ini file.

You will need to do one of the POST's with javascript ajax.
Then the real post which will redirect the browser like normal.
http://www.w3schools.com/jquery/ajax_post.asp
$(selector).post(url,data,success(response,status,xhr),dataType)

Related

php- whats the error?

File Name: sms1.php
Located at: http://techmentry.com/sms1.php
PHP code of sms1.php:
<?php
//Variables to POST
$user = "hidden";
$password = "hidden";
$mobiles = "$_POST[phone]";
$message = "$_POST[msg]";
$sender = "$_POST[sender]";
//Initialize CURL data to send via POST to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.hidden/sendhttp.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"user=$user&
password=$password&
mobiles=$mobiles&
message=$message&
sender=$sender"
);
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result";
?>
<br><br><br>
<form name='sms' action='' method='post'>
Phone number<br/><input type='text' name='phone' value='' maxlength=12/>
<br/>
Sender ID (from) <br/><input type='text' name='sender' value='' maxlength=15/>
<br/>
Message : <br/><textarea rows=5 cols=30 name='msg'></textarea>
<br/>
<input type='submit' value='Send'>
</form>
Please see the output on http://techmentry.com/sms1.php . It is already displaying an error code (105) (already - because it should show the error code when user click send button). 105 error code means missing 'password' parameter. But I have already stated the password in the code.
Please help :)
You're not checking whether the form was submitted, so you're running the cURL code even when displaying the initial form. You need to do:
Change the submit button to:
<input type='submit' name='submit' value='Send'>
and change the PHP code at the top to:
<?php
if (isset($_POST['submit'])) {
//Variables to POST
$user = "hidden";
$password = "hidden";
$mobiles = $_POST['phone'];
$message = $_POST['msg'];
$sender = $_POST['sender'];
//Initialize CURL data to send via POST to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.hidden/sendhttp.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('user' => $user,
'password' => $password,
'mobiles' => $mobiles,
'message' => $message,
'sender' => $sender)
);
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result";
}
?>
The other change I made was to use an array instead of a string as the parameter for CURLOPT_POSTFIELDS. This avoids having to urlencode() all the parameters, which you weren't doing.
And the proper way to assign variables from an associative array is like:
$mobiles = $_POST['phone'];
The key should be in quotes, the array name itself should not. Your way worked because of the way variable interpolation in strings works, but it's not generally done that way unless you're embedding the variable in a longer string, like:
echo "The phone number is $_POST[phone]";
Many programmers avoid this syntax entirely, preferring concatenation:
echo "The phone number is ". $_POST['phone'];
That's a stylistic choice, there's no widespread concensus either way.
"Using PHP variables and newlines within strings often results in problems, could you try the following:
if ($_SERVER['REQUEST_METHOD'] == "POST")){
//this prevents code being executed on page load
$user = "hidden";
$password = "hidden";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.hidden/sendhttp.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
//removed newlines and variables in string
curl_setopt($ch, CURLOPT_POSTFIELDS,"user=".$user.
"&password=".$password.
"&mobiles=". $_POST['phone'].
"&message=". $_POST['msg'] .
"&sender=".$_POST['sender']);
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result";
}
?>
<br><br><br>
<form name="sms" action="" method="post">
Phone number<br/><input type="text" name="phone" value="" maxlength="12"/>
<br/>
Sender ID (from) <br/><input type="text" name="sender" value="" maxlength="15"/>
<br/>
Message : <br/><textarea rows="5" cols="30" name="msg"></textarea>
<br/>
<input type="submit" value="Send">
</form>
Qualifier: I'm learning PHP.
Shouldn't you wrap your operations in if(isset($_POST['submit']))?
It is processing before you submit anything.

send data (POST Method) from local to server, by cURL the server reveive EMPTY RECORD

i send data to server from pc local through this form :
<form method="post" action="proses.php">
<input type="hidden" name="id"><br>
Tanggal <input type="text" name="tgl"><br>
Pesan <textarea name="isi" cols="29" rows="5"></textarea> <br>
Nomor Hp <input type="text" name="nope"><br>
<input type="submit" name="submit" value="Submit"> </form>
and this is code proses.php
<?php
$id = $_POST['id'];
$tgl = $_POST['tgl'];
$isi = $_POST['isi']; $nope= $_POST['nope'];
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, 'http://adibiken.com/SEM/kir.php');
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, "id=".$id."&tgl=".$tgl."&isi=".$isi."&nope=".$nope);
curl_setopt($curlHandle, CURLOPT_HEADER, 0);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandle, CURLOPT_TIMEOUT,30);
curl_setopt($curlHandle, CURLOPT_POST, 1);
curl_exec($curlHandle);
curl_close($curlHandle); ?>
this is code for kir.php ( in server )
<?php $id = $_POST['id']; $tgl = $_POST['tgl']; $isi = $_POST['isi']; $nope = $_POST['nope'];
$quer = "INSERT INTO `adibiken_sem`.`inbox` (`id`,`tgl` ,`isi` ,`nope`)VALUES ( '$id','$tgl', '$isi', '$nope')";
mysql_query($quer); ?>
PROBLEM : data are have been successful SENDING with EMPTY RECORD IN DATBASE SERVER...
need help please
Don't know if this is the problem but for sure
VALUES ( '$id','$tgl', '$isi', '$nope')"
should be
VALUES ( '".$id."','".$tgl."', '".$isi."', '".$nope."')"
In file "proses.php" try using "&" instead of "&". Also in file kir.php ( in server ) run print_r($_POST) or log the whole array somewhere to chceck if you are recieving the correct variable names.
use the http_build_query(...) to form postfields from array.
$request = http_build_query($_POST);
...
curl_setopt($curlHandle, CURLOPT_POSTFIELDS,$request)
If you getting correct values in $_POST array then something is wrong with your SQL syntax. You can try to execute your query in phpMyAdmin or something else and debug it.
It might happen that MySQL fires an error, but you could not see it. You can get any output from kir.php including error messages (it is enabled on your server):
$curResponse = curl_exec($curlHandle);
echo $curResponse;

sending all $_POST[] value to "nextpage."

Suppose i have many values here with form method POST
$_POST["value1"]
$_POST["value2"]
$_POST["value3"]
$_POST["value4"]
$_POST["value5"]
$_POST["value6"]
$_POST["value7"]
and i want to send them to nextpage.php
any function to do that? Besides using
<form method="POST" action="nextpage.php">
<input type="hidden" name="value1" value="value1 />
</form>
Passing without session
If there is no security concern and your post data contains something like search parameters . For example $_POST has
array('query'=>'keyword', 'orderby' => 'name', 'range' => '4-10' )
You can generate a query string from that data using http_build_query and create anchor tag for user to click and pass on that data to next page along with url.
$url = 'nextpage.php?' . http_build_query($_POST);
it will generate a url like nextpage.php?query=keyword&orderby=name&range=4-10 that you can use in html anchor tag and in next page you can get it from $_GET.
Using session
Alternatively you already have the option you storing it in $_SESSION and after using destroy the session in order to keep your site performance up.
store all your values in $_SESSION and use it in next page, or you can create URL using these values and redirect your page to nextpage.php
For passing post values to next page store the complete $_POST superglobal array variable into session and then on next page you can access those values using $_SESSION variable
Alternatively you can use curl to send HTTP request to next page using POST method
Then those variables will be accessible using $_POST variable on next page
Please refer the code snippet mentioned below as an example for sending HTTP request using post method through curl
$url='http://203.114.240.77/paynetz/epi/fts';
$data = array('login' => '11','pass' => 'Test#123','ttype' =>'NBFundTransfer','prodid'=>'NSE','amt'=>50,'txncurr'=>'INR','txnscamt'=>0,'clientcode'=>007,'txnid'=>uniqid(),'date'=>date('d/m/Y H:i:s'),'custacc'=>'123456789');
$datastring = http_build_query($data);
//die($url.'?'.$datastring);
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 180);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
$output = curl_exec($ch);
//echo $output; die;
curl_close($ch);
you can use Session or cookie to access to other page
Use this code.
<!DOCTYPE HTML>
<html>
<head>
<title>First page</title>
</head>
<body onload="document.getElementById('send').submit()">
<form id="send" action="next_page.php" style="display: none;">
<?PHP
foreach($_POST as $key => $val)
{
echo '<input type="hidden" name="'.$key.'" value="'.$val.'" />';
}
?>
</form>
</body>
</html>

Why $_POST array is null?

I have the following code:
<?php
define('ENVIRONMENT', 'tests');
$_POST['id']='AccountPagesView.a_book/45';
$_POST['old_value']='1';
$_POST['value']='2';
header("Location: http://localhost/index.php/welcome/update_record");
?>
I need to set $_POST array in this script and load script by url. But the script from url tells me that $_POST array is null. Why? How can I set the $_POST array and send it to script by url? Thank you in advance.
UPDATE:
I have some code which must be tested, and there is some script on the url "http://localhost/index.php/welcome/update_record", and it uses values from $_POST array; so, I can't change this script, and I want to test it. How can I do it?
UPDATE2:
<?php
//include ('\application\controllers\welcome.php');
define('ENVIRONMENT', 'tests');
$_POST_DATA=array();
$_POST_DATA['id']='AccountPagesView.a_book/45';
$_POST_DATA['old_value']='1';
$_POST_DATA['value']='2';
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/index.php/welcome/update_record');
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST_DATA);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_exec($ch);
?>
You cannot. A redirect will always result in the target page loaded via GET.
However, you could use the session to store these values. Call session_start(); on both pages and use the superglobal array $_SESSION instead of $_POST.
I believe this is what you need to send POST values from one PHP script to another, without using JS, If you absolutely don't want to use $_SESSION though that is what you should be using.
$ch = curl_init();
$data = array('id' => 'AccountPagesView.a_book/45', 'old_value' => '1', 'value' => '2',);
curl_setopt($ch, CURLOPT_URL, 'http://path-to/other.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
$_POST only exists if the request was sent through the POST method, which means a form was sent.
You could use $_SESSION instead.
This is one of the prime reason why $_SESSION's should be used. See this other question for an explanation: PHP - Pass POST variables with header()?
<?php
session_start();
define('ENVIRONMENT', 'tests');
$_SESSION['id']='AccountPagesView.a_book/45';
$_SESSION['old_value']='1';
$_SESSION['value']='2';
header("Location: http://localhost/index.php/welcome/update_record");
Then on index.php/welcome/update_record
<?php
session_start();
define('ENVIRONMENT', 'tests');
$id = $_SESSION['id'];
$old_value = $_SESSION['old_value'];
$value = $_SESSION['value'];
//do something
Two answers.
If the following does not work:
<?php
define('ENVIRONMENT', 'tests');
$_POST['id']='AccountPagesView.a_book/45';
$_POST['old_value']='1';
$_POST['value']='2';
require("/index.php/welcome/update_record");
?>
(I am a bit flabbergasted about the page URL.)
Then:
As you insist on POST (as is your right in asking), you can do:
<html>
<head>
</head>
<body>
<form action="/index.php/welcome/update_record" method="post">
<input type="hidden" name="id" value="AccountPagesView.a_book/45">
<input type="hidden" name="old_value" value="1">
<input type="hidden" name="value" value="2">
<input type="hidden" name="ENVIRONMENT" value="tests">
</form>
<script type="text/javascript">
document.forms[0].submit();
</script>
</body>
</html>
Where that define of ENVIRONMENT needs to be solved somehow.
If the target script uses $_REQUEST which is $_POST + $_GET (i.o. $_POST) then you do a HTTP GET URL: ...-?id=...&old_value=1&value=2 which would be the simplest solution.

Load page and submit form inside PHP

I'm creating an system that uses online compiler. IDEONE give me this feature (throgh an Web Service), but with a price for an high volume of compilations.
Then I'm trying to use codepad, but it doesn't have an Web Service... codepad has an initial page, and clicking it's submit button, apparently the same page loads (the form's action is "/")...
I'm using curl to load page, but I'm getting "Internal Server Error". This is my code: pastebin Code, I'm using 000webhost, I don't know if i did something wrong or if my webserver doesn't support it.
Have you trued removing the TIMEOUT? or maybe extending it?
Try this maybe:
<html>
<div align="center">
<form action="compilador.php" method="POST">
<textarea id="source" name="source"></textarea>
<input type="submit" value="Enviar" />
<?php
if(isset($_POST['source']) && $_POST['source'] != "")
{
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL, "http://codepad.org");
/**
* Ask cURL to return the contents in a variable instead of simply echoing them to the browser.
*/
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$post_data=$_POST;
$post_data['lang'] = 'C';
$post_data['private'] = True;
$post_data['run'] = True;
foreach($post_data as $key => $value)
{
$post_items[] = $key . '=' . $value;
}
$post_string = implode ('&', $post_items);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec ($ch);
/**
* Close cURL session
*/
curl_close($ch);
echo "<br /><br />RESULT: {".$result."}";
}
?>
</form>
</div>
</html>

Categories