Requesting information from one php file to another using only php - php

I am pretty new to php so I'm having trouble with POSTing.
I am trying to transfer information between 2 php files where send_var.php sends a command by POST and get_var.php executes some data manipulation and returns the response.
The send_var.php is as follows:
<?php
$url = "./get_var.php";
$fields = array('response' => "323243");
$data = http_build_query($fields);
// echo $data."<br />";
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: text/html\r\n",
'content' => $data
),
));
$out = file_get_contents($url, false, $context);
echo "Info from get_var : " . $out;
?>
And the get_var.php is :
<?php
$arg1 = isset($_POST['response']) ? $_POST['response'] : null;
if($arg1 == '')
{
echo "No Command! ";
}
if($arg1 != "")
{
echo $_POST['response'];
}
else
{
$_POST['response'] = "123456";
echo $_POST['response'] . " end of get_var";
}
?>
This code was extracted from other examples on stack overflow. The only output I get is "Info from get_var :"
Obviously I'm missing some pretty fundamental knowledge. If someone can help it would be much appreciated. I'm executing this under XAMPP.

In order to run a PHP script, you have to access it through the webserver. So the URL needs to be an http: URL, not just a filename:
$url = "http://localhost/path/to/get_var.php";
If you just use a filename, file_get_contents() will just return the PHP source code, it won't run it.
Also, your Content-type header is wrong, it should be application/x-www-form-urlencoded, not text/html (that's the content type of the response, your context specifies the type of the POST data).

Related

PHP POST request debugging

Context
I have the following POST pipeline:
index.php -> submit.php ->list/item/new/index.php
index.php has a normal form with an action="submit.php" property.
submit.php decides where to send the following post request by some logic based on the POST variable content.
The problem is that I haven't found a successful way to debug this pipeline. Somewhere, something is failing and I would appreciate a fresh pair of eyes.
What I have tried
I have tried running list/item/new/index.php with dummy parameters through a regular GET request. DB updates successfully.
I have tried running submit.php (below) with dummy parameters through a regular GET request. The value of $result is not FALSE, indicating the file_get_contents request was successful, but it's value is the literal content of list/new/index.php instead of the generated content, which I expect to be the result of
echo $db->new($hash,$content) && $db->update_content_key($hash);
Here is submit.php
$url = 'list/new/index.php';
if($test){
$content = $_GET["i"];
$hash = $_GET["h"];
}else{
$content = $_POST["item"]["content"];
$hash = $_POST["list"]["hash"];
}
$data = array(
'item'=>array('content' => $content),
'list'=>array('hash' => $hash)
);
$post_content = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n".
"Content-Length: " . strlen($post_content) . "\r\n",
'method' => 'POST',
'content' => $post_content
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo "error";
//commenting out for testing. should go back to index.php when it's done
//header('Location: '.$root_folder_path.'list/?h='.$hash.'&f='.$result);
}
else{
var_dump($result);
//commenting out for testing. should go back to index.php when it's done
//header('Location: '.$root_folder_path.'list/?h='.$hash.'&f='.str_replace($root_folder_path,"\n",""));
}
And here is list/item/new/index.php
$db = new sql($root_folder_path."connection_details.php");
if($test){
$content = $_GET["i"];
$hash = $_GET["h"];
}else{
$content = $_POST["item"]["content"];
$hash = $_POST["list"]["hash"];
}
// insert into DB, use preformatted queries to prevent sqlinjection
echo $db->new($hash,$content) && $db->update_content_key($hash);
The worst thing about this is that I don't know enough of PHP to effectively debug this (I actually had it working at some point today but I did not commit right then...).
All comments and suggestions are welcome. I appreciate your time.
Got it.
I'm not sure what to call the error I was making (or what is actually going on behind the scenes) but it was the following:
on the POST request I was using
$url='list/item/new/index.php'
I used the whole url scheme:
$url = 'https://example.com/list/item/new/index.php';`

PHP Posting data to another php file hosted in a remote server using file_get_contents

I have access to 3 different remote servers. They all host the same php file, it's named processing.php.
And in a different server I have 3 pages :
index.html : that contains a form with POST method that send data to forward.php
forward.php : that forward the form values to processing.php on the other servers
processing.php : Display the posted data
The Problem : the code in processing.php is not executed and the returned result is a plain text of the source code of processing.php!!
forward.php :
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
rtrim($_POST['listserver'],"-");
$listServer = explode("-",$_POST['listserver']);
foreach ($listServer as $server){
if(!empty($server)){
$url = 'http://'.$server.'/processing.php';
$data = array('field1' => $field1, 'field2' => $field2);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo "You can't ";
}else{
echo ('result : '.$result);
}
}
}
Processing.php
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$result = $field1+$field2;
$myFile = "files/result.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $result);
fclose($fh);
But in all the servers, result.txt is empty!!
Thanx to #MarkusZeller suggestion, I managed to get it work using cURL.
This thread was very helpful, thank you Stack Over Flow community !

PHP JSON error parsing the JSON document. The document may not be well-formed

This is my code:
if ($_SERVER ["REQUEST_METHOD"] === "GET") {
include_once('../database/dbSource.php');
$databaseSource = DataBaseSource::getInstance();
//Parse
$ini_array = parse_ini_file("../../pto/config.ini");
$user = $_GET['userSid'];
$username = $ini_array['ctsi_CIBMON_fid'];
$password = $ini_array['ctsi_CIBMON_pass'];
$ctsi_url = $ini_array['ctsi_url'] . $user . '&view=full';
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Content-Type: application/json\r\n" . "Accept: application/json\r\n" .
"Authorization: Basic " . base64_encode("$username:$password")
)
);
$context = stream_context_create($opts);
echo file_get_contents($ctsi_url, false, $context);
} else {
echo $_SERVER ["REQUEST_METHOD"];
}
I get the following error :
There was an error parsing the JSON document. The document may not be
well-formed.
I tried checking addiitonal spaces in code (which i removed) etc.
Also there is no issues with authorization.
Can't figure out what's the issue.
Please help.
Note: Also it used to work but stopped working without any change to code even. so Strange.
also the url that i am trying to access is https://xxx.xxx.net not http - does it matter?

Receive PHP code with an POST request

I need to send a POST request to another file called global.php, for this I try this code below:
$url = 'global.php';
$data = array('stack' => 'overflow');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
This is the global.php file that should process the request:
if(isset($_POST['stack'])){
echo 'exists';
}else{
echo 'error';
}
The problem is that instead of the command var_dump ($ result); show exists, it shows the PHP code? how can I solve this problem?
And why when I try to do the same thing using ajax it returns me the text exists and not PHP code?
You should use full url, to process php file through server.
$url = 'http://YOURURL.com/global.php';
AJAX call is made from browser, to absolute URL, thats why You are getting desired response.

Can't read XML with simplexml_load_file PHP

So i am trying to parse data from an XML url and insert it into a table using php, which can be seen here, (please keep in mind there are more products than displayed on this page, i am not trying to get it for just this Product,the code below shows how i am parsing all products) but i keep getting the following errors:
[EDITED]
class DataGrabber {
//The URL where data will be extracted from, which is an XML file
protected $URL = "http://json.zandparts.com/api/category/GetCategories/44/EUR/";
public function call_api($data) {
if(count($data) == 0) return array();
$jsondata = array();
foreach($data as $entry){
$url = $this->URL . $entry['model'] . "/" . urlencode($entry['family']) . "/" . urlencode($entry['cat']) . "/" . $entry['man'] . "/null";
$json = file_get_contents($url);
$data = json_decode($json, true);
if(!empty($data['Products'])){
foreach ($data['Products'] as $id => $product) {
$jsonentry = array(
'productnumber' => $id,
'partnumber' => $product['strPartNumber'],
'description' => $product['strDescription'],
'manu' => $product['Brand']
);
$jsondata[] = $jsonentry;
}
}
}
return $jsondata;
}
}
[NEW ERRORS]
So i have fixed the error:
PHP Warning: file_get_contents(http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E Series/AC Adapter/Asus/null): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in /home/svn/dev.comp/Asus.php on line 82
by using urlencode as shown in my code above
This warning below isnt finding the values for the url:
PHP Warning: file_get_contents(http://json.zandparts.com/api/category/GetCategories/44/EUR///04G265003580/Asus/null): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
as you can see after, 44/EUR there are three forward slashes with no data?? How would i resolve this??
The remote server appears to use the Accept HTTP header to choose the output format. With PHP default options it sends back JSON instead of XML:
<?php
echo file_get_contents('http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null');
... prints:
{"Categories":[{"Brand":null,"Fami...
To specify an Accept header you need to retrieve the data with some other function, e.g.:
<?php
$context = stream_context_create(
array(
'http' => array(
'header' => "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n",
)
)
);
echo file_get_contents('http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null', false, $context);
... prints:
<?xml version="1.0" encoding="utf-8"?><ProductCategory ...
Tweak it to your exact needs, I just copied the header from my browser.
Here's a code snippet that shows you how to get the values for strPartNumber, strDescription and Brand for all the products in that JSON data:
<?php
$url = 'http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null';
$json = file_get_contents($url);
// Decode the JSON data as a PHP array
$data = json_decode($json, true);
if (!empty($data['Products'])) {
foreach ($data['Products'] as $id => $product) {
echo "Product #{$id}\n";
echo "Part number: {$product['strPartNumber']}\n";
echo "Description: {$product['strDescription']}\n";
echo "Brand: {$product['Brand']}\n\n";
}
}
Output:
Product #0
Part number: 04G265003580
Description: POWER ADAPTER 65W19V 3PIN
Brand: Asus
Product #1
Part number: 14G110008340
Description: POWER CORD 3P L:80CM,TW(B)
Brand: Asus

Categories