Avatar of mindwarpltd
mindwarpltd
 asked on

How can I post data from a php script to another script on another site?

I'm not sure if this is possible, but I did find some code.

I get the following from the script below...

Start
Problem with http://www.othersite.com/php/report.php
Problem reading data from http://www.othersite.com/php/report.php
<?php

error_reporting(E_ALL);
ini_set('display_errors','ON');

echo "Start<br>";

$data = "smv";
$url = "http://www.othersite.com/php/report.php";
$optional_headers = null;

  $params = array('http' => array(
              'method' => 'POST',
              'reason' => $data
            ));


if ($optional_headers !== null) {

	$params['http']['header'] = $optional_headers;

}

$ctx = stream_context_create($params);

$fp = @fopen($url, 'rb', false, $ctx);

if (!$fp) {

	echo "Problem with $url<br>";

}

$response = @stream_get_contents($fp);

if ($response === false) {

	echo "Problem reading data from $url<br>";

}



?>

Open in new window

PHP

Avatar of undefined
Last Comment
Richard Quadling

8/22/2022 - Mon
lenamtl

If this is for monitoring a web site you can use cron jobto check x minute and send email or SMS alert.
Is this what you are trying to achieve?

Insoftservice inso

Hi,

mns u mean to say u want to transfer post data from say
yahoo.com to google.com
please confirm
mindwarpltd

ASKER
lenamtl, no not monitoring.

infosoftservice, yes.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Richard Quadling

You are on the right track. Using a context to set up the headers and the POST.

Personally, for testing/development, I'd NOT use @ to suppress errors.

Instead,

<?php
error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);


With this in place, what errors are you getting?
darren-w-

Hi,

I would assume if you are posting some data you would capture it with the receiving page using the $_REQUEST[] function http://www.w3schools.com/php/php_post.asp ?

mindwarpltd

ASKER
RQuadling, I've replaced

error_reporting(E_ALL);
ini_set('display_errors','ON');


with

error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);

And I get the same messages as above.

Start
Problem with http://www.othersite.com/php/report.php
Problem reading data from http://www.othersite.com/php/report.php
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Richard Quadling

Did you remove the @'s
Richard Quadling

What are the real URLs? Do you need to login to these sites to be able to use them?
mindwarpltd

ASKER
I'm using post

$reason = $_POST['reason'];

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
mindwarpltd

ASKER
>Did you remove the @'s

Which @'s ?

No I don't need a login.
Their both my sites.
Richard Quadling

Line 26 $fp = @fopen($url, 'rb', false, $ctx);
Line 34 $response = @stream_get_contents($fp);

The @'s suppress error reporting. So you don't see any errors. This overrides the error_reporting(-1) for that call only.

In other words, you are hiding the errors and asking us what is going on.

Stop hiding the errors and tell us what they are.
Richard Quadling

Are both sites on the same server? If so, why not just access the code directly?
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
mindwarpltd

ASKER
Ahh right

