I have an index.php file in /api folder on my server. And I'm beginning with Slim and I'm trying to make a REST api.
So in my index.php I've got this:
$app->get('/', function() use ($db) {
echo "Get";
});
$app->post('/', function() use ($db) {
echo "Post";
});
$app->get('/test', function() use ($db) {
echo "Test";
});
And in my .htaccess file, as it was downloaded:
RewriteEngine On
# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
If I make a GET call to ../api/ I've got "Get", the post call works fine too, but if I make .../api/test call I've got a 500 Internal Server error.
What am I doing wrong?
Thank you!
Related
I have this code using the slim framework and php with apache2 on linux:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../../vendor/autoload.php';
$app = new \Slim\App;
#doesn't work results in URl not found in browser
$app->get('/hello','sayhi');
#works, when i just type in 'localhost/' into my webbrowser
$app->get('/',function()
{
return 'testing';
});
$app->run();
#functions
function sayhi()
{
echo 'hello world again';
}
.htaccess (same directory as my index.php file)
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
000-default.conf has the documentroot set to the directory of where my php file and .htaccess file.
When i type in 'localhost/' into my web browser the anonymous function is executed. As that's what it will do if the server recieves '/'
However when i type in 'localhost/hello' it results in URL not found, when it should execute the 'sayhi' function when the server receives this type of url.
Why is it doing this? is there something wrong in my code, as i don't understand how to go about sorting this.
I also tried setting the option to the directory of my php file
AllowOverride All
However this results in a 500 Internal error, when i have this option set. I tried following this guide: 500 internal error guide to no avail.
I have no idea how to sort this, help?
You can tell Apache to redirect all routes to index. Try something like in your vhost or in a .htaccess file :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [QSA, L]
I think you need to configure apache so that all requests would go into index.php in which your code are located. It seems that when you request localhost/hello your web server tries to find file hello.
I have a very simple Slim app that works fine on my Ubuntu machine but I get an error 500 when I deploy it to a Hostgator shared account using a subdomain.
I suspect the problem lies in my .htaccess file.
The structure of my files is:
project/
├──api/
│ ├── .htaccess
│ ├── services.php
├──src/
├──vendor/
My Slim app (services.php):
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require_once '../src/vendor/autoload.php';
$c = new \Slim\Container();
$c['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['response']
->withStatus(404)
->withHeader('Content-Type', 'text/html')
->write('Invalid endpoint');
};
};
$app = new \Slim\App($c);
$app->post('/myEndpoint', function (Request $request, Response $response, array $args) {
if($request->getHeader("key") != null && $request->getHeader("key")[0] == "123456789="){
$reqdata = $request->getParsedBody();
$data = $reqdata['data'];
return json_encode('{"data":'.$data.',"response":"OK","errorcode":"0"}');
} else {
return '{"data":"","response":"Access denied","errorcode":"9999"}';
}
});
$app->run();
My .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . services.php [QSA,L]
</IfModule>
# Use PHP71 as default
AddHandler application/x-httpd-php71 .php
<IfModule mod_suphp.c>
suPHP_ConfigPath /opt/php71/lib
</IfModule>
I created a subdomain (api.mydomain.com) with project/api/ as document root.
When I make a POST request in my local installation to
127.0.0.1/api/services.php/myEndpoint
works as expected and returns the data. However, when I make the same request to my Hostgator subdomain:
api.mydomain.com/services.php/myEndpoint
I get the error 500.
Note that if I add a simple test.php file to my api/ directory that only prints something, e.g.
<?php
echo "OK"
?>
and I go to api.mydomain.com/test.php, it works fine and prints the string.
What do I need to change or add in my .htaccess for my slim app to work?
I solved it by doing two things:
I moved my project folder to public_html, created again the subdomain and pointed it to the project directory.
I updated my .htaccess file IfModule mod_rewrite.c section. It now looks like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ services.php [QSA,L]
</IfModule>
The difference with the previous one is I added this line:
RewriteBase /
And this one:
RewriteRule . services.php [QSA,L]
updated to this:
RewriteRule ^ services.php [QSA,L]
I got the .htaccess fixes here:
https://discourse.slimframework.com/t/deploy-slim-project-to-hostgator-using-subdomain/3187/7
I have to create an API in PHP, which I have never done before. I have a index.php in my root folder which contains a form. A button click activates an AJAX Request to read all entries and a form can be filled out to send data. I will also have DELETE and update.
ajaxcall.js
// GET to retrieve
var req;
req=new XMLHttpRequest();
req.open("GET", 'src/api/v1/posts',true);
req.send();
//post with ajax
$.ajax({
type:"POST",
url: "src/api/v1/posts",
data: test,
ContentType:"application/json",
success:function(){
alert('successfully posted');
},
error:function(){
alert('Could not be posted');
}
});
I have a folder src/api/v1 in there I want the endpoint file api.php which handles the different requests. I now need all the AJAX calls to be resend to api.php which sits inside that v1 folder. I created an .htaccess which is stored in also stored in src/api/v1. I added the following:
.htaccess
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule src/api/v1/(.*)$ src/api/v1/api.php?request=$1 [QSA,NC,L]
Unfortunately I get a 404 not found, it just does not seem to re-write the URL to the api.php so it is looking for /posts which does not exists. What am I doing wrong?
Actually you should store the .htaccess on the root directory, otherwise Apache will not know that there's an .htaccess under /src/api/v1, so apache will look for the directory src/api/v1/posts and as is it's not found a 404 error will be returned.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule src/api/v1/(.*)$ /src/api/v1/api.php?request=$1 [QSA,NC,L]
</IfModule>
I have the following httpd structure:
c:/
xampp/
htdocs/
mysite/
bower_components/
app/
index.html
app.js
views/
api/
index.php
.htaccess
Inside the app folder I have my application code: HTMLs, JSs, CSSs, etc. In other words my frontend.
Inside the api folder I have my PHP REST api: index.php. In other words my backend.
As said I am using AngularJS and would like to enable html5Mode, so I can have a cleaner URL.
I manage to put just the frontend to work with the following configuration in Apache:
NameVirtualHost *:8081
<VirtualHost *:8081>
ServerName localhost:8081
DocumentRoot "C:/xampp/htdocs/mysite/app"
Alias "/bower_components" "C:/xampp/htdocs/mysite/bower_components"
<Directory "C:/xampp/htdocs/mysite/app">
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
With the configuration above I am able to run my frontend like a charm.
http://localhost:8081 takes me to index.html and all my states in my $stateProvider are also resolved.
But my API calls fail and I don't know what to do.
I have the following REST service in my index.php:
require 'vendor/autoload.php';
// Create Router instance
$router = new \Bramus\Router\Router();
$router->get('/cart/items', function() {
echo '{"items":[ {"name":"item1"}, {"name":"item2"} ]}';
});
// Run the Router
$router->run();
When I call from my frontend:
$http({
url: '/api/cart/items',
method: 'GET'
}).then(function (response) {
// do stuff...
}, function (error) {
alert(error.data);
});
The call is falling in the rewrite rule to index.html. All my API calls are responding the index.html.
In my api folder I have the following .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
Options -Indexes
I have already tried to put an Alias in the Apache configuration for the api folder but the result was the same.
I've even tried to point my DocumentRoot to C:/xampp/htdocs/mysite. That way my calls to the API are resolved but when I access http://localhost:8081 I get the list of files and folders from mysite.
It seems so close and yet so far. Hope you guys can enlight me.
I'm trying to setup Slim for me application i've got issue that route with parameters not working.
This is my index.php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
// GET route
$app->get('/', function () {
print "hello";
});
$app->get('/books/:id', function ($id) {
print $id;
});
$app->run();
This is the .htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
Request to / works fine, but if I pass /books/1 it returns [404] not found
Man your mod_rewrite is not enable in apache.For enable mod_rewrite follow this.Reference http://www.kingpabel.com/apache-mod-rewrite/
<Directory /var/www/html>
AllowOverride All
</Directory>
//enable mod rewrite
a2enmod rewrite
//restart apache
service apache2 restart