Http 400 bad request - Php file_get_contents in Persian URL - php

I'm a newbie and I have a url that contains Persian language characters.
For example this:
http://tabnak.ir/fa/news/577155/ویدیوی-درگیری-نیروهای-سیا-و-پنتاگون-در-سوریه-با-همدیگر-ویدیوهایی-از-جنجال-پاسخ-مشایخی-به-مجیدی-و-حرف‌های-عجیب-الویس-پریسلی-ایران
When I want to get the html source of that url, with this line of code:
$source = file_get_contents($url);
I get this error:
Warning: file_get_contents(http://tabnak.ir/fa/news/577155/ویدیوی-درگیری-نیروهای-سیا-و-پنتاگون-در-سوریه-با-همدیگر-ویدیوهایی-از-جنجال-پاسخ-مشایخی-به-مجیدی-و-حرف‌های-عجیب-الویس-پریسلی-ایران):
failed to open stream: HTTP request failed! HTTP/1.0 400 Bad request in C:\wamp\www\file.php on line 25
I wanted to solve this problem by using the urlencode, but it didn't work.
The urlencode output of that line becomes:
http%3A%2F%2Ftabnak.ir%2Ffa%2Fnews%2F577155%2F%D9%88%DB%8C%D8%AF%DB%8C%D9%88%DB%8C-%D8%AF%D8%B1%DA%AF%DB%8C%D8%B1%DB%8C-%D9%86%DB%8C%D8%B1%D9%88%D9%87%D8%A7%DB%8C-%D8%B3%DB%8C%D8%A7-%D9%88-%D9%BE%D9%86%D8%AA%D8%A7%DA%AF%D9%88%D9%86-%D8%AF%D8%B1-%D8%B3%D9%88%D8%B1%DB%8C%D9%87-%D8%A8%D8%A7-%D9%87%D9%85%D8%AF%DB%8C%DA%AF%D8%B1-%D9%88%DB%8C%D8%AF%DB%8C%D9%88%D9%87%D8%A7%DB%8C%DB%8C-%D8%A7%D8%B2-%D8%AC%D9%86%D8%AC%D8%A7%D9%84-%D9%BE%D8%A7%D8%B3%D8%AE-%D9%85%D8%B4%D8%A7%DB%8C%D8%AE%DB%8C-%D8%A8%D9%87-%D9%85%D8%AC%DB%8C%D8%AF%DB%8C-%D9%88-%D8%AD%D8%B1%D9%81%E2%80%8C%D9%87%D8%A7%DB%8C-%D8%B9%D8%AC%DB%8C%D8%A8-%D8%A7%D9%84%D9%88%DB%8C%D8%B3-%D9%BE%D8%B1%DB%8C%D8%B3%D9%84%DB%8C-%D8%A7%DB%8C%D8%B1%D8%A7%D9%86
Which is not a correct url address, and I can't get contents again.
What should I do?

Can you try this ? This way, you should be able to do the file_get_contents on the encoded url
$url = 'http://tabnak.ir/fa/news/577155/ویدیوی-درگیری-نیروهای-سیا-و-پنتاگون-در-سوریه-با-همدیگر-ویدیوهایی-از-جنجال-پاسخ-مشایخی-به-مجیدی-و-حرف‌های-عجیب-الویس-پریسلی-ایران';
$url = mb_convert_encoding($url, 'HTML-ENTITIES', "UTF-8");
$source = file_get_contents($url);
EDIT (TESTED THIS AND WORKS) :
Try this, maybe by encoding the part of the URL where there are arabic character, it might work :
$link = 'http://tabnak.ir/fa/news/577155/ویدیوی-درگیری-نیروهای-سیا-و-پنتاگون-در-سوریه-با-همدیگر-ویدیوهایی-از-جنجال-پاسخ-مشایخی-به-مجیدی-و-حرف‌های-عجیب-الویس-پریسلی-ایران';
$exploded = explode('/',$link);
$exploded[6] = urlencode($exploded[6]);
$urlimplode = implode($exploded,'/');
$source = file_get_contents($urlimplode);
echo $source;

In my case, where I wanted to pass a parameter with Get, I did as follows:
$message = "یک پیغام تست";
$link = "http://localhost:5000/myAPI_name?msg=".$message;
$exploded = explode('=',$link);
$exploded[1] = urlencode($exploded[1]);
$urlimplode = implode($exploded,'=');
$source = file_get_contents($urlimplode);
$source=json_decode($source,true);
As the content of $message is Persian, I had to perform encoding just for anything after =

Related

PHP Json decode not work in laravel

I have a C# client, its send a json to my php server.
There is the json string:
{"data":[{"name":"1"}]}
Its a valid json. When i try it in PHP Sandbox its works good
$ad = '{"data":[{"name":"1"}]}';
$contents = utf8_encode($ad );
$results = json_decode($contents);
var_dump($results->data);
But,when i try in laravel 5.1, its not work good.
$response = $connection -> getData();
// return $response; (Its equal : {"data":[{"name":"1"}]} )
$contents = utf8_encode($response);
$results = json_decode($contents);
dd($results->data); // Error Trying to get property of non-object
I hope someone can help me.
Thanks!
Based on the comments, it looks like the socket_read() in the getData() method is reading 1 character at a time, and then concatenating each NUL terminated character into a response string. json_decoded() is choking on all the extra NUL characters.
You can either update your logic in the getData() method so it is not doing this, or you can run a str_replace on the results:
$response = $connection -> getData();
// get rid of the extra NULs
$response = str_replace(chr(0), '', $response);
$contents = utf8_encode($response);
$results = json_decode($contents);
dd($results->data);

error in file_get_content() in php

I m trying to generate a QR code with form values my problem is it's showing some error like:
Warning: file_get_contents(http://www.test.com/chart?chs=100x100&cht=qr&chl=test1,test2 , test3): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in local path.
When I m running this code it will generate a QR-code with no data.
So far I have done this:
$datas = $_POST['data'];
$width = $height = 100;
$url = implode(", ",$datas);
$qr_img = "<img src=\"http://www.test.com/chart?chs={$width}x{$height}&cht=qr&chl=$url\" />";
$filename = "images/qr-code/qr-code.png";
$qr = file_get_contents("http://www.test.com/chart?chs={$width}x{$height}&cht=qr&chl=$url");
file_put_contents($filename, $qr);
Please help me to solve this.
I assume that this line:
$url = implode(", ",$datas);
is generating an invalid url. URLs passed as argument to another URL must be url-encoded:
$datas = $_POST['data'];
$width = $height = 100;
$url = urlencode(implode(", ",$datas)); // encode invalid chars
$qr_img = "<img src=\"http://www.test.com/chart?chs={$width}x{$height}&cht=qr&chl=$url\" />";
$qr = file_get_contents("http://www.test.com/chart?chs={$width}x{$height}&cht=qr&chl=$url");
$filename = "images/qr-code/qr-code.png";
file_put_contents($filename, $qr);
see also here: urlencode in PHP

How to use file_get_contents() with non-ASCII characters in URL?

I currentley trying to get data from a website, and use it in my PHP script.
The link I am trying to reach is:
http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=★%20Bayonet
Here is my code:
<?php
$skin = $_GET['market_hash_name'];
$link = "http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=".$skin."";
$FN = file_get_contents($link);
echo $FN;
?>
And this is how I use my link:
http://myhost.com/getPrice.php?market_hash_name=★ Bayonet
This is the error I am getting:
Warning: file_get_contents(http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=★ Bayonet): failed to open stream: HTTP request failed! HTTP/1.0 500 Internal Server Error in F:\xampp\htdocs\getPrice.php on line 5
EDIT:
Okay, so I have found a solution for my problem, but now a new error is comming up:
Warning: file_get_contents(http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=%E2%98%85+Bayonet+%7C+Stained (Factory New)): failed to open stream: HTTP request failed! HTTP/1.0 500 Internal Server Error in F:\xampp\htdocs\getPrice.php on line 7
This is how I am using my link now:
getPrice.php?market_hash_name=★ Bayonet | Stained
And this is my code:
function getPrice($string) {
$skin = urlencode($_GET['market_hash_name']);
$link = "http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=".$skin." ".$string;
$content = file_get_contents($link);
$data = json_decode($content, true);
return $data['lowest_price'];
}
$FN = getPrice("(Factory New)");
$MW = getPrice("(Minimal Wear)");
$FT = getPrice("(Field-Tested)");
$WW = getPrice("(Well-Worn)");
$BS = getPrice("(Battle-Scarred)");
echo "Factory New: $FN; Minimal Wear: $MW; Field-Tested: $FT; Well-Worn: $WW; Battle-Scared: $BS";
Among other characters, non-ASCII characters must be URL-encoded (aka percent-encoded) in query strings.
$skin = url_encode($_GET['market_hash_name']);
$link = "http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=".$skin."";
$FN = file_get_contents($link);

why does json_decode break when passed specific strings?

here is my function in a class called getminecraftprofile.php
basically it takes data from https://sessionserver.mojang.com/session/minecraft/profile/
dependant on the UUID of the user and gets an array that i can pick formation from.
the URL strings are base64 encoded so it decodes that as well.
public function getSkin()
{
$properties = $this->properties;
$encoded = json_encode($properties);
$imgUrl = json_decode(base64_decode(json_decode($encoded,true)[0]['value']),true) ['textures']['SKIN']['url'];
$img = file_get_contents($imgUrl);
echo($img);
}
this is the file that is passing in what user profile to find and get the skin of that profile. for most profiles it works perfectly and you can see it in action at http://jamesplanet.net/test/src/getskin.php?username=dinnerbone
<?php
include ($_SERVER["DOCUMENT_ROOT"] . '/test/src/getminecraftprofile.php' )?>
<?php
$profile = ProfileUtils::getProfile("useruser3");
//$result = $profile->getSkin();
$properties = $profile->getProperties();
$encoded = json_encode($properties);
$imgUrl = json_decode(base64_decode(json_decode($encoded,true)[0]['value']),true)['textures']['SKIN']['url'];
$img = file_get_contents($imgUrl);
var_dump($encoded);
echo('Texture URL Decoded: ' . $imgUrl );
it all grinds to a halt however if i say
$profile = ProfileUtils::getProfile("_jeb");
then it throws this at me
Warning: file_get_contents(): Filename cannot be empty in /Applications/AMPPS/www/test/src/getskin.php on line 10
string(908) "[{"name":"textures","value":"eyJ0aW1lc3RhbXAiOjE0MDM0ODE0Mjk2NDMsInByb2ZpbGVJZCI6IjdmM2ZjY2ZjYzUzOTQzNTdhZmEwMjExYTYyODc3MWU0IiwicHJvZmlsZU5hbWUiOiJfamViIiwiaXNQdWJsaWMiOnRydWUsInRleHR1cmVzIjp7fX0=","signature":"xIgM9w3MfZHMjlsZyrMDAF1CTAhhhhSWfjRqJgW3NNTCyotVkL9IMDN6ZzPIoNESFBlhwspxfKhrAC81+GlEUcFxLYilzO6qE+\/pYciNS78b9MxRK7R5xEoNNzFhXAyo9\/cW5X7V6bFxOB2MU9Fg7NXt\/B\/u4VypqGsbCA+OAm7Kgomlhkw3wkm1R1djfd5oBqwlCKhTWxt4k4mQJzThsqE5ffLdTcPeMoipezw4NHAV1QJfXZZlGsEDG\/KkzUDh6eOz+QufYvhcxGrOAfwJ4TzlLbu0QyT8IRIu0E5LY96sTSecWQ27W7TzsumXiXrkpOSLZrOi5yqGFMmfOEHqo8dLRnxhoNmyQpzN2rE4OvNBwKqvzOeRbigOzQSSg5xupydFFLdc20Pj9CXcTB18K12fXt6W8FJ+AzYUccPrSx\/1RJALkef9W5DCxNLOLLR5yIS8Irff3\/Gn2sRwTG8EXJz+6qRB50e02jdyTv9DZz853w+TAVoNtSkBB8W9aC08XUSCFFg1KAaLILkRi8H+76BE1pZKraPAoW8MpsUbd6J+6k0kU5lqdtiJZ1PtDssVMA+p9MwtOmQqD7n4hPXehULBv4+phQjZi37s1I6ZWYrQBE7raq3ZKfDx9ztccmHEyk\/VHSboo0QmtM8iCOCOC1l0Jv9QrV\/YQRZil03x+OQ="}]" Texture URL Decoded:
i know there is data there because its visible before the base64 decode.
where is it going wrong?
here is an example of what is being parsed
{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch","properties":[{"name":"textures","value":"eyJ0aW1lc3RhbXAiOjE0MDM0ODE0MjIwNDUsInByb2ZpbGVJZCI6IjA2OWE3OWY0NDRlOTQ3MjZhNWJlZmNhOTBlMzhhYWY1IiwicHJvZmlsZU5hbWUiOiJOb3RjaCIsImlzUHVibGljIjp0cnVlLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTExNmU2OWE4NDVlMjI3ZjdjYTFmZGRlOGMzNTdjOGM4MjFlYmQ0YmE2MTkzODJlYTRhMWY4N2Q0YWU5NCJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvM2Y2ODhlMGU2OTliM2Q5ZmU0NDhiNWJiNTBhM2EyODhmOWM1ODk3NjJiM2RhZTgzMDg4NDIxMjJkY2I4MSJ9fX0=","signature":"TJieaNbZrHGmA7V3n8jn0V/ZVPXAy4EK44lxsh3kidK4JML8BEEZZjt/1eixbbXHGMH39e122UO7ehX2PIutuIIK7ZhvAo6wy8yMG34rPxjuyg0jzZe/tZjKv/kq7Bi78m6PErfwBsaUxjkCD3J0sqLXyvOy9rQ2CbYGKTxnVtOZGzxIaQqC5QH/2We704cMUJ3wIgN9FckppVA2E+DYu0G8iFlvYQnjxxIclokv3jOcPrYwVq0COWJaDrGd0+o+dKUfTfiT/k1OLBuceGDmqjb9CmcbEeTFFRJrmA6XEoA6OHZbLOMpIPLtEs8LbZqBH38Cuf+izPGLl1e28bITwPUdpABzvxaxKoYB3XYnWvtAqyfvzsCEgoBVnV7psx1W+kWU9xjCxC591457bollR2KVrSQBv7p0KBm4qVaVPKa01bjcMfcDDx5PRBIcL6XECVmKoeqh+qUrrf1Z9WN0l4OEujmRd8/tbJMjtJTdqCUZ5ak7urJHl8iTNNLqjx/Dsi47DeZvfUGdSC6ivpDIDBQv3myBLNnHqE7/+Z8DGKa+Bf/nQW0sMdVsNFOxIeiXMyXpWAHMw3/Ee21aMWEUq+rD8l4CD2FTZkQ/gv18y3y7CR9fYIKU+EPccnDUtyF+Y257UtCUag7i0vlkiBpIh46jhpjIkhR+iAG4URqQA6I="}]}

file_get_contents works on localhost but times out on server

I have this code :
$feed = 'urltorss';
$feeds = new SimpleXmlElement( file_get_contents($feed) );
$feed = 'http://www.businessweek.com/feeds/homepage.rss';
$feeds = new SimpleXmlElement( file_get_contents($feed) );
Now both urls don't have any special characters that require url encoding them, but the 2nd url has an .rss extension if it's related.
The first call works and i get a timeout on the 2nd when i try on my server but works perfectly on localhost.
This is the error i'm getting :
Severity: Warning
Message: file_get_contents('http://www.businessweek.com/feeds/homepage.rss')
[function.file-get-contents]:
failed to open stream: Connection timed out
Filename: controllers/mailsystem.php
Line Number: 36
Why is that?
First, check your path so
echo $feed; // just for debug
then check the content
$content = #file_get_contents($feed);
and in the end, get the XML
if( $content ) { $feeds = new SimpleXmlElement( file_get_contents($feed) ); }
Edit: file_get_contents for URLs will only work if you have allow_url_fopen = 1. To get the content of http://www.businessweek.com/feeds/homepage.rss you need a cURL function that gets the content. Something like http://davidwalsh.name/curl-download

Categories