Warning: fopen(http://www.othersite.com/php/report.php) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required in D:\domains\othersite.com\wwwroot\php\testpost.php on line 28
Problem with http://www.othersite.com/php/report.php

Warning: stream_get_contents() expects parameter 1 to be resource, boolean given in D:\domains\othersite.com\wwwroot\php\testpost.php on line 37
Problem reading data from http://www.othersite.com/php/report.php

No their not on the same server.
mindwarpltd

ASKER
*No they're not on the same server.

Sorry about the @'s could see wood for trees.
Interesting that the stop errors though
mindwarpltd

ASKER
Any ideas about those errors ?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Richard Quadling

Error 2 is because of error 1.

Error 1 is telling you that you are supplying data, but you have not supplied the required header that indicates the amount of data.

Can you add ...

echo '
', var_export(stream_get_meta_data($fp), True), '

Open in new window

';

immediately after the fopen() call please.

Considering you aren't posting any data, just your own headers ...

Maybe ...

Content-Length: 0

is still needed.

Try setting the optional headers to ...

'Content-Length: 0'

mindwarpltd

ASKER
Setting...
$optional_headers = 'Content-Length: 0';
Didn't make any different.

Heres the current output.

Start

Warning: fopen(http://www.othersite.com/php/report.php) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required in D:\domains\othersite.com\wwwroot\php\testpost.php on line 28



Warning:  stream_get_meta_data(): supplied argument is not a valid stream resource in D:\domains\othersite.com\wwwroot\php\testpost.php on line 30

false

Problem with http://www.othersite.com/php/report.php

Warning: stream_get_contents() expects parameter 1 to be resource, boolean given in D:\domains\othersite.com\wwwroot\php\testpost.php on line 39
Problem reading data from http://www.othersite.com/php/report.php
mindwarpltd

ASKER
<pre><br />
<b>Warning</b>:  stream_get_meta_data(): supplied argument is not a valid stream resource in <b>D:\domains\softtester.com\wwwroot\php\testpost.php</b> on line <b>31</b><br />
false</pre>
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Ray Paseur

What is the REAL URL of the site you're trying to access?  I'm fairly sure it is not http://www.othersite.com/php/report.php

It is almost impossible to debug your code without the information necessary to test.

Sometimes you may find that cURL is the best tool for a POST method request.  Here is a sample showing how to do that.
<?php // RAY_curl_post_example.php
error_reporting(E_ALL);

function curl_post($url, $post_array, $timeout=2, $error_report=FALSE)
{
    // PREPARE THE POST STRING
    $post_string = '';
    foreach ($post_array as $key => $val)
    {
        $post_string .= urlencode($key) . '=' . urlencode($val) . '&';
    }
    $post_string = rtrim($post_string, '&');

    // PREPARE THE CURL CALL
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL,            $url);
    curl_setopt($curl, CURLOPT_HEADER,         FALSE);
    curl_setopt($curl, CURLOPT_POST,           TRUE);
    curl_setopt($curl, CURLOPT_POSTFIELDS,     $post_string);
    curl_setopt($curl, CURLOPT_TIMEOUT,        $timeout);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

    // EXECUTE THE CURL CALL
    $htm = curl_exec($curl);
    $err = curl_errno($curl);
    $inf = curl_getinfo($curl);
    curl_close($curl);

    // ON FAILURE
    if (!$htm)
    {
        // PROCESS ERRORS HERE
        if ($error_report)
        {
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            echo "<pre>\n";
            var_dump($inf);
            echo "</pre>\n";
        }
        return FALSE;
    }

    // ON SUCCESS
    return $htm;
}

// USAGE EXAMPLE CREATES ASSOCIATIVE ARRAY OF KEY=>VALUE PAIRS
$args["name"]  = 'Ray';
$args["email"] = 'Ray.Paseur@Gmail.com';

// ACTIVATE THIS TO SEE THE ARRAY OF ARGS
// var_dump($args);

// SET THE URL
$url = "http://LAPRBass.com/RAY_bounce_post.php";

// CALL CURL TO POST THE EATA
$htm = curl_post($url, $args, 3, TRUE);
if (!$htm) die("NO $url");

// SHOW WHAT CAME BACK
echo "<pre>";
echo htmlentities($htm);

Open in new window

Richard Quadling

Hi Ray. Already asked for the URL.

"Hmm, www.othersite.com isn't loading right now." :-)
Richard Quadling

http://www.checkupdown.com/status/E411.html

"Fixing 411 errors - general

This error seldom occurs in most Web traffic, particularly when the client system is a Web browser. The problem can only be resolved by examining what your client system is trying to do then discussing with your ISP why the Web server expects a 'Content-Length' specification."

Your help has saved me hundreds of hours of internet surfing.
fblack61
Richard Quadling

Ah. You are posting, but not sending any data (only headers).

Does anything change if you change 'POST' to 'GET'?
mindwarpltd

ASKER
Richard Quadling

All seems to be OK. Code I used and log file of results attached.
<?php

error_reporting(-1);
ini_set('display_errors', 1);

echo "Start<br>";

$data = "smv";
$url = "http://www.softtester.com/php/report.php";
$optional_headers = null;

  $params = array('http' => array(
              'method' => 'GET',
              'reason' => $data
            ));


if ($optional_headers !== null) {

	$params['http']['header'] = $optional_headers;

}

