Sending data from PHP - php

I need to 'export' certain information with PHP. However, sending an email won't solve my issue. I also don't want to use PECL functions since the package is not installed by default and I can't know whether it is on the server I'll need to send the information from.
Considering I'm dragging the information from a certain file with a regular expression or whatever and sending it out to an external source. The best scenario would be to write the information to a remote file so that it is publicly easily accessible. I thought of forging a raw socket and appending the data to an additional header but I don't know how that could work. Again, as I said, mail() isn't an alternative in this case.
Any ideas are highly appreciated.

If you only have little data, you could use file_get_contents() method and append your data URL encoded as parameter to a web resource. The receiver could be a simple PHP script as well.
sender.php
$data_plain = "to be sent";
$data_enc = urlencode($data);
file_get_contents("https://www.your-receiver.com/receiver.php?data=" . $data_enc);
receiver.php
$data_enc = $_GET["data"];
$data_plain = urldecode($data_enc);

If you want to store it in a variable (and have server side processing done at the same time)
$file = 'some_file.php';
ob_start();
include_once($file);
$contents = ob_get_contents();
ob_end_clean();
echo $contents;

Related

BIRT 4.5 - Disable saving connectstring inside report.rptdesign, PHP to assign connectstring

I am using Birt 4.5 and PHP/MYSQL.
I am able to run birt reports with php. I have enabled tomcat and copied 'birt-runtime-4_5_0/WebViewerExample' to tomcat/webapps and renamed it to birt.
So I can run birt viewer with php;
<?php
$fname = "report/test.rptdesign&__showtitle=false";
$dest = "http://localhost:8081/birt/frameset?__report=";
$dest .= $fname;
header("Location: $dest" );
?>
Above code is working fine. But report connectstring already saved in test.rptdesign file.
I want to remove DB login credentials from test.rptdesign file and assign it while report open with PHP.
I have tried with report parameters. But all the parameters will display on browser address-bar.
Is there any secure way to do this? This is very important when we need to change the database location. It is very hard to change the data source of each and every .rptdesign file.
Thank You,
Supun
I don't believe using report parameters to handle a database connection is the right way. In addition to the address-bar problem you mentionned, it will cause unexpected issues: for example you won't be able to use this database to feed the dataset of another report parameter.
With Tomcat the best approach is to externalize the database connection in a connection pool: easy, robust, and reports might run significantly faster.
Alternatively the datasource can be externalized in a BIRT library (.rptlibrary) and shared across all report-designs: thus only the library needs to be updated when the database location is changing.
I agree with Dominique that sending the database parameters via the query is most likely an inappropriate solution - and you've not given any explanation of whether this is a requirement of the system.
But it is quite trivial to proxy the request via PHP and decorate the URL with the required parameters, something like...
<?php
$_GET['__showtitle']=$_GET['__showtitle'] ? $_GET['__showtitle'] : 'false';
$_GET['__report']=$fname; // NB this should be NULL in your code!
$_GET['dbuser']='a_db_user';
$_GET['passwd']='s3cr3t';
$qry=http_build_query($_GET);
$url="http://localhost:8081/birt/frameset?" . $qry;
// if its simply returning HTML, then just....
$fin=fopen($url, 'r');
while ($l=fgets($fin)) {
print $l;
}
exit;
If the returned content contains relative links the you'll need to rewrite the output stream. If the content type is unusual or you want to project other headers (e.g. for caching) to the browser, then you'll need to use Curl, capture the headers and relay them.

Save binary request body as file

