Php file_get_contents Special Characters - php

im gonna use an api to get player details. Some names are with special characters.
Name Bausí
Url: https/eu.api.battle.net/wow/character/Blackrock/Bausí?fields=statistics&locale=en_GB&apikey=xxx
if i use file_get_contens() there is no response.
Names without special characters works perfectly. I already used rawurlencode() and urlencode(). Both are not working. What can i do?
I read something about urlencode() and rawurlencode() is server dependant.
Thanks Chzn

Well i dont know whats wrong.
$charname = mb_convert_encoding("Bausí", "HTML-ENTITIES", "UTF-8");
$realm = "Blackrock";
$_SESSION["region"] = "eu";
$opts = array('https' => array('header' => 'Accept-Charset: UTF-8, *;q=0'));
$context = stream_context_create($opts);
$char_params = array(
'fields' => "statistics",
'locale' => "en_GB",
'apikey' => "my_api_key"
);
$char_url = "https://".$_SESSION['region'].".api.battle.net/wow/character/".str_replace("'","",$realm)."/".$charname."?".http_build_query($char_params);
if (!$json_char_o = file_get_contents($char_url, false, $context)) {
$error = error_get_last();
echo "HTTPs request failed. Error was: " . $error['message'];
}else{
echo $json_char_decoded = json_decode($json_char_o);
}
it throws me an error:
HTTP request failed. Error was: file_get_contents(https://eu.api.battle.net/wow/character/Blackrock/Bausí?fields=statistics&locale=en_GB&apikey=my_api_key): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
The response should be a json object.
If i open the link manually it works perfectly. What is wrong? :/

Related

file_get_contents change "&" to "&amp"

I want get json from a url with file_get_contents but it replace & with &amp and it dosnt work this way
i tried curl and happened again
i try url directly too and it worked ,so url haven't problem
$url="https://api.kavenegar.com/v1/asdkljsadlkjsd/sms/send.json?receptor=09148523669&sender=100005252&message=testing";
$json = file_get_contents($url);
echo "1";
var_dump($json);
and this is the result:
( ! ) Warning:
file_get_contents(https://api.kavenegar.com/v1/asdkljsadlkjsd/sms/send.json?receptor=09148523669&sender=100005252&message=testing):
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in C:\wamp64\www\te\func\testjson.php on line 22
Of course stackoverflow remove &amp from result url.
The trouble seems to be that it's returning an error status code. If so then see:
Ignoring errors in file_get_contents HTTP wrapper?
$url="https://api.kavenegar.com/v1/asdkljsadlkjsd/sms/send.json?receptor=09148523669&sender=100005252&message=testing";
$context = stream_context_create(array('http' => array('ignore_errors' => true),));
$json = file_get_contents($url, false, $context);
echo $json;
this is the answer :
$url = 'https://example.url?';
// http_build_query builds the query from an array
$query_array = array (
'search' => $string,
'from' => $from,
'to' => $to,
'format' => 'json'
);
$query = http_build_query($query_array);
$result = file_get_contents($url . '&' . $query);

file_get_contents giving warning

$url="http://www.smszone.in/sendsms.asp?page=".$page."&username=".$usrnm."&password=".$passw."&number=".$mobile."&message="."Hi ".$admi.' '.implode($msg)." Is issued ..."."\n"."Regards";
$homepage = file_get_contents($url);
if($homepage)
{
echo "Message Send Compleated...";
}
else{
echo "Something Went Wrong...";
Warning: file_get_contents(http://www.smszone.in/sendsms.asp?page=SendSmsBulk&username=*******&password=****&number=**********&message=Hi Izza AMGR-8A:3/1-BCS-GR:2/1-CCL Is issued ... Regards): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in F:\xampp\htdocs\loglib\logissue.php on line 40
Something Went Wrong...
This is the error i am getting when i run this through my php code. If i copy the generated url and paste in any browser, it works....
Note: I am using xampp
You can use http_build_query function to build correct query string:
$query = [
'page' => $page,
'username' => $user,
// ...
];
$url = 'http://...?'.http_build_query($query);

PHP: failed to open stream: HTTP request failed

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');
}

fedora commons ingest object via REST error

I recently set up FEDORA for a project I am working on to catalogue various
media. I want to be able to consume files (datastreams) via the FEDORA REST api. I managed to create a digital object via curl with no issues at all. I also managed to add an html page as a datastream to the digital object mentioned above with no problems as well.
However, adding a digital object with other content types/file types fails and throws an internal server error 500. On checking the logs, the following error appears:
[http-bio-8080-exec-18] (DatastreamResource) Error with uploaded://47 : XML was not well-formed. Invalid byte 1 of 1-byte UTF-8 sequence
The following is my code snippet of how I am ingesting the files:
$url = "http://localhost:8080/fedora/objects/changeme:5/datastreams/NEWDS8?controlGroup=X&dsLabel=LAZLO";
$file = "namibia2015.pdf";
// Build cURL options
$userPassword = "fedoraAdmin:test123"; // username:password
$verifyPeer = false; // false for ignoring self signed certificates
$headers = array("Accept: text/xml", "Content-Type: " . mime_content_type($file));
$fileContents = file_get_contents($file);
$curlOptions = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userPassword,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_SSL_VERIFYPEER => $verifyPeer,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fileContents
);
$curlHandle = curl_init();
$success = curl_setopt_array($curlHandle, $curlOptions);
throw new Exception(
sprintf(
"curl_setopt_array(...) failed. Error: %s. Info: %s",
curl_error($curlHandle),
print_r(curl_getinfo($curlHandle), true)
),
curl_errno($curlHandle)
);
}
$curlReturn = curl_exec($curlHandle);
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
I came across this post How can I ingest an image into Fedora Commons using PHP? tried the suggested method but still no luck.
What am I doing wrong? What am I missing? Why is it possible to add an html file datastream to the digital object but it fails when I try to
add .jpeg, .pdf, .txt etc?
I finally fixed the error. The exception was being caused by the way I was structuring my URL parameters in my curl request. Using a URL with the following format:
$url = "http://localhost:8080/fedora/objects/changeme:5/datastreams/NEWDS8?controlGroup=X&dsLabel=LAZLO";
will throw the error. Instead, you have to build an http query of all the options you want attached to the POST request. I did that as follows:
$array = array();
$array['dsID'] = '5' ;
$array['controlGroup'] = 'M' ;
$array['altIDS'] = 'Other';
$array['versionable'] = true;
$array['dsLabel'] = 'The pic';
$array['logMessage'] = 'Example log message';
$link = "http://localhost:8080/fedora/objects/changeme:5/datastreams/newobject";
$params = http_build_query($array);
$url = $link.'?'.$params; //add the http query parameters to the url
Thereafter, I made my curl request as before and it will successfully create a data stream attached to the digital object.
Hope this will help someone in the future.

passing headers into file_get_contents() for a json request

I need to pass these headers into the $context variable, i tried using putting the values into an array and then passing it into stream_context_create() function but i get http warnings from the file_getcontents function
$prod_id = 4322;
$tnxRef = "RT45635276GHF76783AC";
$mackey = "ADECNH576748GH638NHJ7393MKDSFE73903673";
$agent = $_SERVER['HTTP_USER_AGENT'];
$hash = hash('SHA512', $prod_id.$txnRef.$mackey);
$headers = array(
'http'=>(
'method'=>'GET',
'header'=>'Content: type=application/json \r\n'.
'$agent \r\n'.
'$hash'
)
)
stream_context_create($headers)
$url_returns = file_get_contents("https://test_server.com/test_paydirect/api/v1/gettransaction.json?productid=$prod_id&transactionreference=$txnRef&amount=$amount", false, $context);
$json = json_decode($url_returns, true);
Error:
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request`
Thats the error i get, can somebody please help with a definitive example.
You have several errors in your code.
The server returns 400 Bad Request, because your code would result in this incorrect HTTP request:
GET /test_paydirect/api/v1/gettransaction.json?productid=4322&transactionreference=RT45635276GHF76783AC&amount= HTTP/1.1
Host: test_server.com
Content: type=application/json
$agent
$hash
The errors are:
Variable expressions are not evaluated within single quotes
$amount is not set in your code example
The header is Content-Type: and not Content: type=
All headers (agent, hash) must have their corresponding name
Here is an example that should work:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'agent' => $agent,
'header' => "Content-Type: application/json\r\n"
. "X-Api-Signature: $hash"
)
)
);
Please note: X-Api-Signature is just an example - it depends on the API you are using how the API key header is named and how the hash is calculated. You should find this information in the Docs of your API!

Categories