Send txt file from A domain to B domain And run - php

I'm junior php developer with one year experience.
It's my first time to ask for some help
If there's anything that is not appropriate,please tell me,thanks a lot.
Situation:
1.We have two different places(domain A, domain B)
2.When updating the sql on domain A, save a txt file in JSON type as well.(json.txt)
3.Then "send" this txt file from domain A to domain B
4.read and decode the txt file on domain B, then used in Updating sql
Question:
that "send" in situation 3 is the question need to be helped.
What kind of method can be used in this situation?
Here is the whole process in code :
Domain A = "c://example"
Domain B = "220.xxx.xx"
testing file = "sending.txt"
DomainA
<?php
// this code is on Domain A
include_once "lib/database.php";
$pdo = DB_CONNECT();
$file = "sending.txt";
$f = fopen($file, 'w');
// select data from sql, update and put in array, then save it into txt
$sql = "SELECT id,lastupdated FROM customer";
$pdo -> query($sql);
$rs = $pdo -> query($sql);
foreach ($rs as $key => $row) {
$array[$key]=[
"id" => $row["id"],
"lastupdated" => $row["lastupdated"],
];
$sql = "INSERT INTO customer_test (customer_id,lastupdated) VALUES
(".$row["id"].",'".$row["lastupdated"]."')";
$pdo -> query($sql);
}
$array_json = json_encode($array);
fwrite($f, $array_json);
fclose($f);
?>
The Json txt I svaed
[{"id":"1","lastupdated":"2017-03-01 13:55:17"},
{"id":"2","lastupdated":"2017-01-08 17:03:39"},
{"id":"3","lastupdated":"2017-02-07 09:34:29"}]
Domain B
<?php
include_once "lib/database.php";
$pdo = DB_CONNECT();
// get from local txt which has been sent to here From other Domain;
$json_data = file_get_contents('sending.txt');
$array = json_decode($json_data, true);
//then save into same database,but this one is on Domain B.
foreach ($array as $i => $row) {
$id = $array[$i]["id"];
$lastupdated = $array[$i]["lastupdated"];
$sql = "INSERT INTO customer_test (customer_id,lastupdated) VALUES
(".$id.",'".$lastupdated."')";
$pdo -> query($sql);
}
?>
What code should I add in these two php files?
My boss only give this link to me :
How to simulate browser form POST method using PHP/cURL
But I still don't have any idea at all.
Can't even know where to add my code to test.
Please take a look when you are available with this question.
Many thanks.

Add this to the bottom of Domain A. This generates a post request by the php curl library. You'll need to have it installed and it likely is. http://php.net/manual/en/book.curl.php
$ch = curl_init('http://220.xxx.xx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $array_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($array_json))
);
And check the data from Domain A by putting this on domain B:
var_dump($_RESPONSE);exit;
Also, open up the network tab on your element-inspector to get a better idea of what's going on.
// get from local txt which has been sent to here From other Domain;
It could go the other way around. Domain A doesn't send the text... Domain B retrieves the text from Domain A.
Example from php.net: http://php.net/manual/en/curl.examples.php
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "c://example/sending.txt"); // Domain A
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
// or you could use file_get_contents
$text = file_get_contents('c://example/sending.txt');
$text_array = json_decode($text); print_r($text_array);
?>

Related

What's the best way to call php variables from an external domain?

