Here is the code i wrote so far:
<?php
do {
//If this isn't the first time in the loop, pause for a second to prevent spamming their servers
if(isset($statusCode)){
sleep(1);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://steamcommunity.com/profiles/76561198258195397/inventory/json/730/2");
//The curl request should return the body of the text
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Apparently the URL provided initially returns with a 3XX response, this option follows the redirection.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$steamData = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//Repeat this command until we get a successful request
//Note that this is slightly naive - Any 2XX should be deemed successful.
} while ($statusCode !== 200);
//$steamData = file_get_contents("http://steamcommunity.com/profiles/76561198258195397/inventory/json/730/2");
$data = json_decode($steamData, true);
$items = $data['rgDescriptions'];
foreach($items as $key => $item){
$market_hash_name = $item["market_hash_name"];
$market_hash_name = htmlentities($market_hash_name, ENT_QUOTES, 'UTF-8');
$sql = "SELECT price FROM itemprice WHERE market_hash_name='".$market_hash_name."'";
$result = $conn->query($sql);
$itemprice = "-";
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
if($row['price']>0.02){
$itemprice = $row['price'];
$itemprice = floatval($itemprice);
$itemprice = $itemprice*1.05;
$itemprice = round($itemprice, 3);
}else{
$itemprice = 0;
}
}
}
echo '<div class="items"><center><img src="http://steamcommunity-a.akamaihd.net/economy/image/' . $item["icon_url"] . '" height="192" width="256"></center><div><center><h5 style="color:#'.$item["name_color"].'">'.$item["market_name"].' - <strong><b><a style="color:green">$'.$itemprice.'</a></b></strong></h5></center></div></div>';
}
?>
So sometimes its just loading and after around 20sec it stops the chrome giving me an error like i dont have internet connection, and i cant open any page on the site for 1min.But after that everything is okay...Does anybody know another alternative to get the inv?
here is a ss of the output on the site: https://gyazo.com/80e9d1cf3e6dd0ae151a9f85cc1e0cf9
Related
The below script means for cross domain and pull out the JSON result for the select menu. Currently the CURL able to echo out the $result but unable to display in the select menu with console log error: Uncaught ReferenceError: the $result is not defined. I need help on diagnosing this matter.
<?php
$data_string = json_encode($data, JSON_UNESCAPED_SLASHES);
$ch = curl_init('https://xxxxxxx.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);
echo ($result);
?>
<script>
let dropdown = $('#title-dropdown');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose Title</option>');
dropdown.prop('selectedIndex', 0);
const url = $result;
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.description).text(entry.display_name));
})
});
</script>
You aren't outputting the PHP $result variable to the Javascript, you're telling javascript to look for a variable that doesn't exist. Try
const url = '<?php echo $result ?>';
it's been a while since I've done any PHP but that should at least put you on the right track if it isn't 100% correct.
Change this
const url = $result;
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.description).text(entry.display_name));
})
});
to this:
const json = $.parseJSON('<?php echo $result; ?>');
var result = json.result;
for (var i = 0; i < result.length; i++) {
for (var key in result[i]) {
console.log('KEY: ' + key + 'VALUE: ' + result[i][key]);
}
}
I have this code that outputs me source page of source URL with curl!
$url = 'http://source-page.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // add this one, it seems to spawn redirect 301 header
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); // spoof
$output = curl_exec($ch);
curl_close($ch);
$html = str_get_html($output);
In $output i have this:
var flashvars = {
"image_url":"http://path-to-image.com",
"video_title":"This is video title",
"videoUrl":"http://this-is-path-to-mp4.com"
}
I want to echo videoUrl and I have tried with this:
$videoUrl = $html->find('flashvars[0].videoUrl');
echo $videoUrl
And is giving me empty results. What is a good code for doing that?
Someone else suggessted regex + json_decode and then deleted it.
Here's what I would do:
$output = <<<EOF
var flashvars = {
"image_url":"http://path-to-image.com",
"video_title":"This is video title",
"videoUrl":"http://this-is-path-to-mp4.com"
}
EOF;
$str = preg_match('/var flashvars = (\{.*?\})/s', $output, $m);
$data = json_decode($m[1], true);
echo $data['videoUrl'];
I looked around a lot before posting this question so my apologies if it is on another post and this is only my second quesiton on here so apologies if I don't format this question correctly.
I have a really simple web service that I have created that needs to take post values and return a JSON encoded array. That all worked fine until I was told I would need to post the form data with a content-type of application/json. Since then I cannot return any values from the web service and it is definitely something to do with how I am filtering their post values.
Basically in my local setup I have created a test page that does the following -
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
On the webservice I have this (I have stripped out some of the functions) -
<?php
header('Content-type: application/json');
/* connect to the db */
$link = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('webservice',$link) or die('Cannot select the DB');
if(isset($_POST['action']) && $_POST['action'] == 'login') {
$statusCode = array('statusCode'=>1, 'statusDescription'=>'Login Process - Fail');
$posts[] = array('status'=>$statusCode);
header('Content-type: application/json');
echo json_encode($posts);
/* disconnect from the db */
}
#mysql_close($link);
?>
Basically I know that it is due to the $_POST values not being set but I can't find what I need to put instead of the $_POST. I tried
json_decode($_POST), file_get_contents("php://input") and a number of other ways but I was shooting in the dark a bit.
Any help would be greatly appreciated.
Thanks, Steve
Thanks Michael for the help, that was a definite step forward I now have at least got a repsonse when I echo the post....even if it is null
updated CURL -
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
updated php on the page that the data is posted to -
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); //convert JSON into array
print_r(json_encode($input));
As I say at least I see a response now wheras prior it was returning a blank page
You have empty $_POST. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.
You need something like that:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Also you have wrong code for testing JSON-communication...
CURLOPT_POSTFIELDS tells curl to encode your parameters as application/x-www-form-urlencoded. You need JSON-string here.
UPDATE
Your php code for test page should be like that:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
Also on your web-service page you should remove one of the lines header('Content-type: application/json');. It must be called only once.
Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.
$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");
getUserLocation($ip_srv);
Function:
function getUserLocation($services) {
$ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout
for ($i = 0; $i < count($services); $i++) {
// Configuring curl options
$options = array (
CURLOPT_RETURNTRANSFER => true, // return web page
//CURLOPT_HEADER => false, // don't return headers
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
CURLOPT_TIMEOUT => 5, // timeout on response
CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
);
// Initializing curl
$ch = curl_init($services[$i]);
curl_setopt_array ( $ch, $options );
$content = curl_exec ( $ch );
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
//echo 'service: ' . $services[$i] . '</br>';
//echo 'err: '.$err.'</br>';
//echo 'errmsg: '.$errmsg.'</br>';
//echo 'httpCode: '.$httpCode.'</br>';
//print_r($header);
//print_r(json_decode($content, true));
if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {
return json_decode($content, true);
}
}
}
you can put your json in a parameter and send it instead of put only your json in header:
$post_string= 'json_param=' . json_encode($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
//execute post
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
on the service side you can get your json string as a parameter:
$json_string = $_POST['json_param'];
$obj = json_decode($json_string);
then you can use your converted data as object.
I have many inputs on my page like
user name
URL
Des
keywords
bl bl
I need to get the meta tags from an URL the user enters in the URL input with JavaScript or Ajax
because I need not to reload the page.
I know I can use get_meta_tags('single_URL');, but i need to get the metas from the URL on submit :
Here's my code :
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$html = file_get_contents_curl("http://example.com/");
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description')
$description = $meta->getAttribute('content');
if($meta->getAttribute('name') == 'keywords')
$keywords = $meta->getAttribute('content');
}
echo "Title: $title". '<br/><br/>';
echo "Description: $description". '<br/><br/>';
echo "Keywords: $keywords";
I would call it as such :
$html = file_get_contents_curl("http://example.com/"); //<< I need to set the url with the user input without reloading the page
What you are looking for is called xhr, XMLHttpRequest or more commonly : AJAX.
Assuming you are using JQuery :
Client side :
<script>
function get_metas(){
url = $('#txt_url').val();
$('#result').load('your_script.php?url=' + encodeURIComponent(url));
}
</script>
<form id='search' method='post' onsubmit='get_metas();return false;'>
<input type='text' id='txt_url' name='url'/>
<input type='submit' value='OK'>
</form>
<div id='result'></div>
Server side :
...
$html = file_get_contents_curl($_GET['url']);
...
Be careful though as this can potentially turn your server into a proxy to do bad things.
I have a simple Christmas image editor website, and I need to save user's facebook profile picture in order to do it. It works, but takes way too long (between 15-30 seconds), and I have no idea why.
I use javascript to deal with the login stuff, and after that, I use user's id to get the profile picture. I believe the issue occurs after that:
Since this url is not the real path to the image, I have to redirect it first, and then save it. This is my PHP code:
<?php
//just getting the file from the URL
$file = explode('/',$_GET["var1"]);
//if it's from facebook, not uploaded
if( $file[1] != "uploads"){
$saveto = "uploads/".$file[3].".jpg";
$ch = curl_init(get_right_url("http:".$_GET["var1"]));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
function get_right_url($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
return curl_redir_exec($curl);
}
function curl_redir_exec($ch)
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
#list($header, $data) = #explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302)
{
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = #parse_url(trim(array_pop($matches)));
if (!$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (!$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!$url['host'])
$url['host'] = $last_url['host'];
if (!$url['path'])
$url['path'] = $last_url['path'];
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . (#$url['query']?'?'.$url['query']:'');
return $new_url;
} else {
$curl_loops=0;
return $data;
}
}
?>
I'm sure i'm doing something wrong, it shouldn't be this painful to upload a small image like this one. I'd be grateful for any help, thanks a lot.
fixed. got the "real link" for the image with facebook's API
https://developers.facebook.com/docs/reference/api/using-pictures/
curl was delaying it a lot...