Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1067
  • Last Modified:

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

0
mindwarpltd
Asked:
mindwarpltd
  • 24
  • 17
  • 3
  • +3
2 Solutions
 
lenamtlCommented:
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?

0
 
InsoftserviceCommented:
Hi,

mns u mean to say u want to transfer post data from say
yahoo.com to google.com
please confirm
0
 
mindwarpltdAuthor Commented:
lenamtl, no not monitoring.

infosoftservice, yes.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Richard QuadlingSenior Software DeverloperCommented:
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?
0
 
darren-w-Commented:
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 ?

0
 
mindwarpltdAuthor Commented:
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
0
 
Richard QuadlingSenior Software DeverloperCommented:
Did you remove the @'s
0
 
Richard QuadlingSenior Software DeverloperCommented:
What are the real URLs? Do you need to login to these sites to be able to use them?
0
 
mindwarpltdAuthor Commented:
I'm using post

$reason = $_POST['reason'];

0
 
mindwarpltdAuthor Commented:
>Did you remove the @'s

Which @'s ?

No I don't need a login.
Their both my sites.
0
 
Richard QuadlingSenior Software DeverloperCommented:
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.
0
 
Richard QuadlingSenior Software DeverloperCommented:
Are both sites on the same server? If so, why not just access the code directly?
0
 
mindwarpltdAuthor Commented:
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.
0
 
mindwarpltdAuthor Commented:
*No they're not on the same server.

Sorry about the @'s could see wood for trees.
Interesting that the stop errors though
0
 
mindwarpltdAuthor Commented:
Any ideas about those errors ?
0
 
Richard QuadlingSenior Software DeverloperCommented:
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'

0
 
mindwarpltdAuthor Commented:
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
0
 
mindwarpltdAuthor Commented:
<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>
0
 
Ray PaseurCommented:
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

0
 
Richard QuadlingSenior Software DeverloperCommented:
Hi Ray. Already asked for the URL.

"Hmm, www.othersite.com isn't loading right now." :-)
0
 
Richard QuadlingSenior Software DeverloperCommented:
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."

0
 
Richard QuadlingSenior Software DeverloperCommented:
Ah. You are posting, but not sending any data (only headers).

Does anything change if you change 'POST' to 'GET'?
0
 
mindwarpltdAuthor Commented:
0
 
Richard QuadlingSenior Software DeverloperCommented:
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
0
 
Richard QuadlingSenior Software DeverloperCommented:
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.
0
 
mindwarpltdAuthor Commented:
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.
0
 
mindwarpltdAuthor Commented:
Heres what I'm using in report.php

      $reason = $_POST['reason'];

But theres no data getting to it.
0
 
mindwarpltdAuthor Commented:
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
0
 
mindwarpltdAuthor Commented:
I've had several emails from you guys testing...

The following program listing has been reported.



The reason being :
0
 
mindwarpltdAuthor Commented:
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

0
 
Richard QuadlingSenior Software DeverloperCommented:
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.
0
 
Ray PaseurCommented:
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

0
 
mindwarpltdAuthor Commented:
>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.
0
 
mindwarpltdAuthor Commented:
Hmmm...

Maybe this is the reason ?

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

Literally.
0
 
Ray PaseurCommented:
I wonder if there is something strange about the server that carries report.php?  I know that a direct visit to that page redirects, but I am not sure I understand why CURL fails.  According to the form it looks like the CURL post should work.  Maybe if you restart everything the 302 condition will go away.  But that is just a guess.  At this point I am mystified.
0
 
Richard QuadlingSenior Software DeverloperCommented:
'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

0
 
mindwarpltdAuthor Commented:
>'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.
0
 
Richard QuadlingSenior Software DeverloperCommented:
$response will contain the result.

So you could just ...

echo $response;

just like I did in http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_26464226.html?cid=1572#a33646090 (see the zz.log file attached).

Obviously, take out the debugging stuff first.
0
 
mindwarpltdAuthor Commented:
And I want to specific two post values.

$data = "verification=". getdate() . "data=" . $Enc;
0
 
Richard QuadlingSenior Software DeverloperCommented:
Add them to $_POST before you process it...

$_POST['verification'] = getdate();
etc.
0
 
mindwarpltdAuthor Commented:
I mean the in the script which does the posting.
0
 
mindwarpltdAuthor Commented:
$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;
0
 
Richard QuadlingSenior Software DeverloperCommented:
Simplistically,

$data = http_build_query($_POST);

So, if you did ...

$_POST['verification'] = getdate();
$_POST['data'] = $Enc;
$data = http_build_query($_POST);

0
 
mindwarpltdAuthor Commented:
Right cool.

Oh dear, I'm getting response of Array.

Any ideas ?

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

0
 
mindwarpltdAuthor Commented:
Weird, its detdate()

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

It works with a hard coded number
0
 
mindwarpltdAuthor Commented:
Are a simple date fix for that last thing.
0
 
Richard QuadlingSenior Software DeverloperCommented:
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
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 24
  • 17
  • 3
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now