$ctx = stream_context_create($params);

$fp = fopen($url, 'rb', false, $ctx);

var_export(stream_get_meta_data($fp));

if (!$fp) {

	echo "Problem with $url<br>";

}

$response = stream_get_contents($fp);

if ($response === false) {

	echo "Problem reading data from $url<br>";

} else

echo $response;

Open in new window

zz.log
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Richard Quadling

Using POST rather than GET ...

Start

Warning: fopen(http://www.softtester.com/php/report.php): failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required
 in Z:\zz.php on line 26

Warning: stream_get_meta_data() expects parameter 1 to be resource, boolean given in Z:\zz.php on line 28
NULLProblem with http://www.softtester.com/php/report.php

Warning: stream_get_contents() expects parameter 1 to be resource, boolean given in Z:\zz.php on line 36
Problem reading data from http://www.softtester.com/php/report.php




Trying to post with no data and no content-length was the error.
mindwarpltd

ASKER
OK, let me explain my situation and put my cards completely on the table.

I have a workable scenario, where I process data for my site (hosted with my ISP), the site is www.softtester.com.

The data is processed on my other machine which has a local ip address of 192.168.7.6

I use to be able to run my processing online however I can no longer do this.

So I have two copies of my main database.

Today I've been adding a feature which will allow users to report inappropriate pages. However, this give me the problem that I have to update two databases. Therefore the report is emailed to me and I get two urls, a live url and a url from my other machine, showing the same page data.

e.g.

The following program listing has been reported.

http://www.softtester.com/programs/mdbsecure-88872.shtml

http://192.168.7.6/programs/mdbsecure-88872.shtml

The reason being :Broken link(s)

If the use the second link, I have a button, which is only shown on 192.168.7.6 Which allows me to call a script which I intend to use to  delete records and post an encrypted string to a script on the live sever which will delete the records there too. That script works fine.

But I need to get the posting to work from one script to another.

Foolishly while discussing here, I've use the script on the same server.
This is the result I now get from 192.168.7.6

Start

array (
  'wrapper_data' =>
  array (
    0 => 'HTTP/1.1 302 Moved Temporarily',
    1 => 'Connection: close',
    2 => 'Date: Fri, 10 Sep 2010 13:12:55 GMT',
    3 => 'Server: Microsoft-IIS/6.0',
    4 => 'X-Powered-By: ASP.NET',
    5 => 'Location: http://www.softtester.com/sent.shtml',
    6 => 'Content-type: text/html',
    7 => 'Content-Length: 0',
    8 => 'HTTP/1.1 200 OK',
    9 => 'Connection: close',
    10 => 'Date: Fri, 10 Sep 2010 13:12:56 GMT',
    11 => 'Server: Microsoft-IIS/6.0',
    12 => 'X-Powered-By: ASP.NET',
    13 => 'Content-type: text/html',
    14 => 'Content-Length: 26274',
  ),
  'wrapper_type' => 'http',
  'stream_type' => 'tcp_socket/ssl',
  'mode' => 'rb',
  'unread_bytes' => 1179,
  'seekable' => false,
  'uri' => 'http://www.softtester.com/php/report.php',
  'timed_out' => false,
  'blocked' => true,
  'eof' => false,
)

However the data isn't getting passed.
mindwarpltd

ASKER
Heres what I'm using in report.php

      $reason = $_POST['reason'];

But theres no data getting to it.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
mindwarpltd

ASKER
Also the report script does work, when called e.g.

http://www.softtester.com/programs/mdbsecure-88872.shtml

Click report this a form appears and the data is sent...

I get this in an email...

The following program listing has been reported.

http://www.softtester.com/programs/mdbsecure-88872.shtml

http://192.168.7.6/programs/mdbsecure-88872.shtml

The reason being :Spyware / malware / virus
mindwarpltd

ASKER
I've had several emails from you guys testing...

The following program listing has been reported.



The reason being :
mindwarpltd

ASKER
Heres my current script with content length set.
<?php

error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);

echo "Start<br>";

$data = "smv";
$url = "http://www.softtester.com/php/report.php";
$optional_headers = null;

  $params = array('http' => array(
              'method' => 'POST',
              'reason' => $data
            ));

