How do you access another PHP script in a PHP script? - php

I have a PHP page that needs to send data to another PHP page during the page execution and receive data back.
Can this be done? If so, how?
Update:
Sorry - meant to say that the second script is on a completely different server and domain.
Like how is Stripe doing it with their PHP option: https://stripe.com/docs/api?lang=php

EDIT
Looking at the Stripe source code, you will see they do use cURL (ApiRequestor.php):
private function _curlRequest($meth, $absUrl, $headers, $params, $myApiKey)
{
$curl = curl_init();
$meth = strtolower($meth);
$opts = array();
if ($meth == 'get') {
$opts[CURLOPT_HTTPGET] = 1;
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else if ($meth == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = self::encode($params);
} else if ($meth == 'delete') {
$opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else {
throw new Stripe_ApiError("Unrecognized method $meth");
}
$absUrl = self::utf8($absUrl);
$opts[CURLOPT_URL] = $absUrl;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_CONNECTTIMEOUT] = 30;
$opts[CURLOPT_TIMEOUT] = 80;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_HTTPHEADER] = $headers;
$opts[CURLOPT_USERPWD] = $myApiKey . ':';
$opts[CURLOPT_CAINFO] = dirname(__FILE__) . '/../data/ca-certificates.crt';
if (!Stripe::$verifySslCerts)
$opts[CURLOPT_SSL_VERIFYPEER] = false;
curl_setopt_array($curl, $opts);
$rbody = curl_exec($curl);
if ($rbody === false) {
$errno = curl_errno($curl);
$message = curl_error($curl);
curl_close($curl);
$this->handleCurlError($errno, $message);
}
$rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array($rbody, $rcode);
}
cURL - from the PHP manual:
PHP supports libcurl, a library created by Daniel Stenberg, that
allows you to connect and communicate to many different types of
servers with many different types of protocols. libcurl currently
supports the http, https, ftp, gopher, telnet, dict, file, and ldap
protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP
PUT, FTP uploading (this can also be done with PHP's ftp extension),
HTTP form based upload, proxies, cookies, and user+password
authentication.
<?php
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '#/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>

Use include('script2.php') from script1.php
Then you can call the functions within script2.php (assuming they have global scope) from script1.php.

The other possibility if you want to call a PHP script like the end user via URL's, cURL is a good tool to know about.
http://php.net/manual/en/book.curl.php

Related

curl command not working on bigrock server…?

<?php
if(isset($_POST["submit"]))
{
$adm=$_POST["admno"];
$phn=$_POST["phn1"];
include("model.php");
$db = new database;
$r=$db->register($adm);
while($row=mysql_fetch_array($r))
{
if($row["phn_no1"]==$phn || $row["phn_no2"]==$phn || $row["phn_no3"]==$phn)
{
$formatted = "".substr($phn,6,10)." ";
$password = $formatted + $adm;
echo $password;
$db->setpassword($adm,$password);
$pre = 'PREFIX';
$suf = '%20ThankYou';
$sms = $pre.$password.$suf;
session_start();
$ch = curl_init("http://www.perfectbulksms.in/Sendsmsapi.aspx? USERID=ID&PASSWORD=PASS&SENDERID=SID&TO=$phn&MESSAGE=$sms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
$result = curl_exec($ch);
curl_close($ch);
header("Location:password.php?msg=new");
}
else
{
header("Location:register.php?msg=invalid");
}
}
}
?>
this code is working perfect on my local host .. but when i put it on server ... it takes lots of time but the code in curl command is not working it only refers to next page ... i checked that curl is enabled .. if i use only sms api without curl command it sends sms immidiately.... but i want to run both header and also want to hide my sms api.... is there any alternate of this ???

HTTP Requests made with file_get_contents() share the same session data?

I've got a problem...
I've a MVC-like framework and the redirect mechanism allows me too get snippets of HTML code generated by PHP on a remote host.
I'm getting these snippets by using the file_get_contents() function, with allow_url_fopen turned on.
The problem is the fact I use session data inside these code fragments and the session data is being lost every time. I'm assuming this new request is not sharing the same session data and therefore I need a way to get these fragments without losing my session data.
Any suggestions?
If the files your accessing are on the same server as the calling file then you might as well use include(); like #user574632's answer.
But if not, to keep the session you will need to handle the cookies the server sends;
Sessions are cookie based, server sets the session cookie your browser picks it up and uses it for all subsequent requests.
By default file_get_contents wont handle cookies, so your need to grab the header from the server by accessing $http_response_header array and then match with regex the Set-Cookie: header then store that and on following requests use the cookie and create a stream context with the cookie added to the header and pass that to fgc:
<?php
function get_cookies() {
//check cookies folder - or make it
if(!file_exists('./cookies/')){
mkdir('./cookies/', 0755, true);
}
$return = null;
foreach(glob("./cookies/*.txt") as $file) {
$return .= file_get_contents($file).';';
}
return $return;
}
function save_cookies($http_response_header) {
print_r($http_response_header);
foreach($http_response_header as $header) {
if(substr($header, 0, 10) == 'Set-Cookie'){
if(preg_match('#Set-Cookie: (([^=]+)=[^;]+)#i', $header, $matches)) {
$fp = fopen('./cookies/'.$matches[2].'.txt', 'w');
fwrite($fp, $matches[1]);
fclose($fp);
}
}
}
}
$opts = array('http' =>
array('header'=>'Cookie: '.get_cookies()."\r\n")
);
$context = stream_context_create($opts);
$contents = file_get_contents('http://mywebsite.com/snippets/', false, $context);
save_cookies($http_response_header);
echo $contents;
?>
Alternatively you should use curl instead its faster and handles cookies fine.
So something like the following, use curl and then revert to fgc if curl is not present, all wrapped up with cookie support in a class, so the 3 functions are contained:
<?php
//example usage
echo new curl_get_contents('http://example.com/page_that_needs_sessions');
class curl_get_contents{
public $result;
function __construct($url){
$this->curl_rev_fgc($url);
}
function __toString(){
return $this->result;
}
private function get_cookies() {
$return = null;
foreach(glob("./cookies/*.txt") as $file) {
$return .= file_get_contents($file).';';
}
return $return;
}
private function save_cookies($http_response_header) {
foreach($http_response_header as $header) {
if(substr($header, 0, 10) == 'Set-Cookie'){
if(preg_match('#Set-Cookie: (([^=]+)=[^;]+)#i', $header, $matches)) {
$fp = fopen('./'.$matches[2].'.txt', 'w');
fwrite($fp, $matches[1]);
fclose($fp);
}
}
}
}
private function curl_rev_fgc($url){
//check cookies folder - or make it
if(!file_exists('./cookies')){
mkdir('./cookies/', 0755, true);
}
$usragent = 'Mozilla/5.0 (compatible; Yourbot/0.1; +https://yoursite/bot.html)';
//Check curl is installed or revert to file_get_contents()
$curl = function_exists('curl_init') ? true : false;
if($curl){
$opts = array(
'http' => array(
'method' => "GET",
'header' => 'Cookie: '.$this->get_cookies().'\r\n', // cookie in fgc support
'user_agent' => $usragent)
);
$context = stream_context_create($opts);
$result = #file_get_contents($url, false, $context);
$this->save_cookies($http_response_header);
if(empty($result)){
$this->result = 'Error fetching: '.htmlentities($url);
}else{
$this->result = $result;
}
return;
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_USERAGENT, $usragent);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
if(!file_exists('./cookies/curl.txt')){
file_put_contents('./cookies/curl.txt',null);
}
curl_setopt($curl, CURLOPT_COOKIEFILE, './cookies/curl.txt');
curl_setopt($curl, CURLOPT_COOKIEJAR, './cookies/curl.txt');
$result = curl_exec($curl);
if(empty($result)){
$this->result = 'Error fetching: '.htmlentities($url);
}else{
$this->result = $result;
}
curl_close($curl);
return;
}
}
?>
Use include instead. If you need to read the output into a variable to display later/elsewhere in the code, as suggested in the comments, use the output buffer:
ob_start();
include('path/to/file.php');
$included = ob_get_clean();
//nothing has been output to the browser yet
//later on
echo $included;

PHP Curl check for file existence before downloading

I am writing a PHP program that downloads a pdf from a backend and save to a local drive. Now how do I check whether the file exists before downloading?
Currently I am using curl (see code below) to check and download but it still downloads the file which is 1KB in size.
$url = "http://wedsite/test.pdf";
$path = "C:\\test.pdf;"
downloadAndSave($url,$path);
function downloadAndSave($urlS,$pathS)
{
$fp = fopen($pathS, 'w');
$ch = curl_init($urlS);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $httpCode;
//If 404 is returned, then file is not found.
if(strcmp($httpCode,"404") == 1)
{
echo $httpCode;
echo $urlS;
}
fclose($fp);
}
I want to check whether the file exists before even downloading. Any idea how to do it?
You can do this with a separate curl HEAD request:
curl_setopt($ch, CURLOPT_NOBODY, true);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
When you actually want to download you can use set NOBODY to false.
Call this before your download function and it's done:
<?php function remoteFileExists($url) {
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}
?>
Since you are using HTTP to fetch a resource on the internet, what you really want to check is that the return code is a 404.
On some PHP installations, you can just use file_exists($url) out of the box. This does not work in all environments, however. http://www.php.net/manual/en/wrappers.http.php
Here is a function much like file_exists but for URLs, using curl:
<?php function curl_exists()
$file_headers = #get_headers($url);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
} ?>
source: http://www.php.net/manual/en/function.file-exists.php#75064
Sometimes the CURL extension isn't installed with PHP. In that case you can still use the socket library in the PHP core:
<?php function url_exists($url) {
$a_url = parse_url($url);
if (!isset($a_url['port'])) $a_url['port'] = 80;
$errno = 0;
$errstr = '';
$timeout = 30;
if(isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
$fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
if (!$fid) return false;
$page = isset($a_url['path']) ?$a_url['path']:'';
$page .= isset($a_url['query'])?'?'.$a_url['query']:'';
fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
$head = fread($fid, 4096);
$head = substr($head,0,strpos($head, 'Connection: close'));
fclose($fid);
if (preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head)) {
$pos = strpos($head, 'Content-Type');
return $pos !== false;
}
} else {
return false;
}
} ?>
source: http://www.php.net/manual/en/function.file-exists.php#73175
An even faster function can be found here:
http://www.php.net/manual/en/function.file-exists.php#76246
In the first example above $file_headers[0] may contain more than or something other than 'HTTP/1.1 404 Not Found', e.g:
HTTP/1.1 404 Document+%2Fdb%2Fscotbiz%2Freports%2FR20131212%2Exml+not+found
So it's important to use some other test, e.g., regex, as '==' is not reliable.

