file_get_contents api link two connections with session - php

I have two api pages, api1.php and api2.php. On 1 there is set an session and on 2 this session needs to be returned.
Ofcourse there will be additional functions but my goal of this is to link those two api connections to one and eachother by using a session.
api1.php:
session_start();
$api_key = 'dfdsakdsfjdskfjdskfdsjfdfewfifjjsd';
$_SESSION['api_key'] = $api_key;
setcookie('api_key', $api_key);
api2.php:
session_start();
echo $_SESSION['api_key'];
echo $_COOKIE['api_key'];
test.php:
$url = 'http://example.com/api1.php';
$content1 = file_get_contents($url);
$url2 = 'http://example.com/api2.php';
$content2 = file_get_contents($url2);
echo $content2;
As you may have noticed, i'm visiting the page test.php to obtain a result.
But no result is being returned.
Can somebody tell me why this is not working and what may be an additional way of making all of this happen?
(Notice: the example.com are both the same site (mine))

You're code "links" correctly. The problem is actually in test.php! Instead of executing the code contained in both files, it retrieves the entire file. If you view source you will note the PHP tags and your code. A better solution to check if this is working is to go to api1.php and api2.php separately. With some code adjustments you could also just use the include() or require() functions. Which would look like this:
api2.php
echo $_SESSION['api_key'] . "\n<br/>\n";
echo $_COOKIE['api_key'];
test.php
include('api1.php');
include('api2.php');
It's worth noting the using the include and require functions executes the code in api1.php and api2.php as if that code were a part of test.php.

Related

What's wrong with this include statement?

This function is returning the content of the file rather the result of fetch_link_settings_overide() within it.
The issue is not with the overide function as after the initial error I commented out my modification just to be sure it wasn't something I had done there.
function fetch_link_settings(){
include( plugins_url()."/plugin-child/plugin_overrides.php");
return fetch_link_settings_override();
}
Adding the content of the derived function plugin-child/plugin_overrides.php as we are not getting anywhere currently.
function fetch_link_settings_override(){
global $post;
// If the destination url is set by the user, use that. Otherwise, use the permalink
$destination_url = get_post_meta($post->ID, '_promo_slider_url', true);
// ASAdd additional place to look in the case of the post being via the PODS advert track
if( ! $destination_url )
$destination_url = get_post_meta($post->ID, 'okd_advert_link', true);
if( ! $destination_url )
$destination_url = get_permalink($post->ID);
// If the target attribute is set by the user, use that. Otherwise, set it to _self
$target = get_post_meta($post->ID, '_promo_slider_target', true);
if( ! $target ) $target = '_self';
// Setup the disable links variable
$disable_links = get_post_meta($post->ID, '_promo_slider_disable_links', true);
return compact('destination_url', 'target', 'disable_links');
}
You write this:
include( plugins_url()."/plugin-child/plugin_overides.php");
Why is plugins_url() there? The include function is strictly based on the file system:
The `include` statement includes and evaluates the specified file.
As explained in the WordPress docs, the plugins_url() would give you the full web URL which is 100% different than the file system WordPress is installed on:
Retrieves the absolute URL to the plugins directory (without the
trailing slash) or, when using the $path argument, to a specific file
under that directory.
So perhaps it should be like this:
include("/plugin-child/plugin_overides.php");
Or perhaps you need the plugin_dir_path()?
include(plugin_dir_path( __FILE__ ) . "/plugin-child/plugin_overides.php");
But that seems wrong. Where would /plugin-child/plugin_overides.php? Try doing this:
include("/full/path/to/wordpress/and/this/plugin-child/plugin_overides.php");
Just replace /full/path/to/wordpress/and/this/ with the actual file system path to /plugin-child/plugin_overides.php.
EDIT: Since the original poster is persistent in using plugins_url() despite all of the suggestions otherwise, here is my detailed response:
…you said “you cannot load raw functions via a URL with include” well
this is not relevant because even if I add $some_var = 'smith'; as the
first statement in the included file, it is not visible in the
function using the include.
Apologies. Functions, classes, strings, constants… Just about anything that you want to be raw, unprocessed PHP will simply not be passed via an http:// or https:// URL because Apache will parse the PHP instructions & simply return the output of that file and not the raw, unprocessed contents of the PHP in that file.
Additionally the original poster contents the following:
You can’t help me because what you are saying does not make sense or
you are not explaining yourself adequately. Look at these examples:
include realpath(dirname(FILE) . "/" . "relative_path");
include("data://text/plain;base64,".base64_encode($content));
include("data://text/plain,".urlencode($content));
All taken from the official PHP documentation. They all use
functions returning components that are concatenated with the rest of
the url. I also tried this typing the filepath explicitly and the
result is the same.
The examples cited are as follows:
include realpath(dirname(FILE) . "/" . "relative_path");
This is a filesystem level include which is the most common way PHP files are included into other files.
include("data://text/plain;base64,".base64_encode($content));
include("data://text/plain,".urlencode($content));
These are both data URLs. Not http or https. So again when you use plugins_url() what you are getting is a full http:// or https:// URL in which Apache parses the PHP instructions & simply return the output of that file and not the raw, unprocessed contents of the PHP in that file. Or as very clearly explained in the PHP documentation you are linking to; emphasis mine:
If "URL include wrappers" are enabled in PHP, you can specify the file
to be included using a URL (via HTTP or other supported wrapper - see
Supported Protocols and Wrappers for a list of protocols) instead of a
local pathname. If the target server interprets the target file as PHP
code, variables may be passed to the included file using a URL request
string as used with HTTP GET. This is not strictly speaking the same
thing as including the file and having it inherit the parent file's
variable scope; the script is actually being run on the remote server
and the result is then being included into the local script.
Going back to your example, you say now the contents of plugin_overides.php is $some_var = 'smith';. How exactly? If it is a PHP file like this:
<?php
$some_var = 'smith';
?>
When you call that file via a URL generated by the following code:
include(plugins_url() . "/plugin-child/plugin_overrides.php");
Assuming your website is http://some.cool.website/ the you are basically making a call like this:
http://some.cool.website/plugin-child/plugin_overides.php
So the output of plugin_overides.php would be 100% blank. If you wanted to get output of that file, you could do the following:
<?php
$some_var = 'smith';
echo $some_var;
?>
And that would return smith. Meaning the absolute ONLY output you would get from that call is pure text. Nothing else.
Now I see you actually have posted the contents of plugin_overides.php. My example explanation above is still apt, but still a basic question. This is your function; just the interface & return for example:
function fetch_link_settings_override(){
// Other code removed. Just a structural illustration for now.
return compact('destination_url', 'target', 'disable_links');
}
Do you actually call fetch_link_settings_override() in plugin_overides.php when it runs? Well, if that function does not run, then there is 100% no way you will ever get any output. But assuming good faith, look at your return statement here:
return compact('destination_url', 'target', 'disable_links');
If you are returning compact, then you are returning an array. You cannot simply return a bare array as a URL call like this http://some.cool.website/plugin-child/plugin_overides.php. The output at most would be simply the word Array.
If the goal is to take that array & do something, then you should use json_encode in fetch_link_settings_override and then use json_decode on the receiving side of that. So the return statement would be something like this:
return json_encode(compact('destination_url', 'target', 'disable_links'));