$optional_headers = 'Content-Length: 0';

if ($optional_headers !== null) {

	$params['http']['header'] = $optional_headers;

}

$ctx = stream_context_create($params);

#$fp = @fopen($url, 'rb', false, $ctx);
$fp = fopen($url, 'rb', false, $ctx);

echo '<pre>', var_export(stream_get_meta_data($fp), True), '</pre>';

if (!$fp) {

	echo "Problem with $url<br>";

}

#$response = @stream_get_contents($fp);
$response = stream_get_contents($fp);

if ($response === false) {

	echo "Problem reading data from $url<br>";

}



?>

Open in new window

âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Richard Quadling

So, $_POST contains the data?

You can't supply an array in a POST request without some work.

$data = http_build_query($_POST);

and

$len = strlen($data);

Use

"Content-Length: $len" in the 'header'

and, for the context, set the 'content' to $data.

All explained (sorta) on http://docs.php.net/manual/en/function.stream-context-get-default.php example 1 (look at the alternative options bit).

Oh. And look at the user note there. Hmmm. Shame that the site is LONG gone. I really should care more.
Ray Paseur

I tried running the script in the code snippet below and got this output.  Based on the information from the W3, that is kind of an odd response.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Can you please show us the HTML that would be used to post information to that page?  Thanks.


CURL FAIL: http://www.softtester.com/php/report.php TIMEOUT=3, CURL_ERRNO=0

array(20) {
  ["url"]=>
  string(40) "http://www.softtester.com/php/report.php"
  ["content_type"]=>
  string(9) "text/html"
  ["http_code"]=>
  int(302)
  ["header_size"]=>
  int(213)
  ["request_size"]=>
  int(151)
  ["filetime"]=>
  int(-1)
  ["ssl_verify_result"]=>
  int(0)
  ["redirect_count"]=>
  int(0)
  ["total_time"]=>
  float(0.51651)
  ["namelookup_time"]=>
  float(0.316303)
  ["connect_time"]=>
  float(0.408335)
  ["pretransfer_time"]=>
  float(0.40835)
  ["size_upload"]=>
  float(10)
  ["size_download"]=>
  float(0)
  ["speed_download"]=>
  float(0)
  ["speed_upload"]=>
  float(19)
  ["download_content_length"]=>
  float(0)
  ["upload_content_length"]=>
  float(0)
  ["starttransfer_time"]=>
  float(0.516431)
  ["redirect_time"]=>
  float(0)
}

NO http://www.softtester.com/php/report.php
<?php // RAY_temp_curl_post_example.php
error_reporting(E_ALL);

function curl_post($url, $post_array, $timeout=2, $error_report=FALSE)
{
    // PREPARE THE POST STRING
    $post_string = '';
    foreach ($post_array as $key => $val)
    {
        $post_string .= urlencode($key) . '=' . urlencode($val) . '&';
    }
    $post_string = rtrim($post_string, '&');

    // PREPARE THE CURL CALL
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL,            $url);
    curl_setopt($curl, CURLOPT_HEADER,         FALSE);
    curl_setopt($curl, CURLOPT_POST,           TRUE);
    curl_setopt($curl, CURLOPT_POSTFIELDS,     $post_string);
    curl_setopt($curl, CURLOPT_TIMEOUT,        $timeout);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

    // EXECUTE THE CURL CALL
    $htm = curl_exec($curl);
    $err = curl_errno($curl);
    $inf = curl_getinfo($curl);
    curl_close($curl);

    // ON FAILURE
    if (!$htm)
    {
        // PROCESS ERRORS HERE
        if ($error_report)
        {
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            echo "<pre>\n";
            var_dump($inf);
            echo "</pre>\n";
        }
        return FALSE;
    }

    // ON SUCCESS
    return $htm;
}

// USAGE EXAMPLE CREATES ASSOCIATIVE ARRAY OF KEY=>VALUE PAIRS
$args["reason"] = 'smv';

// ACTIVATE THIS TO SEE THE ARRAY OF ARGS
// var_dump($args);

// SET THE URL
$url = "http://www.softtester.com/php/report.php";

