In lumen my code is below to send file content in api response , for some document it is working fine but for some document it gives error for HTTP_INTERNAL_SERVER_ERROR
$content = base64_encode(file_get_contents($URL));
Symfony\Component\HttpKernel\Exception\HttpException Object
(
[statusCode:Symfony\Component\HttpKernel\Exception\HttpException:private] => 500
[headers:Symfony\Component\HttpKernel\Exception\HttpException:private] => Array
(
)
[message:protected] => HTTP_INTERNAL_SERVER_ERROR
[string:Exception:private] =>
[code:protected] => 0
[file:protected] => D:\xampp7.1\htdocs\PROJECT_NAME\app\Exceptions\Handler.php
[line:protected] => 76
[trace:Exception:private] => Array
( ...
Is there any solution or required to set php.ini veriable ??
In web error log it gives me error like ,
failed to open stream: HTTP request failed! HTTP/1.1 505 HTTP Version not supported
to resolve this I have get file content with help of below,
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $data[$k]['doc_url']);
$data = curl_exec($ch);
curl_close($ch);
echo"<pre>";print_r($data);die;
it gives me empty output without file contect
I have also add below code
$content = base64_encode(file_get_contents(urlencode($data[$k]['doc_url'])));
$data[$k]['doc_content'] = "$content";
It gives me error of , failed to open stream: No such file or directory in PATH...
Could be that the URL your trying to reach is blocking such ways like you've tried to get contents from their server?
Maybe you should use a CURL with all the relevant settings.
The best way I know to duplicate a request is to open developers console on chrome, then on "Newtork" tab find the request that your trying to mimic. Right click -> Copy -> Copy as CURL (cmd), than paste it here to receive the equivalent PHP CURL code:
https://incarnate.github.io/curl-to-php/
hope it helps, if not, could you expan on the destination you're trying to reach?
good luck
First, you can set context to this kind of request:
$options = array(
'http' => array(
'protocol_version' => '1.0',
'method' => 'GET'
)
);
$context = stream_context_create($options);
Try to get the path to your file like this:
$api = "http://PATH_TO_YOUR_FILE?param=optional_query_params";
$response = file_get_contents($api, false, $context);
Good luck!
Related
I am uploading a file on teamworking using the following link
https://developer.teamwork.com/projects/questions/fileUpload-preferred
Here I am using PHP Codeigniter 4.x framework with CURL to send request and in response to the first step, I am getting Ref and URL both values. i.e. First step is working fine on my end.
Now for the second step as mentioned in the documentation as follows,
Send a PUT request to the link above, with the ‘file’ in the body of the request. Along with this, you need the following headers:
X-Amz-Acl: public-read,
Content-Length: file-size
Host:host-from-the-generate-link
I am passing file object
CodeIgniter\HTTP\Files\UploadedFile Object ( [path:protected] =>
/var/www/web116/tmp/phpDyYgjj [originalName:protected] =>
banner-01.png [name:protected] => banner-01.png
[originalMimeType:protected] => image/png [error:protected] => 0
[hasMoved:protected] => [size:protected] => 639542
[pathName:SplFileInfo:private] => /var/www/web116/tmp/phpDyYgjj
[fileName:SplFileInfo:private] => phpDyYgjj )
in request body.
Here is my code as follows:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // $url is value which I have gotten after first step
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Amz-Acl: public-read',
'Content-Length:' . $fileSize, // size of file
'Host: tw-bucket.s3.amazonaws.com'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['file' => $file])); // $file is file object which I have printed above
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
$result = (array) json_decode($json);
$result['http_code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
But in the HTTP code, I am getting 403 rather than 200.
Can anyone please help me out with this so that I can upload the file on teamwork? I am working to upload a file for a particular task on teamwork.
Thanks
You can find another API to bypass this issue until the Teamwork API Support Team can fix this issue, here is what I did to make this work:
Step 1: Use the API https://apidocs.teamwork.com/docs/teamwork/86ecebd6161af-file-uploading-via-the-api-classic
To do this, you make an API Call to POST /pendingFiles.json. The actual file contents are sent via a form field called “file.”
If this is successful, you will receive a Status Code of 201 (Created) and a structure containing a reference code.
{ “pendingFile”: { “ref” : “tf_xxxxxxxxxxxxxxxx” } }
The ref bit is the important part and is the Pending File Handle.
Step 2: Create an actual file object using the Pending File Handle
The next step is to create the actual file object in a project on your Teamwork account.
To do this, you make an API Call to POST /projects/{id}/files.json where {id} is the project you want to create the file.
{
“file”: {
“description”: “Optional string describing the file”,
“category-id”: “ID of the category you to create the file in. Pass 0 if no category”,
“category-name”: “String if you want to create a new category – Pass category-id=0 also”,
“pendingFileRef”: “tf_xxxxxxxxxxxxxxxx”
}
}
Please note the "fileId" instead of the "pendingFileRef" if you want to attach the file to a task.
This is not a pending file like the other API.
I am using the Google ReCaptcha library in my PHP application. It has been working reliably for quite a while now. However, today, I started receiving errors related to the library.
*[05-Apr-2018 09:19:03 America/Chicago] Severity: 2,Message: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed,File: E:\inetpub\wwwroot\vendor\google\recaptcha\src\ReCaptcha\RequestMethod\Post.php,Line: 68
[05-Apr-2018 09:19:04 America/Chicago] Severity: 2,Message: file_get_contents(): Failed to enable crypto,File: E:\inetpub\wwwroot\vendor\google\recaptcha\src\ReCaptcha\RequestMethod\Post.php,Line: 68
[05-Apr-2018 09:19:04 America/Chicago] Severity: 2,Message: file_get_contents(https://www.google.com/recaptcha/api/siteverify): failed to open stream: operation failed,File: E:\inetpub\wwwroot\vendor\google\recaptcha\src\ReCaptcha\RequestMethod\Post.php,Line: 68*
I did not make any changes to my application. The issue just started suddenly and (from my perspective) without logical explanation.
For reference, here is the Post.php from Google's library (not authored by me).
public function submit(RequestParameters $params)
{
/**
* PHP 5.6.0 changed the way you specify the peer name for SSL context options.
* Using "CN_name" will still work, but it will raise deprecated errors.
*/
$peer_key = version_compare(PHP_VERSION, '5.6.0', '<') ? 'CN_name' : 'peer_name';
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => $params->toQueryString(),
// Force the peer to validate (not needed in 5.6.0+, but still works)
'verify_peer' => true,
// Force the peer validation to use www.google.com
$peer_key => 'www.google.com',
),
);
$context = stream_context_create($options);
return file_get_contents(self::SITE_VERIFY_URL, false, $context);
}
The last line is "68". I am using PHP 7.1. with OpenSSL 1.0.2k 26 Jan 2017. I am calling the library as follows:
// validate ReCaptcha
$response = null;
$reCaptcha = new \ReCaptcha\ReCaptcha(RECAPTCHA_SECRET);
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verify(
$_POST["g-recaptcha-response"], $_SERVER["REMOTE_ADDR"]
);
}
Any advice would be greatly appreciated. The application is hosted on IIS and Windows Server.
Mikail G.'s answer is nearly correct, you do need to access it over CURL. I think something has been changed to actually prevent your current (and mine) from working as I have seen several posts about it all from recent days.
Use this instead:
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'secret' => $secretKey,
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR']
],
CURLOPT_RETURNTRANSFER => true
]);
$output = curl_exec($ch);
curl_close($ch);
$json = json_decode($output);
<?php
if(isset($_POST['submit']))
{
$stream_opts = [
"ssl" => [
"verify_peer"=>false,
"verify_peer_name"=>false,
]
];
$secret = '6Le__FoUAAXXXXXXXXXXXXXXoQtXhJfdZi92ZPHaAj';
$gRecaptchaResponse = $_POST['g-recaptcha-response'];
$remoteIp = $_SERVER['REMOTE_ADDR'];
$url="https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$gRecaptchaResponse&remoteip=$remoteIp";
$response=file_get_contents($url,false, stream_context_create($stream_opts));
$result = json_decode($response);
if ($result->success)
{
header("location: index.php");
}
else
echo 'Captcha verification failed.
}
?>
No need to include the autoload.php file. Just include the file below just before closing tag
<script src='https://www.google.com/recaptcha/api.js'></script> and before the submit button add the following code <div class="g-recaptcha" data-sitekey="6Le__FoUAAXXXXXXXXXXXXXXoQtXhJfdZi92ZPHaAj"></div>
Copy and paste all the folders of recaptcha v2 in home directory of your site. This will 100% work in localhost without ssl. Thanks
In order to fix the issue you need to call the google api with "http" , or use a diffrent way to make request such as curl , here the function to do so :
function file_get_contents_curl($url, $data (array)) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
return $server_output;
}
Why don't you try Step by Step guide to integrate reCpatcha
I have the script below and was wondering why I was getting the error:
failed to open stream: HTTP request failed! HTTP/1.1 401 Authorization Required
The base64 encoded value is in the form username:password and is correct. The API documentation gave the example as:
Authorization: Basic
QWxhZGRpbjpvcGVuIHNlc2FtZQ==
For example, if the user agent uses Aladdin as the username and open sesame as the password, then the field is formed as above in the HTTP header
<?php
$postData = array(
'primaryContact' => array('id' => 1),
'subject' => 'Something not working'
);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=\r\nContent-Type: application/json",
'content' => json_encode($postData)
)
));
// Send the request
$response = file_get_contents('http://127.0.0.1/', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData;
?>
Any ideas?
Tested and your code works. i think its the server. atleast check the server username and password again (your base64 code is correct)
I tested on: iis 7.5 the website has basic auth setup (http 401 Challenge)
(on iis that means that i can use my windows server credentials)
add the $http_response_headers to your error line to get more information.
// Check for errors
if($response === FALSE){
var_dump($http_response_header);
die('Error');
}
I have a very simple script that works perfectly on most sites but not the main site I want it to work with - the code below accesses a sample site perfectly. However when I use it on a site I want to access http://www.livescore.com I get an error
This works.
<?php
$url = "http://www.cambodia.me.uk";
$page = file_get_contents($url);
$outfile = "contents.html";
file_put_contents($outfile, $page);
?>
This does not work.....
<?php
$url = "http://www.livescore.com";
$page = file_get_contents($url);
$outfile = "contents.html";
file_put_contents($outfile, $page);
?>
and gives the following error
Warning: file_get_contents(http://www.livescore.com)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.0 404 Not Found in C:\Program Files
(x86)\EasyPHP-5.3.8.1\www\Livescore\attempt-1-read-page.php on line 3
Thanks for any assistance
In common case you can just say to file_get_contents to follow redirects:
$context = stream_context_create(
array(
'http' => array(
'follow_location' => true
)
)
);
$html = file_get_contents('http://www.example.com/', false, $context);
This site tries to analyze User-agent http header, and fails if it's not found. Try to add some user-agent header:
<?php
$context = stream_context_create(
array(
'http' => array(
'header' => "User-agent: chrome",
'ignore_errors' => true,
'follow_location' => true
)
)
);
$html = file_get_contents('http://www.livescore.com/', false, $context);
echo substr($html, 0, 200)."\n";
Most likely www.livescore.com is doing a hidden redirect which file_get_contents is too basic to catch.
Do you have lynx installed on your server?
$page= shell_exec("lynx -source 'http://www.livescore.com'");
lynx is a full browser and can 'bypass' certain redirects.
I am using simple_html_dom.php library from this example
http://nimishprabhu.com/top-10-best-usage-examples-php-simple-html-dom-parser.html
But i got error 500 inside class, when I type url in browser it works ok?
I have some vaules in array like this
$result= Array (
[Avenya Group AG] =>
Array (
[link] => CHE-218.938.800
[href] => http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0 ) )
When I try something like this
foreach($result as $key => $value) {
$xmlFind = file_get_html($value['href']);
foreach($xmlFind->find('a') as $a) {
echo '<p>'.$a->href.'</p>';
}
}
I got error
A PHP Error was encountered
Severity: Warning
Message: file_get_contents(http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
Filename: libraries/Simple_html_dom.php
Line Number: 76
But when I try manually like this
$xmlFind = file_get_html('http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0');
Result is there, also if i type that url i browser all is ok, only problem i have is when i try to loop an array ??
check http://php.net/manual/en/function.file-get-contents.php Notes section.
Please check your server settings for "fopen wrappers"
I tried the following
<?php
include('simple_html_dom.php');
$result= Array (
'Avenya Group AG' =>
Array (
'link' => 'CHE-218.938.800',
'href' => 'http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0' ) );
foreach($result as $key => $value) {
$xmlFind = file_get_html($value['href']);
foreach($xmlFind->find('a') as $a) {
echo '<p>'.$a->href.'</p>';
}
}
And got this
#
http://www.shab.ch/shabforms/servlet/Search?EID=7&DOCID=6890948
http://www.shab.ch/shabforms/servlet/Search?EID=7&DOCID=981331
http://zh.powernet.ch/webservices/inet/hrg/hrg.asmx/getExcerpt?Chnr=CH-020.3.038.402-5&Amt=20&Lang=1
mailto:info#powernet.ch
Proxy might be a problem. Use appropriate proxy.
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n",
'proxy' => 'tcp://221.176.14.72:80',
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://ifconfig.me/ip', false, $context);
var_dump($file);
Try this,
<?php
$result= Array (
'Avenya Group AG' =>
Array (
'link' => 'CHE-218.938.800',
'href' => 'http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0'
)
);
foreach($result as $arr_item){
if(is_array($arr_item)) {
if(isset($arr_item['href'])) {
echo file_get_contents($arr_item['href']);
}
}
}
?>
After executing above code, I got this response as shown into attached image.
If you still get an warning error, you can use curl to send get request.
so instead of echo file_get_contents($arr_item['href']); above
replace it with the following code.
$ch = curl_init($arr_item['href']);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
This message is returned by the remote server. It shows that the server might be unavailable at this time.
I think this might be caused by a too important amount of resources needed to execute the different requests you made within your loop. It can also be linked to some Denial of Service protection.
After reaching the maximum number of authorized connection, it returns "HTTP 500 Server Too Busy".
See: https://www.iis.net/configreference/system.webserver/asp/limits
The requestQueueMax attribute specifies the maximum number of concurrent ASP requests that are permitted into the queue. Any client browser that attempts to request ASP files when the queue is full is sent an HTTP 500 Server Too Busy error.
You can try to delay each of your call to the url with a sleep() if you're not time limited.
The best thing to do is contact the owner/sys admin of the remote web service in order to let him know about the problem so that he could investigate.
Depending of what you are doing in your script you can also ignore the error message and continue with the next call:
foreach($result as $key => $value) {
// added # to ignore the error
$xmlFind = #file_get_html($value['href']);
// continue to the next result
if (!$xmlFind) continue;
foreach($xmlFind->find('a') as $a) {
echo '<p>'.$a->href.'</p>';
}
}