1

Is this valid approach: I want to keep api key from being accessible via source code so I have been trying to keep it hidden with PHP and use Javascript to display data. (I prefer to use js syntax to display data) I've been able to display data successfully but when I look at the source code I can see the JSON response. Can anyone tell me if this is a valid approach and why not good idea to have json shown in source?

<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
$json = json_decode($data,true);
?>

I then access the response like so:

<script type="text/javascript">

    var data =  <?php echo json_encode($json) ?>;
    $('.in-theaters-soon').append('<p>' + data.movies[0].title + '</p>');

</script>

3 Answers 3

3

You can directly echo the values from PHP since you already have the response in $json. For example:

<div class="in-theaters-soon">
    <p><?php echo $json['movies'][0]['title']; ?></p>
</div>
2
  • Hi littleibex, I prefer to use javascript to display data as I more familiar with its syntax. Do you think the above approach is valid? and what do you think about the JSON being able to be viewed in the source code? Commented Jul 19, 2015 at 12:59
  • 1
    Your approach is valid because it gets the work done even though it's a very roundabout way of doing it. The fact that your JSON is being viewed in the source code does not cause any harm since you are anyways displaying it to the users in a pretty way (using HTML). Also, since it's only the JSON there's no way of backtracking as to how and where the JSON came from.
    – littleibex
    Commented Jul 19, 2015 at 13:02
1

Always make some validation of the printed data.

<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
if (is_array($data) && ! empty($data)) {
    /**
     * Do something.
    /**/
}
0

You could do something like this if you have the php in a separate file.

Your php file.

<?php
// create a token check to make sure it is being called.
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
echo json_encode($data);
?>

Then query your php file something like this sending a token or something similar.

$.ajax({
    url: url,
    type: 'POST',
    data: {token:token},
    success: function(data){
        var response = $.parseJSON(data);
        for(var x = 0; x < response.length; x++){
            $('.in-theaters-soon').append('<p>' + response[x].title + '</p>');
        }
    },
    cache: false,
    contentType: false,
    processData: false
}); 

Hope this helps.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.