This is very basic, but I am kind of confused where I am going wrong (learning how to implement a RESTful Web Service). The context is, I have a simple simulator.php file that simulates an HTTP request to one of my local PHP files. The local PHP file (index.php) does nothing but return a variable with a value. So it's pretty much like this:
<?php
$variable = 'hello';
return $variable;
?>
and my simulator.php file has the following:
?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/kixeye/index.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
var_dump($contents);
curl_close($ch);
?>
However, var_dump($contents) does not quite spit out the value of $variable which is being returned from index.php. I don't quite understand why not.
returning something outside of a function won't actually do anything. The cURL request you are making will return the HTML response from the requested page, so what your really want to do is echo the response rather than using return.
Just change the index.php script to this:
<?php
$variable = 'hello';
echo $variable;
?>
And your var_dump() in the second script will output hello.
The $contents variable will contain the web page being returned by the http request done with Curl. If you only need one value from index.php, just echo it, and its value will end up in $contents as a string.
If you want to retrieve several variables, you could try json encode them and then echo the result in index.php. Then you would have to do the reverse in your second script by json decoding $contents.
Alternatively, you could generate and echo valid php code in the first script, and then eval it in the second, but this is very bad practice (the use of eval is strongly discouraged).
See:
json_encode
eval
Related
I am trying to print php code on web page by using my URL. I know by file name i can print php code using "show_source('filename.php');" but i want to print code by URL, not by file.
I tried:-
<?php
show_source("http://URL.com/index.php");
?>
I also tried this code:-
<?php
$c = curl_init('http://URL.com');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
//curl_setopt(... other options you want...)
$html = curl_exec($c);
if (curl_error($c))
die(curl_error($c));
// Get the status code
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
I also tried this code:-
$html = file_get_contents('https://www.URl.com');
print_r ($html) ;
?>
Short answer: If the web server is configured correctly, it should be impossible to do what you are trying to do.
A correctly configured web server will only send content after PHP has processed it. If the web server is sending raw PHP when a .php file is requested, it is misconfigured. If you are trying to view your own PHP files from a server you control, you can try making a copy of the PHP files and changing the extension to .phps, which the server should send as raw PHP code. Note that this will expose the PHP source to the web, which could present a security risk.
As Mr. Squidward already mentioned, this should not be possible. Otherwise this would be a major security breach since you can store passwords for databases in the PHP files.
A possible solution for your problem would be that you create a REST API on the second server and there you have a function that gets the content of a specific file and returns it in JSON.
But ensure that you don't pass any critical data as passwords or user-data in it.
I tried to find any widget to show Tinkoof's bank currency rate, because it changes every 60sec., but nothing.
Finally I found this API, but there is no any documentation for it.
I tried to find any articles about parsing, but I guess there's no use in that because of absence of any tag.
I need to show the currency rate on my website via this API. Any idea?
Big thanks!
You just need to fetch the content You can use cURL or file_get_contents()
cURL version:
<?php
$url = "https://www.tinkoff.ru/api/v1/currency_rates";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
file_get_contents version:
<?php
$r = file_get_contents('https://www.tinkoff.ru/api/v1/currency_rates');
echo "<pre>";
echo print_r(json_decode($r, true));
echo "</pre>";
?>
Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.
Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.
It looks pretty straightforward to me. For someone with a decent knowledge of PHP will do this, provided the output is:
Now with the above information, I would:
Get the result to PHP using file_get_contents().
Parse the result as an array using json_decode($contents, $true).
Using the above result, I would get display the value using: $output["payload"]["rates"][0]["buy"] or something similar.
At this time of writing, the above will get me 58:
I'm working on a project where I need to get info from iTunes, cache it, and display it on a webpage with PHP. I prefer to use curl, since it seems faster, but I'm more familiar with get_file_contents. An example of the json url is http://itunes.apple.com/lookup?id=284910350. I'm able to grab and decode it, but I'm having trouble from there.
Here's my start:
<?php
$cas = curl_init('http://itunes.apple.com/lookup?id=284910350');
curl_setopt($cas, CURLOPT_RETURNTRANSFER, 1);
$jsonitunes = curl_exec($cas);
curl_close($cas);
$arr = json_decode($jsonitunes,true);
foreach($arr as $item) {
echo "kind: ". $item['kind'] ."<br>";
}
?>
I can print the array, or var_dump it, but can't seem to grab any values. After that, I need to cache the whole thing. If possible, I'd like to set it up to grab new content when it arrives, or on a frequent schedule without weighing down the server.
PHP Notice: Undefined index: kind in /var/www/html/frank/scratch.php on line 9
That should be your first clue (make sure you're logging notices somewhere where you can see them as you work). When you see that, you know you're referencing the array incorrectly.
Your next step should be
var_dump($arr);
to see where the key you're looking for actually is.
Then you should see that you actually need
foreach($arr['results'] as $item) {
Have you tried the json_decode function? You should be able to use cURL to download the contents of that page, store it in a variable, then use json_decode.
<pre>
<?php
$ch = curl_init("http://itunes.apple.com/lookup?id=284910350");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
$jsonDecoded = json_decode($content, true);
echo $jsonDecoded['results'][0]['artistName'];
?>
</pre>
I'm using a file_get_contents to interact with an api for simple GET requests... however sometimes it throws headers signifying there's been an error. How can I get these headers and determine if there's a problem?
Php will set $http_response_header after file_get_contents which contains the response headers as an array of header lines/strings. Its not necessary to use curl if all you want is the headers responses (and probably shouldn't, some LAMP stacks still don't have cURL).
Doc on $http_response_header: http://php.net/manual/en/reserved.variables.httpresponseheader.php
Example:
file_get_contents('http://stacksocks.com');
foreach ($http_response_header as $header)
{
echo $header . "<br>\n";
}
Tips taken from post in comments:
1) The value changes with each request
made.
2) When used in methods/functions, the
current value must be passed to the
method/function. Using
$http_response_header directly in the
method/function without being assigned
a value by a function/method parameter
will result in the error message:
Notice: Undefined variable:
http_response_header
3) The array length and value
locations in the array may change
depending on the server being queried
and the response received. I'm not
sure if there are any 'absolute' value
positions in the array.
4) $http_response_header ONLY gets
populated using file_get_contents()
when using a URL and NOT a local file.
This is stated in the description when
it mentions the HTTP_wrapper.
Use curl instead of file_get_contents.
See: http://www.php.net/manual/en/curl.examples-basic.php
I imagine if your communicating with a REST Api then your actaully wanting the Http Status code returned. In which case you could do something like this:
<?php
$ch = curl_init("http://www.example.com/api/users/1");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 501) {
echo 'Ops it not implemented';
}
fclose($fp);
?>
file_get_contents('http://example.com');
var_dump($http_response_header);
I've got a simple php script to ping some of my domains using file_get_contents(), however I have checked my logs and they are not recording any get requests.
I have
$result = file_get_contents($url);
echo $url. ' pinged ok\n';
where $url for each of the domains is just a simple string of the form http://mydomain.com/, echo verifies this. Manual requests made by myself are showing.
Why would the get requests not be showing in my logs?
Actually I've got it to register the hit when I send $result to the browser. I guess this means the webserver only records browser requests? Is there any way to mimic such in php?
ok tried curl php:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "getcorporate.co.nr");
//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);
same effect though - no hit registered in logs. So far it only registers when I feed the http response back from my script to the browser. Obviously this will only work for a single request and not a bunch as is the purpose of my script.
If something else is going wrong, what debugging output can I look at?
Edit: D'oh! See comments below accepted answer for explanation of my erroneous thinking.
If the request is actually being made, it would be in the logs.
Your example code could be failing silently.
What happens if you do:
<?PHP
if ($result = file_get_contents($url)){
echo "Success";
}else{
echo "Epic Fail!";
}
If that's failing, you'll want to turn on some error reporting or logging and try to figure out why.
Note: if you're in safe mode, or otherwise have fopen url wrappers disabled, file_get_contents() will not grab a remote page. This is the most likely reason things would be failing (assuming there's not a typo in the contents of $url).
Use curl instead?
That's odd. Maybe there is some caching afoot? Have you tried changing the URL dynamically ($url = $url."?timestamp=".time() for example)?