How to run simple Php API?

502

I used Php Slim Framework for my API. I install the Slim Framework to my web root directory on my server and copy the index.php file I coded.

Index.php:

<?php
require 'vendor/autoload.php';

$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->get('/user/:id', 'getUser');
$app->run();

function getConnection() {
$dbhost="localhost";
$dbuser="";
$dbpass="";
$dbname="";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}

function getUsers() {
$sql = "select * FROM manga";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
}
catch(PDOException $e) {
echo json_encode($e->getMessage());
}
}
?>

I am getting 500 (Internal Server Error).

Edit: I changed "$app = new Slim();" to the "$app = new \Slim\Slim();" then receive the below error.

I am using EasyEngine(Nginx).

enter image description here

Edit-2:Now 500 Internal gone but another error showing.

XMLHttpRequest cannot load http://api.mangayurdu.com/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://deneme.mangayurdu.com' is therefore not allowed access.

Here is my code that getting JSON data:

 .factory('MY', function($http){
  var factory = {};
  var url = 'http://api.mangayurdu.com/users?callback=JSON_CALLBACK';
  factory.isimler = $http.get(url);
  return factory;
  })
162

Answer

Solution:

From the posted code it looks like Slim can't find a function calledgetUser.getUsers() is defined in your code, but nogetUser() function.

132

Answer

Solution:

try putting this in the start of your PHP page

<?php header('Access-Control-Allow-Origin: *');?>

People are also looking for solutions to the problem: php - Class not recognized - laravel Eloquent Model

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.