0

I would like to find out how a PHP page calls another PHP page, which will return JSON data.

I am working with PHP (UsersView.php) files to display my contents of a website. However, I have separated the MySQL Queries in another PHP (Get_Users.php) file.

In the Get_Users.php, I will have a MySQL statement to query the database for data. It will then encode in JSON and be echo-ed out.

In the UsersView.php, I will call the Get_Users.php in order to retrieve the Users JSON data. The data will then be used to populate a "Users Table".

The thing is, I do not know how to call the "Get_Users.php" from the "UsersView.php" in order to get the data.

Part of UserView.php

$url =  "get_user.php?id=" . $id;
$json = file_get_contents($url);
$result = json_decode($json, true);

I am trying to call the file which is in the same directory, but this does not seem to work.

Whole of Get_Users.php

<?php
$connection = mysqli_connect("localhost", "root", "", "bluesky");

// Test if connection succeeded
if(mysqli_connect_errno()) {
    die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
        "<br>Please retry your last action. Please retry your last action. " .
        "<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}

$valid = true;

if (!isset($_GET['id'])) {
    $valid = false;
    $arr=array('success'=>0,'message'=>"No User ID!");
    echo json_encode($arr);
}

$id = $_GET['id'];

if($valid == true){
    $query = "SELECT * FROM user WHERE id = '$id'";
    $result = mysqli_query($connection, $query);
    if(mysqli_num_rows($result) == 1){
        $row = mysqli_fetch_assoc($result);
        $arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
        echo json_encode($arr);
    }else{
        $arr=array('success'=>0,'message'=>"Invalid User ID!");
        echo json_encode($arr);
    }
}

mysqli_close($connection);
?>
13
  • you'll need to "require_once" or "require" it Commented Oct 8, 2016 at 11:47
  • Why not create a function inside Get_Users.php that query the database and return the result as json? Then you could simply include the file and call the function from UserView.php. Another approach would be to make sure so allow_url_fopen is enabled in your php.ini and then grab contents from the file using file_get_contents('http://example.com/Get_Users.php', false, $content);. Notice that you need to create a context to actually send the id to your script. You could also achieve this by making an ajax GET request. Commented Oct 8, 2016 at 11:48
  • @user629283 do you mean to make a function and include the Get_User.php, so i can call the function to query? Commented Oct 8, 2016 at 11:52
  • You could also set the $_GET['id'] parameter before you include the script: $_GET['id'] = 3; include_once('Get_Users.php'); Commented Oct 8, 2016 at 11:52
  • @Cyclone Can I just open the file and execute the query? By context, you mean I can only use the absolute link right? Commented Oct 8, 2016 at 11:55

2 Answers 2

4

You have a couple of different ways to accomplish this:

  • You should be able to first set the actual id and then include the Get_Users.php file like this. Notice that you should not echo out the output from Get_Users.php, instead only return the encoded json data using return json_encode($arr);:

// set the id in $_GET super global
$_GET['id'] = 1;
// include the file and catch the response
$result = include_once('Get_Users.php');
  • You can also create a function that can be called from UserView.php:

// Get_Users.php
<?php
  function get_user($id) {
    // connect to and query database here
    // then return the result as json
    return json_encode($arr);
  }
?>

// In UserView.php you first include the above file and call the function
include_once('Get_Users.php');
$result = get_user(1);
  • You could also use file_get_contents(). Notice that you need to make sure so that allow_url_fopen is enabled in your php.ini file for this to work:

$result = file_get_contents('http://example.com/Get_Users.php?id=1');

To enable allow_url_fopen you need to open up your loaded configuration file and set allow_url_fopen=1 and finally restart your webserver.


  • You could also use curl to achieve the same result:

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Get_Users.php?id=1');
$result = curl_exec($ch);
curl_close($ch);

  • An ajax request could also be made to get the result. This example uses jQuery:

$(document).ready(function() {
  $.get({
    url: 'Get_Users.php',
    data: 'id=1',
    success: function(response) {
      // response contains your json encoded data
      // in this case you **must** use echo to transfer the data from `Get_Users.php`
    }
  });
});
Sign up to request clarification or add additional context in comments.

7 Comments

The first method worked, but the json will be printed on the screen (because of the "echo" in Get_User.php)
@Jeffrey - I added an explaination to how you solve this.
Thank you for all the possible solutions. its really helpful for me. The reason why I used "echo" is because I would want to use that same .php file for ajax. I thought i could also used it for php. seems like the only way is to use the "return" (using a function) instead. If not I will have to use an absolute path (with the files stored on a server).
regarding the ajax method, how can I use the json in php?
@Jeffrey - I'm not sure I understand the question? Like I said you need to actually echo out the response in case of an ajax request (which will send the output to the browser). A simple workaround in order to use the same function would be to simply add an second parameter ajax=1 and check if this parameter is set in the function. If ajax is equal to 1 then you use echo to output the encoded data, if its not then simply use return to deliver the result to the caller.
|
1

Change UsersView.php to like this

$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['CONTEXT_PREFIX'];
$url =  "get_users.php?id=" . $id;
$url = $actual_link.$url;
$json = file_get_contents($url);
$result = json_decode($json, true);

This will work fine.

2 Comments

Thank you Angel. I am not sure what the $_SERVER['CONTEXT_PREFIX'] does. but this does not solve the problem. All I get was only the "localhost" from $_SERVER['HTTP_HOST'], which makes the url to be "localhostgetusers.php?id=1"
$_SERVER['CONTEXT_PREFIX'] gets your alias name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.