I wrote a program that reads a binary file into the RAM and then sends it using an HTTP request to my server. It uses the PUT method and the binary file is (in) the body.
Now how can I tell my server to receive and safe the file in a folder?
If possible without any additional libraries that I would need to download (unless it's more efficient).
I know, there are some similar threads to this one, but they either they where about receiving text or they were about doing it with libraries or there simply was no sufficient answer.
I'd also like to know, if it would be more efficient or smarter to use the POST method or any other instead of PUT.
You can get at the data by opening a stream to php://input, like so:
$datastr = fopen('php://input',rb);
if ($fp = fopen('outputfile.bin', "wb")){
while(!feof($datastr)){
fwrite($fp,fread($datastr,4096)) ;
}
}
As to whether to use POST or anything else depends on what is happening with the data, and whether you care about being RESTful or such. See other questions/answers, indempotency.
The advantage I would see with using POST is that it's more commonly used (on most submission forms where you upload a file), and therefore has more support from within PHP and html.

Get .php file locally using curl

I'm using curl in PHP to return the content of a PHP file. I want to do this locally because I will be accessing multiple PHP files during the same script, so it would be faster to open the file directly.
However, I want to be able to push parameters into the PHP files (treat them exactly as PHP files on the web, but grabbing them locally), as I want to push parameters into the scripts which will be generating additional dynamic content when I grab it.
Is this possible to do if I call the files locally? I've tried using the file:///, calling the file directly, but this won't run the PHP code found in these files.
Any ideas?
edit
Sorry for the confusion:
-This is currently running on a webserver, and I am currently calling http:// (and not file:///) so the PHP contained in those files can be executed. However, I find this to be slow because I'm generating multiple curl() calls that are essentially calling the server itself multiple times.
you can do trick like:
function php_to_string($php_file, $new_GET = false, $new_POST = false) {
// replacing $_GET, $_POST if necessary
if($new_GET) {
$old_GET = $_GET;
$_GET = $new_GET;
}
if($new_POST) {
$old_POST = $_POST;
$_POST = $new_POST;
}
ob_start();
include($php_file);
// restoring $_GET, $_POST if necessary
if(isset($old_GET)) {
$_GET = $old_GET;
}
if(isset($old_POST)) {
$_POST = $old_POST;
}
return ob_get_clean();
}
$content = php_to_string('my_file.php');
$content = php_to_string('my_file.php', Array('id'=>23)); // http://localhost/my_fie.php?id=23
But please mind it may overwrite your existing variables, causing bugs (for example duplicate defines) etc. so you may use sandbox solution
I believe you would want to set up a web server (e.g. Apache) on your local machine so you can go to http://localhost/script.php?param1=foo&param2=bar instead of file:///path/to/script.php. The difference is that when you do file:///, the files are just opened, but if you go through Apache, the scripts are actually executed.
As for passing arguments to your scripts, use the query string for that (e.g. ?param1=foo, etc.).
I don't know why you're doing what you're doing, but hopefully that helps you do it.

PHP - file_get_contents() with variable in string?

Im trying to email an order with PHPMailer to the customer when this order is received.
I tried doing that this way:
$email_page = file_get_contents("email_order_html.php?order=$order_id");
I want to get the contents of this page as string so I can send this with PHPMailer but this function wont execute the page because of the variable $order_id in it, how can I fix this?
You can only add Query Params when using file_get_contents with an Url Aware Stream Wrapper, e.g. it would work for http://localhost/yourfile.php?foo=bar. Doing so would issue an HTTP Get Request to a webserver at localhost with the specified query params. The request would be processed and the result of the request would be returned.
When using file_get_contents with a filename only, there wont be any HTTP Requests. The call will go directly to your file system. Your file system is not a webserver. PHP will only read the file contents. It wont execute the PHP script and will only return the text in it.
You should include the file and call whatever the script does manually. If the script depends on the order argument, set it via $_GET['order'] = $orderId before including the file.
One of the certainly better ways to do it would be to use output buffering combined with simply including the content creating script.
// $order_id is certainly available in place where file_get_contents has been used...
ob_start();
require 'email_order_html.php';
$email_page = ob_get_clean();
email_template.php
<body>
<p>{foo}</p>
<p>{bar}</p>
</body>
sendmail.php
../
$mail = new PHPMailer();
//get the file:
$body = file_get_contents('email_template.php');
$body = eregi_replace("[\]",'',$body);
//setup vars to replace
$vars = array('{foo}','{bar}');
$values = array($foor,$bar);
//replace vars
$body = str_replace($vars,$values,$body);
//add the html tot the body
$mail->MsgHTML($body);
/...
Hope it helps someone ;)
use require("email_order_html.php");
and $order_id will available in your file
As Gordon said, file_get_contents() reads files from the filesystem - text or binary files, that is, not the result of the execution of those files.
You can use Curl (docs) to do that, in case you'll want to move the script to a separate server. At the moment, simply including the file and passing the arguments directly to the function you want is a more sensitive approach.
$email_page = file_get_contents("email_order_html.php?order=".$order_id);
file_get_contents can read content in url too, at least, in 2021, yes it can.

How to retrieve http page from another host server with php and detect redirect

Let's say I have a server at www.myhost.com. From there by using php I want to retrieve the html document that the php file www.anotherhost.com/somefile.php produces. I also want to use php to do this. anotherhost is not on the same server as myhost.
I know that functions such as fopen, f_get_contents and file can do this by simply executing e.g.
$fp = fopen ("http://www.anotherhost.com/somefile.php")
and from there fp can be used as any other file pointer to read the contents.
BUT, for some reason I also want to know if somefile.php at anotherhost ordered a client-side redirect when I tried to retrieve somefile.php´s resulting html document. somefile.php can do this by
header ("Location: http://www.anotherhost.com/extrafile.php")
Now fopen will retrieve the html document that extrafile.php produces, without detecting that a client-side redirect has been performed.
Is there some functionality in PHP that enables you to retrieve html documents from other servers AND notifies you if a redirect has taken place? It is acceptable if I must follow the redirect by myself (not done automatically), as long as I'm told what the new URL is.
Executing arbitrary commands with the function system is not preferred.
PS. If you are going to suggest fsockopen, then please explain why i get the error "Unable to find the socket transport "http" - did you forget to enable it when you configured PHP?" when I try to execute
fsockopen ("http://localhost")
and I also get "Failed to parse address "localhost" when I do
fsockopen ("localhost")
Thanks for reading. Help would be greatly appreciated.
You can use the Zend_Http_Client from Zend Framework. It has methods for retrieving the number of redirects as well as setting a limit to the number of redirects to follow etc. If you just want to know how it's done, then you can look into the source code and try to figure it out. Shouldn't be too hard I think.
I would use cURL for this. If the redirect is specified in the header, instead of apache mod_rewrite for example, then you should be able to detect if a redirect is present by grabbing all of the headers sent by the response.
Optionally, there is a setting to automatically follow the redirect (http://us.php.net/manual/en/function.curl-setopt.php).
As of php 5.2 you can use the stream api and a stream_notification_callback
e.g.
function notification($code, $severity, $message, $mcode, $transferred, $max) {
if ( STREAM_NOTIFY_REDIRECTED===$code ) {
echo 'redirected to ', $message, "\n";
}
}
$ctx = stream_context_create(null, array('notification' => 'notification'));
$c = file_get_contents("http://spiegel.de", false, $ctx);
echo 'len=', strlen($c);
prints
redirected to http://www.spiegel.de/
len=144446
You probably want a full HTTP client, not stream wrappers and fopen()/file_get_contents(). I think its possible to do what you want with stream wrappers using stream_get_meta_data() but you would be better off with a fuller implementation.
If you don't want to go down the Zend or stream route, you could always use the cURL functions. These will let you return the headers, hence you could analyse these to ascertain whether any re-directs are being issued.
(You can also use the 'CURLOPT_MAXREDIRS' option to specify that it shouldn't follow re-directs.)

Categories