I'm having trouble with this script. It works on my local server and test server, but doesn't seem to run correctly on my Rackspace server.
<?php
$path = "http://query.yahooapis.com/v1/public/yql?q=";
$path .= urlencode("SELECT * FROM feed WHERE url='http://feeds.feedburner.com/TMSEvents'");
$path .= "&format=json";
$feed = file_get_contents($path, true);
$feed = json_decode($feed); ?>
It is very simple, but I am getting the follow error message on the Rackspace server:
PHP Warning:
file_get_contents(http://query.yahooapis.com/v1/public/yql?q=SELECT+%2A+FROM+feed+WHERE+url%3D%27http%3A%2F%2Ffeeds.feedburner.com%2FTMSEvents%27&format=json)
[function.file-get-contents]:
failed to open stream: HTTP request failed! HTTP/1.0 500 999 This page
is currently unavailable
Anyone have any ideas why this would work on one server, but not on another? Thanks!
Look on this : http://codular.com/curl-with-php
Try Below code. Its working fine with tested :
<?php
$path = "http://query.yahooapis.com/v1/public/yql?q=";
$path .= urlencode("SELECT * FROM feed WHERE url='http://feeds.feedburner.com/TMSEvents'");
$path .= "&format=json";
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $path,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$feed = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$feed = json_decode($feed);
?>
Related
I'm trying to return JSON results from a page but I get the following error using file_get_contents(): " failed to open stream: HTTP request failed! "
Can someone tell me why I get this error?
<?
$newURL = 'https://api.qwant.com/api/search/images?count=10&offset=1&q=Spicy
Cranberry Cavolo Nero (Kale)';
$returnedData = file_get_contents($newURL);
?>
Never use <? ?>. Use only <?php ?> or <?= ?>
urlencode() use only on values of your parameters, not on the whole parameter's line.
file_get_contents() is not a really good method to receive data from the outer servers. Better use CURL.
<?php
// Your URL with encoded parts
$newURL = 'https://api.qwant.com/api/search/images?count=10&offset=1&q='.urlencode('Spicy Cranberry Cavolo Nero (Kale)');
// This is related to the specifics of this api server,
// it requires you to provide useragent header
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => 'any-user-agent-you-want',
);
// Preparing CURL
$curl_handle = curl_init($newURL);
// Setting array of options
curl_setopt_array( $curl_handle, $options );
// Getting the content
$content = curl_exec($curl_handle);
// Closing conenction
curl_close($curl_handle);
// From this point you have $content with your JSON data received from API server
?>
I'm using file_get_contents() to get a PHP file which I use as a template to create a PDF.
I need to pass some POST values to it, in order to fill the template and get the produced HTML back into a PHP variable. Then use it with mPDF.
This works perfectly on MY server (a VPS using PHP 5.6.24)...
Now, at the point where I'm installing the fully tested script on the client's live site (PHP 5.6.29),
I get this error:
PHP Warning: file_get_contents(http://www.example.com/wp-content/calculator/pdf_page1.php): failed to open stream: HTTP request failed! HTTP/1.1 406 Not Acceptable
So I guess this can be fixed in php.ini or some config file.
I can ask (I WANT TO!!) my client to contact his host to fix it...
But since I know that hosters are generally not inclined to change server configs...
I would like to know exactly what to change in which file to allow the code below to work.
For my personnal knowledge... Obviously.
But also to make it look "easy" for the hoster (and my client!!) to change it efficiently. ;)
I'm pretty sure this is just one PHP config param with a strange name...
<?php
$baseAddr = "http://www.example.com/wp-content/calculator/";
// ====================================================
// CLEAR OLD PDFs
$now = date("U");
$delayToKeepPDFs = 60*60*2; // 2 hours in seconds.
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if(substr($entry,-4)==".pdf"){
$fileTime = filemtime($entry); // Returns unix timestamp;
if($fileTime+$delayToKeepPDFs<$now){
unlink($entry); // Delete file
}
}
}
closedir($handle);
}
// ====================================================
// Random file number
$random = rand(100, 999);
$page1 = $_POST['page1']; // Here are the values, sent via ajax, to fill the template.
$page2 = $_POST['page2'];
// Instantiate mpdf
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new mPDF( __DIR__ . '/vendor/mpdf/mpdf/tmp');
// GET PDF templates from external PHP
// ==============================================================
// REF: http://stackoverflow.com/a/2445332/2159528
// ==============================================================
$postdata = http_build_query(
array(
"page1" => $page1,
"page2" => $page2
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
// ==============================================================
$STYLE .= file_get_contents("smolov.css", false, $context);
$PAGE_1 .= file_get_contents($baseAddr . "pdf_page1.php", false, $context);
$PAGE_2 .= file_get_contents($baseAddr . "pdf_page2.php", false, $context);
$mpdf->AddPage('P');
// Write style.
$mpdf->WriteHTML($STYLE,1);
// Write page 1.
$mpdf->WriteHTML($PAGE_1,2);
$mpdf->AddPage('P');
// Write page 1.
$mpdf->WriteHTML($PAGE_2,2);
// Create the pdf on server
$file = "training-" . $random . ".pdf";
$mpdf->Output(__DIR__ . "/" . $file,"F");
// Send filename to ajax success.
echo $file;
?>
Just to avoid the "What have you tried so far?" comments:
I searched those keywords in many combinaisons, but didn't found the setting that would need to be changed:
php
php.ini
request
header
content-type
application
HTTP
file_get_contents
HTTP/1.1 406 Not Acceptable
Maaaaany thanks to #Rasclatt for the priceless help! Here is a working cURL code, as an alternative to file_get_contents() (I do not quite understand it yet... But proven functional!):
function curl_get_contents($url, $fields, $fields_url_enc){
# Start curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
# Required to get data back
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
# Notes that request is sending a POST
curl_setopt($ch,CURLOPT_POST, count($fields));
# Send the post data
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_url_enc);
# Send a fake user agent to simulate a browser hit
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56');
# Set the endpoint
curl_setopt($ch, CURLOPT_URL, $url);
# Execute the call and get the data back from the hit
$data = curl_exec($ch);
# Close the connection
curl_close($ch);
# Send back data
return $data;
}
# Store post data
$fields = array(
'page1' => $_POST['page1'],
'page2' => $_POST['page2']
);
# Create query string as noted in the curl manual
$fields_url_enc = http_build_query($fields);
# Request to page 1, sending post data
$PAGE_1 .= curl_get_contents($baseAddr . "pdf_page1.php", $fields, $fields_url_enc);
# Request to page 2, sending post data
$PAGE_2 .= curl_get_contents($baseAddr . "pdf_page2.php", $fields, $fields_url_enc);
I used to include files between sites routinely, until my webhost banned the practice. Now it appears that a recent PHP upgrade also tightened the screws, as I'm getting a "no suitable wrapper could be found" error - and I'm working with LOCAL sites.
Let's start with a website # www.gx.com and a subdomain at subdomain.mysite.com. However, they display locally as two separate websites - mysite.com and subdomain.com.
A page on subdomain.com features the following include request:
require_once($GX_URL."/2b/inc/D/Shared/Body/Bottom/Footer.php
$GX_URL displays as http[://]gx locally and http[://]gx.com online.
How can I modify this include so it works in both situations? I can use the following switch to hold two separate includes, one for online use and the other for local use:
switch(PHP_OS)
{
case 'Linux':
break;
default:
break;
}
I just figured the answer to my first question; I simply mapped out the entire path to the file in the other website on my computer:
/Applications/MAMP/htdocs/gx/2b/inc/D/Shared/Body/Bottom/Footer.php
So I guess I need to do something similar to include a file from my main domain. However, I'll leave this question open in case anyone has a more elegant solution.
I have more you can try one.
Try download html and include to your php page :).
Http Request or CURL request
Use Allow_url_include, example: http://wiki.dreamhost.com/Allow_url_include
Use Object download: http://php.net/manual/de/function.ob-start.php
Example::
1. Curl Download html string
function curl_get($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, $this->CURL_UA);
curl_setopt($ch, CURLOPT_REFERER, $this->YT_BASE_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
curl_close ($ch);
return $contents;
}
2. Http send request width file_get_contents
function sendRequest($url, $data = array())
{
$data = http_build_query($data);
$context_options = array('http' => array('method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($data) . "\r\n",
'content' => $data)
);
$context = stream_context_create($context_options);
$result = file_get_contents($url, false, $context);
return $result;
}
3 Object : http://php.net/manual/de/function.ob-start.php
When i'm trying to invoke the YQL via cURL i'm getting the following error.
HTTP Version Not Supported
Description: The web server "engine1.yql.vip.bf1.yahoo.com" is using an unsupported version of the HTTP protocol.
Following is the code used
// URL
$URL = "https://query.yahooapis.com/v1/public/yql?q=select * from html where url=\"http://www.infibeam.com/Books/search?q=9788179917558\" and xpath=\"//span[#class='infiPrice amount price']/text()\"&format=json";
// set url
curl_setopt($ch, CURLOPT_URL, $URL);
//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);
echo $output;
?>
Invoking the same URL from thr browser works fine
https://query.yahooapis.com/v1/public/yql?q=select * from html where
url="http://www.infibeam.com/Books/search?q=9788179917558" and
xpath="//span[#class='infiPrice amount price']/text()"&format=json
Can someone please point me what is wrong in the code?
The problem is probably caused because the url you feed to cURL is not valid. You need to prepare / encode the individual values of the query strings for use in a url.
You can do that using urlencode():
$q = urlencode("select * from html where url=\"http://www.infibeam.com/Books/search?q=9788179917558\" and xpath=\"//span[#class='infiPrice amount price']/text()\"");
$URL = "https://query.yahooapis.com/v1/public/yql?q={$q}&format=json";
In this case I have only encoded the value of q as the format does not contain characters that you cannot use in a url, but normally you'd do that for any value you don't know or control.
Okay I gottacha .. The problem was with the https. Used the following snippet for debug
if (false === ($data = curl_exec($ch))) {
die("Eek! Curl error! " . curl_error($ch));
}
Added below code to accept SSL certificates by default.
$options = array(CURLOPT_URL => $URL,
CURLOPT_HEADER => "Content-Type:text/xml",
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_RETURNTRANSFER => TRUE
);
Complete code is here
<?php
// create curl resource
$ch = curl_init();
// URL
$q = urlencode("select * from html where url=\"http://www.infibeam.com/Books/search?q=9788179917558\" and xpath=\"//span[#class='infiPrice amount price']/text()\"");
$URL = "https://query.yahooapis.com/v1/public/yql?q={$q}&format=json";
echo "URL is ".$URL;
$ch = curl_init();
//Define curl options in an array
$options = array(CURLOPT_URL => $URL,
CURLOPT_HEADER => "Content-Type:text/xml",
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_RETURNTRANSFER => TRUE
);
//Set options against curl object
curl_setopt_array($ch, $options);
//Assign execution of curl object to a variable
$data = curl_exec($ch);
echo($data);
//Pass results to the SimpleXMLElement function
//$xml = new SimpleXMLElement($data);
echo($data);
if (false === ($data = curl_exec($ch))) {
die("Eek! Curl error! " . curl_error($ch));
}
if (200 !== (int)curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
die("Oh dear, no 200 OK?!");
}
//Close curl object
curl_close($ch);
?>
When I was making an xml request to tmdb.org I was using this
$movie_name="Dabangg 2";
$xml = simplexml_load_file("http://api.themoviedb.org/2.1/Movie.search/en/xml/accd3ddbbae37c0315fb5c8e19b815a5/"$movie_name"");
and it was working !!
Now I have to change the URL since the response is JSON not xml
I have changed it to
<?php
$movie_name="Dabangg 2";
$url="http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=$movie_name";
$json = file_get_contents($url);
var_dump($json);
?>
But it does not work
If you search for
http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=Dabangg 2
on browser you will get the results.
Warning: file_get_contents(http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=Dabangg 2) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 BAD_REQUEST in /home/wwww/public_html/test/movie.php on line3
Please help me
Try with
urlencode($movie_name);
This function is convenient when encoding a string to be used in a
query part of a URL, as a convenient way to pass variables to the next
page.
Look on this : http://codular.com/curl-with-php
Try Below code :
<?php
$movie_name="Dabangg 2";
$movie_name = urlencode($movie_name);
$url="http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=$movie_name";
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
var_dump($resp);
?>