// CALL CURL TO POST THE EATA
$htm = curl_post($url, $args, 3, TRUE);
if (!$htm) die("NO $url");

// SHOW WHAT CAME BACK
echo "<pre>";
echo htmlentities($htm);

Open in new window

mindwarpltd

ASKER
>Can you please show us the HTML that would be used to post information to that page?

Click on report this.
http://www.softtester.com/programs/mdbsecure-88872.shtml

This is the form

        <form METHOD="POST" ACTION="../php/report.php">
      <input type="radio" name="reason" value="smv" checked> Spyware / malware / virus<br>
      <input type="radio" name="reason" value="bl"> Broken link(s)<br>
      <input type="radio" name="reason" value="ic"> Inappropriate content<br>
      <center><INPUT class="send" TYPE="SUBMIT" VALUE="Report"></center>
      </form>

I'm using report.php as a test, for this script were talking about here.

Since I added...

$len = strlen($data);
$optional_headers = 'Content-Length: ' . $len;

I'm getting an error.

Warning: fopen(http://www.softtester.com/php/report.php) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in D:\Build\STPHP\php\testpost.php on line 32

By the way, if anyone can think of an easier way to do all this let me know, I didn't think it would cause so many problems.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
mindwarpltd

ASKER
Hmmm...

Maybe this is the reason ?

  $params = array('http' => array(
              'method' => 'POST',
              'reason' => $data
            ));

Literally.
SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Richard Quadling

'reason' isn't a HTTP header. It is one of YOUR headers. Nothing to do with HTTP.


As I said earlier, 'content' is the entry you need to set. For which you will also need to set the content length.

'content' => $data





Easier???


Your new script...

<?php
// Get the $_POST content from the user.
// Validate it, etc.
// Assume all is well.

file_get_contents('http://www.softtester.com/php/report.php?' . http_build_query($_POST));
?>

And in your softtester.com/php/report.php, use $_GET rather than $_POST

mindwarpltd

ASKER
>'reason' isn't a HTTP header. It is one of YOUR headers. Nothing to do with HTTP.

Yes I think this has been the problem.

I think things are working, however how can I get whats shown on the report.php

I echo out a success status.
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Richard Quadling

$response will contain the result.

So you could just ...

echo $response;

just like I did in https://www.experts-exchange.com/questions/26464226/How-can-I-post-data-from-a-php-script-to-another-script-on-another-site.html?cid=1572&anchorAnswerId=33646090#a33646090 (see the zz.log file attached).

Obviously, take out the debugging stuff first.
mindwarpltd

ASKER
And I want to specific two post values.

$data = "verification=". getdate() . "data=" . $Enc;
Richard Quadling

Add them to $_POST before you process it...

$_POST['verification'] = getdate();
etc.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
mindwarpltd

ASKER
I mean the in the script which does the posting.
mindwarpltd

ASKER
$data = "verification=". getdate() . "data=" . $Enc;

$params = array('http' => array(
       'method'=>"POST",
       'header'=>"Content-type: application/x-www-form-urlencoded\r\n" . "Content-length: " . strlen($data),
       'content'=> $data
));

If this was a query string I'd put & in between the values, but its not.

e.g.

$data = "verification=". getdate() . "&data=" . $Enc;
ASKER CERTIFIED SOLUTION
Richard Quadling

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
mindwarpltd

ASKER
Right cool.

Oh dear, I'm getting response of Array.

Any ideas ?

<B>Response=</B>
<verification>Array</verification><br>

âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
mindwarpltd

ASKER
Weird, its detdate()

#$_POST['verification'] = getdate();
$_POST['verification'] = "33333535";

It works with a hard coded number
mindwarpltd

ASKER
Are a simple date fix for that last thing.
Richard Quadling

getdate() returns an array.

Do you not know about the PHP documentation? http://docs.php.net

array getdate ([ int $timestamp = time() ] )

If you want a timestamp ...

$_POST['verification'] = time(); // 1284133959
or
$_POST['verification'] = microtime(true); // 1284133982.6668

If you want a Human Readable date ...

$_POST['verification'] = date('r'); // Fri, 10 Sep 2010 16:52:17 +0100
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23