Attempting to make POST request from one page on my site to another with PHP and Curl

Hey all I have seen several questions on the topic here, but none of them have solved my problem. I have a script on my site which I want to use to generate several different types of emails to my users. I wanted a way to be able to create template files for the different emails which accept $_POST variables to fill in relevant information, and to simply make a post request to these templates and get back the response to place as the body of the email. I am attempting to write a function which would accept the location of the template file (either relative or absolute would work, but I would prefer relative honestly), and an array of parameters that I would like to send to the template via post. So far I have had no luck. Here is my code so far:
private function post_request($url, $data) {
$output = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = curl_error($ch);
}
curl_close($ch);
return $output;
}
I have been getting the error "couldn't connect to host" from curl, but after outputting my url to an error log I have been able to verify that copying and pasting the URL into firefox results in seeing the page correctly.
Any ideas? I am not married to the idea of using curl, so if there is a better option I would be more than happy to use it instead. Thanks for the help all!
You should be able to use file_get_contents() for this, so long as your host has not prevented it from accessing remote locations (and the $url script is not looking exclusively for POST data).
private function post_request($url, $data) {
$output = array();
$url_with_data = '';
foreach ( $data as $k=>$v ){ // Loop through data and create request string
$url_with_data .= '&' . $k . '=' . $v;
}
// Remove first ampersand and encode the data
$url_with_data = urlencode( substr( $url_with_data, 1 ) );
// Request file
// Format will be http://url.com?var1=data&var2=data&var3=data
$result = file_get_contents( $url . '?' . $url_with_data );
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = 'Could not open remote file';
}
return $output;
}
Another option: You say that both files reside on the same server. If that is the case, you could simply require() the template builder.
private function post_request($url, $data) {
$output = array();
#require_once('./path/to/template_builder.php');
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = 'Could not open remote file';
}
return $output;
}
Then in template_builder.php:
<?php
unset( $result );
if ( is_array( $data ) ){
// Parse $data ...
$result = $email_template;
}
As it turns out, the issue ended up being a server configuration error. The server was timing out while attempting to contact the file because it was hitting the wrong DNS server. Fixing that solved my problem!

Gotomeeting php api(oauth) implementation

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz

Categories