I have a small php script: domain1.com/script1.php
//my database connections, check functions and values, then, load:
$variable1 = 'value1';
$variable2 = 'value2';
if ($variable1 > 5) {
$variable3 = 'ok';
} else {
$variable3 = 'no';
}
And I need to load the variables of this script on several other sites of mine (different domains, servers and ips), so I can control all of them from a single file, for example:
domain2.com/site.php
domain3.com/site.php
domain4.com/site.php
And the "site.php" file needs to call the variable that is in script1.php (but I didn't want to have to copy this file in each of the 25 domains and edit each of them every day):
site.php:
echo $variable1 . $variable2 . $variable3; //loaded by script.php another domain
I don't know if the best and easiest way is to pass this: via API, Cookie, Javascript, JSON or try to load it as an include even from php, authorizing the domain in php.ini. I can't use get variables in the url, like ?variable1=abc.
My area would be php (but not very advanced either), and the rest I am extremely layman, so depending on the solution, I will have to hire a developer, but I wanted to understand what to ask the developer, or maybe the cheapest solution for this (even if not the best), as they are non-profit sites.
Thank you.
If privacy is not a concern, then file_get_contents('https://example.com/file.php') will do. Have the information itself be passed as JSON text it's the industry standard.
If need to protect the information, make a POST request (using cURL or guzzle library) with some password assuming you're using https protocol.
On example.com server:
$param = $_REQUEST("param");
$result = [
'param' => $param,
'hello' => "world"
];
echo json_encode($data);
On client server:
$content = file_get_contents('https://example.com/file.php');
$result = json_decode($content, true);
print_r ($result);
For completeness, here's a POST request:
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/file.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
$result = json_decode($server_output , true);

Cookies set on another server could not be retrieved using CURL

I'm not sure if what I want to do is possible but here's the case.
Cookies are set on server A (first name, last name, etc).
I have a script on server A which gets the cookies, saves it into the db for future use and then finally displays it. Let's say the script is getCookies.php
Here's the code:
include 'dbconnect.php';
$sessid = $_GET['sid'];
$un = $_COOKIE['un'];
$ul = $_COOKIE['ul'];
$up = $_COOKIE['up'];
$ue = $_COOKIE['ue'];
$idn = $_COOKIE['idn'];
if(!empty($un) || !empty($ul) || !empty($up) || !empty($ue) || !empty($idn)){ // Save log to Database
$savedate = date('Y-m-d G:i');
$q = "INSERT INTO cookiedb (sid, un, ul, up, ue, idn, savedate) VALUES ('$sessid', '$un', '$ul', '$up', '$ue', '$idn', '$savedate')";
$rs = mysqli_query($con,$q);
}
echo "$un, $ul, $up, $ue, $idn";
The code above works if I directly access the script from the browser. However, if I access on another server (server B) using CURL, the cookies doesn't seem to work. It's not being read and saved in the db. I'm getting a blank response. I even used some codes like this suggestion I found here on stackoverflow:
$url = "http://serverA.co.za/getCookie.php";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by #Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
var_dump($matches);
...but this code does not work. Do you have any idea how I can get the value for those cookies? If CURL could not be used here, are there any other ways? Thank you.

Display info from file externally on another site

Basically I want to have one centralized file (preferably .php or .txt).. In it I will define the version and online statuses of my 3 API's (login, register, and stats)
I will somehow link it to my system status page and call upon them in my html with like $version, $login, $register, or $stats and they will automatically display whatever is defined in the centralized file.
My stats page (https://epicmc.us/status.php).. I want to define it all from a seperate file and call upon it in the HTML.
I tried making an external file called check.php and put this in it:
<?php
$version = "1.0.0";
$login = 'online';
$register = 'online';
$stats = 'online';
echo json_encode(compact('version','login','register','stats'));
?>
and then in my stats page I called upon it with
<?php
$data= json_decode(file_get_contents('https://epicmc.us/api/bridge/check.php'),true);
echo $version;
echo $login;
echo $register;
echo $stats;
?>
The page is just blank though.
How would you go about implementing this into my stats page code?
http://pastebin.com/nREdfH1u
A good solution here would be to curl your file.
As you already return a JSON string containing your values, just curl your 'check.php' file and json_decode the response.
One of the advantages of this method is that you can access these informations from other domains.
You should be able to get all the values easily.
Example :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'check.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // to return the response in a variable and not output it
// $result contains the output string
$result = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$array_response = json_decode($result, true);
// echo $array_response['version']...

Change Output of PHP Script to use POST Method

Bear with my inexperience here, but can anyone point me in the right direction for how I can change the PHP script below to output each variable that is parsed from the XML file (title, link, description, etc) as a POST method instead of just to an HTML page?
<?php
$html = "";
$url = "http://api.brightcove.com/services/library?command=search_videos&any=tag:SMGV&output=mrss&media_delivery=http&sort_by=CREATION_DATE:DESC&token= // this is where the API token goes";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 80; $i++){
$title = $xml->channel->item[$i]->video;
$link = $xml->channel->item[$i]->link;
$title = $xml->channel->item[$i]->title;
$pubDate = $xml->channel->item[$i]->pubDate;
$description = $xml->channel->item[$i]->description;
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p>
<iframe width='480' height='270' src='http://link.brightcove.com/services/player/bcpid3742068445001?bckey=AQ~~,AAAABvaL8JE~,ufBHq_I6FnyLyOQ_A4z2-khuauywyA6P&bctid=$titleid&autoStart=false' frameborder='0'></iframe><hr/>";/* this embed code is from the youtube iframe embed code format but is actually using the embedded Ooyala player embedded on the Campus Insiders page. I replaced any specific guid (aka video ID) numbers with the "$guid" variable while keeping the Campus Insider Ooyala publisher ID, "eb3......fad" */
}
echo $html;
?>
#V.Radev Here's another PHP script using cURL that I think will work with the API I'm trying to send data to:
<?PHP
$url = 'http://api.brightcove.com/services/post';
//open connection
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, '$title,$descripton,$url' . stripslashes($_POST['$title,$description,$url']));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
// Enable for Charles debugging
//curl_setopt($ch,CURLOPT_PROXY, '127.0.0.1:8888');
$result = curl_exec($ch);
curl_close($ch);
print $result;
?>
My question is, how can I pass the variables from my feed parsing script (title, description, URL) to this new script?
I have this code from Brightcove, can I just output the variables from my parser script and send to this PHP script so that the data goes to the API?
<?php
// This code example uses the PHP Media API wrapper
// For the PHP Media API wrapper, visit http://docs.brightcove.com/en/video-cloud/open-source/index.html
// Include the BCMAPI Wrapper
require('bc-mapi.php');
// Instantiate the class, passing it our Brightcove API tokens (read, then write)
$bc = new BCMAPI(
'[[READ_TOKEN]]',
'[[WRITE_TOKEN]]'
);
// Create an array of meta data from our form fields
$metaData = array(
'name' => $_POST['bcVideoName'],
'shortDescription' => $_POST['bcShortDescription']
);
// Move the file out of 'tmp', or rename
rename($_FILES['videoFile']['tmp_name'], '/tmp/' . $_FILES['videoFile']['name']);
$file = '/tmp/' . $_FILES['videoFile']['name'];
// Create a try/catch
try {
// Upload the video and save the video ID
$id = $bc->createMedia('video', $file, $metaData);
echo 'New video id: ';
echo $id;
} catch(Exception $error) {
// Handle our error
echo $error;
die();
}
?>
Post is a request method to access a specific page or resource. With echo you are sending data which means that you are responding. In this page you can only add response headers and access it with a request method such as post, get, put etc.
Edit for API request as mentiond in the comments:
$curl = curl_init('your api url');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $your_data_to_send);
$result_from_api = curl_exec($curl);
curl_close($curl);

