Home > database >  Get json data from dynamic url (based on form input as url suffix) and show data in php
Get json data from dynamic url (based on form input as url suffix) and show data in php

Time:02-22

I need to show json data from dynamic url in my website. When visitor make input which is his loyalty card number that number is added to url as sufix. That url is url that contains his detals related to loyalty programme (points he earned so far etc.).

My code:

<form action="" method="get">
<input type="text" id="unos" name="card" value = ""><br><br>
<input type="submit" name="submit" value="Provjeri bodove">
</form> 
<?php
$card = $_GET["card"];
$url='http://81.93.93.78:8085/cardcheck/testAlsLoyalty.php?card= <?php echo $card; ?> ';
$json = file_get_contents($url);
$jo = json_decode($json);
echo $jo->user;
echo $jo->card;
echo $jo->rezultat;
echo $jo->bodova;
echo $jo->raspolozivo;

?>

What I got so far is that this code add input as suffix to url of my website, and if I put url of json website as form action value visitor is taken to json website where he can see data. But I want to load data from that url at my website (html or php) after he type card number.

Thank you in advance

CodePudding user response:

You don't use <?php echo in strings. Use string concatatenation.

$url='http://81.93.93.78:8085/cardcheck/testAlsLoyalty.php?card=' . $card;

<?php echo ... ?> is used when you've exited PHP code with ?>, and want to insert a PHP expression in the output.

CodePudding user response:

You should check that the variable you're trying to use later on is actually set and also before you append the card number to the url, use rawurlencode() before submitting, otherwise that could break the url (when someone uses unallowed URL characters - i.e. spaces).

<form action="" method="get">
<input type="text" id="unos" name="card" value = ""><br><br>
<input type="submit" name="submit" value="Provjeri bodove">
</form> 
<?php

if(isset($_GET["card"])){
    $card = $_GET["card"];
    $url='http://SERVER_URL_HERE/cardcheck/testAlsLoyalty.php?card=' . rawurlencode($card);
    $json = file_get_contents($url);
    $jo = json_decode($json);
    echo $jo->user;
    echo $jo->card;
    echo $jo->rezultat;
    echo $jo->bodova;
    echo $jo->raspolozivo;
}else{
    //Notify user here that no card number has been submitted
}

?>

Note that I removed the IP address and port from the URL and replaced with SERVER_URL_HERE. You should never ever publish your public IP address (or domain) as it just opens doors for attackers, especially when you directly give the endpoint...

  • Related