How can I use file_get_contents without losing echo values?

Let's begin with an article on a static page (Test.php) that includes another file full of PHP code (Code.php). Some of the echo values on Code.php are declared on a third file higher up the food chain (Values.php).
Everything works fine - until I take the article out of Test.php, insert it in a database and display it by echoing $Content. Now my include doesn't work, since you can't put PHP includes inside a database. (Or maybe you can, but it's apparently next to impossible, and everyone screams DON'T DO IT!)
I just learned how to use file_get_contents:
$Content = str_replace('<p id="1"', '.file_get_contents($BaseINC."/inc/Test.php").'<p id="1">', $Content);
It works great, except that it only displays static text - no PHP code.
Then I learned how to parse the file, like this:
file_get_contents("http://MySite/Test.php")
It works better. I can echo $Something, as long as $Something is defined in Test.php...
$Something = 'Cool!';
echo $Something;
The problem is that all the echo values that are defined on a separate file (e.g. Values.php) no longer work, apparently because I've removed Test.php from the flow. Is there a way to somehow reconnect Test.php with Code.php so those echo values will regain their values? Or is there some other way to accomplish what I'm trying to do?
For whatever it's worth, most of the missing values are created by a database query. One workaround is to recreate the values based on each page's URL. The irony is that all the scripts I've tried for displaying page URL don't even work; instead, they display the path to Test.php. So I'm really confused.
I tried to illustrate the different ways of including a php file:
<?php
//Test.php
$bar = 'orange'; echo $bar;
<?php
// Example.php
echo file_get_contents("Test.php") // $bar = 'orange'; echo $bar;
echo file_get_contents("http://example.com/Test.php") // orange
// Probably not correct, big security risk https://www.owasp.org/index.php/Code_Injection
include("Test.php") // orange

simple_html_dom not finding my element

I'm trying prices off of Amazon for an exercise.
<?php
require('simple_html_dom.php');
$get = $_GET['id'];
$get_url = 'http://www.amazon.co.uk/s/field-keywords='.$get;
echo $get_url;
// Retrieve the DOM from a given URL
$html = file_get_html($get_url);
foreach($html->find('li[class=newp]') as $e)
echo $e->plaintext . '<br>';
I tried a few differents:
li[class=newp]
.price
ul[class=rsltL]
but it doesn't return anything, what am I doing wrong?
I tried returning the titles as well:
.lrg.bold
Tried Xpath, nothing.
Thanks
Your code is fine. It is very likely that your PHP settings are the culprits.
put
error_reporting(E_ALL);
ini_set('display_errors', '1');
at the begining of your php script and see if it prints out any useful error.
Also, note that simple_html_dom uses the file_get_contents() function internally to grab page content. So, you may want to run file_get_contents($get_url) to see what happens.
If that function does not work then it is definitely your PHP setting. In such case, I recommend starting another thread with that issue in the title.
This might help though:
PHP file_get_contents does not work on localhost

How to Capture PHP Output into a Variable

I've been wanting to do this because my site does about 3 HTTP requests per page load, because each PHP's output is retrieved with cURL. This is too slow, and I want to avoid using cURL. I found this question on Stack Overflow, and it basically does what I want. The accepted answer's suggestion is to use ob_start(); to start getting output then use ob_get_clean(); to put the output into a variable. My issue now is that the PHP scripts I'm trying to capture output from need variables passed to them using HTTP Get. The access those variables like this:
$term = $_GET['term'];
And I don't want to change that, because although I'm going to access these PHP scripts' outputs from another PHP script, I'm also planning on accessing them from elsewhere. So, is there a way to fool these PHP scripts into accepting some arguments through Get, then capturing their outputs with the method suggested above?
You can $_GET variables from any php script if its set (use isset to check that). Then just cURL to such url's will work.
If you have changed the method to POST earlier, you can use CURLOPT_HTTPGET. See the curl_setopt functions page (http://www.php.net/manual/en/function.curl-setopt.php) for more details.
For a non-cURL method, use jQuery ajax. It is quite simple to use, just read the documentation here.
EDIT: This is what you wanted (haven't checked the code though)
<?php
function get_include_contents($filename, $get) {
if (is_file($filename)) {
ob_start();
$_GET = array();
while (list($key, $val) = each($get)) {
$_GET[$key]=$val;
}
include $filename;
return ob_get_clean();
}
return false;
}
$string = get_include_contents('somefile.php', array('param1'=>'x', 'param2'=>'y'));
?>
And I don't want to change that, because although I'm going to access these PHP scripts' outputs from another PHP script, I'm also planning on accessing them from elsewhere. So, is there a way to fool these PHP scripts into accepting some arguments through Get, then capturing their outputs with the method suggested above?
Your question is a bit unclear as to why you're using cURL in the first place. If your scripts are on the same server, you can simply set the correct $_GET variables and use:
<?php
ob_start( );
// include the file.
$_GET['foo'] = 'bar';
include 'the_file.php';
$output = ob_get_clean( );
If your scripts are located on another server, where include is not viable, you will always have to do a HTTP request to get their contents, regardless of whether your this with cURL or Ajax, or sockets for all I care.
well you can access a $_GET from any script loaded as long as its in the URI, the variable $term can be used in any script. You can also include the script.
When you include a script you can access some of its content after the include.

Secretly adding (extra) HTTP GET Variables to a swf file through PHP

I'm trying to build a workaround for embedding my (downloaded) flash videoplayer. (it's the JWplayer...)
At the moment, when somebody wants to embed the videoplayer they have to include the swf with all the added flashvars (ex: www.site.be/core/swf/player.swf?streamer=url&file=file.mp4&image=file.jpg&plugin=analytics...).
That's messy, and it feels a bit risky... people who know what they are doing can also just remove the plugin and other added data, resolving in me not being able to track pageviews etc.
My workaround is like this:
$data = file_get_contents('URL');
header("content-type: application/x-shockwave-flash");
echo $data;
Turns out that, when I use file_get_contents on a regular test file, info.php, that responds through a $_GET['var'], the above stated code works, but when I use it on the flashplayer, it doesn't...
As in: the flash file does not seem to be accepting (or responding to) the added header variables...
Can somebody tell me why this is? Is this a 'flash' related problem or a 'Php' related problem?
Or are there suggestions on how to handle my "flash-embed-with-to-much-junk"-problem in a different way?
(thanks)
The flash is expecting GET parameters so you can't force them any other way.
What I would do is store the GET variables in a SESSION (called swf_vars in my example) if you want it a secret, then have the <embed> code point to a PHP script that does something like..
<?php
session_start();
// Full URL path to SWF
$url = "http://www.site.be/core/swf/player.swf?";
// These are the GET variables you want
foreach ($_SESSION['swf_vars'] as $key => $value) {
$url .= $key . "=" . urlencode($value) . "&";
}
$url = rtrim("&", $url);
// Fetch the SWF
header("Content-Type: application/x-shockwave-flash");
echo file_get_contents($url);
?>

Categories