Google maps response's language issue

I'll try to be short: if you need more info, I'll tell you.
I'm using this code to get infos from Google Maps:
<?php
function getData($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0); //Change this to a 1 to return headers
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = 'http://maps.google.com/maps/geo?output=xml&q=' . urlencode($startPlace);
$url = 'http://maps.google.com/maps/api/geocode/json?sensor=false&gl=IT&address=' . urlencode($startPlace);
$xml = simplexml_load_string($this->getData($this->url)) or die("Error loading xml data");
$points = $xml->Response->Placemark->Point->coordinates;
$provincia = $xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->SubAdministrativeAreaName;
$regione =$xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;
echo $regione."<br>";
preg_match_all("/-*[0-9.]*(?=,)/", $points[0], $matches);
$longitude = $matches[0][0];
$latitude = $matches[0][2];
The code is used to retrieve infos about italian locations and till three days ago, all worked fine, but this morning I saw something strange: $regione returned by code ($xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;) had an english name.
Let's say the location found be a little town in Lombardia (where 'Lombardia' is the name of the Administrative Area), the Administartive Area name returned by Google Maps was no more 'Lombardia' but 'Lombardy'.
Since this data is used to search in a local database other places in the Administrative area and since the name used in the database is obviously italian name, application doesnìt work anymore.
I'll be grateful for any advice
The problem is solved using a different url, specifying language parameter:
'http://maps.google.com/maps/api/geocode/xml?sensor=false&language=IT&address=' . urlencode($startPlace);
This url type return correct results but defferently formed so it is necessary change the code to access the infos and put them into variables, but this solved my problem

Categories