I just got started with Slim. My application for the moment is something like this:
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim([
'debug' => true
]);
var_dump($app->request());
$app->get('/:name', function ($name) {
echo "Hello, $name";
});
$app->get('/', function () {
echo 'hello world';
});
$app->run();
I am running it on localhost using PHP built in web server. For every request I try in the browser (or Postman, or CURL), what I get is always "hello world", as if the first route is not considered. Moreover, if I remove the second route, I always get a 404.
Am I forgetting something?
For debugging purposes, which HTTP header is used by SLIM to determine the route?
You can't remove the second route $app->get('/') as it is the Home default route and it is quite normal to get a 404 because $app->get('/:name', function ($name) {}) is expecting a callback function's argument 'name' that is missing.
Are you trying the following:
http://localhost/mysite/ --- Outputs Hello World
http://localhost/mysite/marcosh --- Outputs a 404 ??
If this is the case then as a77icus5 suggested we may need to look into your htacess file and what is the project directory structure...
I have a fresh Slim Skeleton install and I thought I'd share my configuration with you...
My Web project directory is as follow :
Webroot
-htaccess
- public
-- htaccess
-- assets
--- js
--- css
- templates
- app
- vendor
-- Slim
-- Twig
In the first .htaccess located in the project root directory I added :
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
Here public matches the name of the app public folder
Then in the .htaccess located in the public folder I added :
<IfModule mod_php5.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>
Then in SLIM -> Environment.php (line 142 - Virtual Path ) and try to edit as follow :
// Virtual path
// $env['PATH_INFO'] = substr_replace($requestUri, '', 0, strlen($physicalPath)); // <-- Remove physical path
$env['PATH_INFO'] = str_replace(str_replace('/public', "", dirname($_SERVER['PHP_SELF'])), '', "/".$requestUri); // remove public from URI
$env['PATH_INFO'] = str_replace('?' . $queryString, '', $env['PATH_INFO']); // <-- Remove query string
$env['PATH_INFO'] = '/' . ltrim($env['PATH_INFO'], '/'); // <-- Ensure leading slash
Eventually, I found out that the problem was given by a wrong document root.
I was launching the application from the main folder of my project using php -S localhost:8080 public/index.php and this caused the PATH_INFO header of the HTTP request not to be compiled.
Changing directory to ./public and launching the app using php -S localhost:8080 index.php solved the problem
You need some kind of url rewriting for Slim to work. Since you are using internal PHP webserver you cannot use mod_rewrite. Instead create route.php file to same folder as index.php with following code.
<?php
# Used only for running the app with internal PHP webserver
# php -S localhost:8080 route.php
if (file_exists(__DIR__ . "/" . $_SERVER["REQUEST_URI"])) {
return false;
} else {
include_once "index.php";
}
Then run it with php -S localhost:8080 route.php. Everything works now as expected.
$ curl --include http://localhost:8080/foo
HTTP/1.1 200 OK
Host: localhost:8080
Connection: close
X-Powered-By: PHP/5.6.2
Content-type: text/html;charset=UTF-8
Hello, foo
Related
I am creating a mobile application(flutter) that works with api on Laravel. The api should work but there are problems. I'm trying to figure it out, although I don't have previous experience with Laravel (I have experience with PHP). so on server Cpanel. when i try to call the api i get an error
404 Not Found
body:
The requested URL was not found on this server.
Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request
This is a fairly common problem, the points I checked are the following points.
the api is in the public_html folder, some folders inside:
app
routes
bootstrap
checked file public_html/.htaccess
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php74” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php74 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
I changed it to:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
executed the following commands
php artisan route:clear
php artisan route:cache
after that i execute the command
php artisan route:list
result:
I try the following options for the url:
https://appdomain.com/api/v1/login
https://appdomain.com/api/v1/Check-login
https://appdomain.com/api/v1/user-login
https://appdomain.com/api/login
https://appdomain.com/api/Check-login
https://appdomain.com/api/user-login
https://appdomain.com/login
https://appdomain.com/Check-login
https://appdomain.com/user-login
but each of these urls return a 404 error.
Laravel - version 5.5.50
part of api.php
Route::group(['prefix' => 'v1'], function () {
Route::post('/user-login',['as' => 'login','uses' =>
'api\v1\UserController#user_login']);
});
7. when I added file public_htm/index.php - any request to api returns that file
Which url is correct?
What else can I check?
How can this be fixed?
Any advice - I will be very grateful.
Method 1:
Change Document Root to public_html/public and upload the source code to public_html.
Method 2:
Upload the source code except public folder to the parent folder of public_html folder. And upload the files in public folder to public_html folder.
Add the following code to public_html/index.php:
$app->bind('path.public', function() {
return __DIR__;
});
Place .htaccess file into root directory of your project . public_html/.htaccess
The first thing you should do is to verify if your request actually hits your Laravel Application. There are number of ways you can do this, like adding additional testing routes in web.php or api.php
Addtionally, you may install clockwork and capture all the request, so you can also easily see if your request actually hits the laravel app.
If it hits your Laravel application, turn on the debug mode in your env file and put the application in development mode, then try checking the laravel logs for any error.
If your request is not hitting the laravel application, then its something related to your server configuration or laravel installation configuration.
Normally, the root folder for laravel application is in laravel-root-directory/public/ which should be the root folder when configuring the domain, but I've seen people where they move the root folder to actual laravel app root and not inside public folder
I have a WordPress website that I have extended with the Slim Framework to provide some custom API. Everything works fine in local, but when I move the application on a live server (SiteGround), if I try to call any of the custom endpoints I get a 404 error Slim\Exception\HttpNotFoundExceptio.
This is my folder structure
In Local the root folder is C:\xampp\htdocs\example\
In remote the root folder is /home/customer/www/example.com/public_html/
api\
vendor\
public\
.htaccess
index.php
routes\
v1\
autocomplete.php
.htaccess
composer.json
composer.lock
wp-admin
wp-content
wp-includes
... all others WordPress files
In local I was able to call the endpoint http://localhost/example/api/v1/autocomplete, while on remote if I call https://www.example.com/api/v1/autocomplete I get a 404 not found error
code: 404
file: "/home/customer/www/example.com/public_html/api/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php"
line: 91
message: "Not found."
type: "Slim\Exception\HttpNotFoundException"
As per Slim documentation the Apache mod_rewrite is enabled by the default WordPress .htaccess and AllowOverride All is setted by default on all SiteGround server.
Here is the content of the important Slim files
root\api\.htaccess
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
root\api\public\.htaccess
# Redirect to front controller
RewriteEngine On
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
root\api\public\index.php
<?php
use Selective\BasePath\BasePathMiddleware;
use Slim\Factory\AppFactory;
require_once __DIR__ . "/../vendor/autoload.php";
$app = AppFactory::create();
// Add Slim routing middleware
$app->addRoutingMiddleware();
// Set the base path to run the app in a subdirectory.
// This path is used in urlFor().
$app->add(new BasePathMiddleware($app));
$app->addErrorMiddleware(true, true, true);
// PUT ALL ROUTES HERE
require_once "../routes/v1/autocomplete.php";
// Run app
$app->run();
root\api\routes\v1\autocomplete.php
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
$app->get("/v1/autocomplete", function (Request $request, Response $response) {
$params = $request->getQueryParams();
$payload = array(
"status" => "error",
"message" => "missing param 'user_input'",
);
if (isset($params["user_input"])) {
$payload = getSuggestions($params);
}
$response->getBody()->write(json_encode($payload));
return $response
->withHeader("Content-Type", "application/json");
});
Thanks in advance
If you run your Slim 4 app in a sub-directory of the webservers DocumentRoot, you need to set the basePath.
Maybe in your case:
$app->setBasePath('/api');
Server configuration:
Ubuntu 18.04
Apache 2.4.29
PostgreSQL 10.6
PHP 7.3 (I was using 7.2 but the system has decided to update it for me, I will rollback once I have resolved the current bugs)
Composer
Slim/Slim 3.0
Slim/php-view
I have been building an API with the Slim PHP framework, using gothinkster's repository as a starting point. The code has been heavily adapted, though all code relating to rendering templates remains intact. When I access the website's homepage, the index.phtml file is rendered properly, but following any hyperlinks from th homepage results in a 404 error, although the .phtml files all reside within the same directory.
The following are excerpts of my code, excluding irrelevant configuration. Although I have only displayed one endpoint, the API defines 10 endpoints, all of which are get requests with no arguments, using .phtml files which reside within the same folder.
Settings, routes and dependencies are called using require statements within the index.php file.
/[api_root]/public/index.php:
if (PHP_SAPI == 'cli-server') {
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) {
return false;
}
}
require __DIR__ . '/../vendor/autoload.php';
session_start();
// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';
$app = new \Slim\App($settings);
// Set up dependencies
require __DIR__ . '/../src/dependencies.php';
// Register middleware
require __DIR__ . '/../src/middleware.php';
// Register routes
require __DIR__ . '/../src/routes.php';
// Run app
$app->run();
The settings file returns an array containing a reference to the template path.
[api_root]/src/settings.php:
'settings' => [
'renderer' => [
'template_path' => __DIR__ . '/../templates/',
]
]
Templates are assigned to the renderer within the dependencies.php file.
[api_root]/src/dependencies.php:
$container = $app->getContainer();
// view renderer
$container['renderer'] = function ($c) {
$settings = $c->get('settings')['renderer'];
return new Slim\Views\PhpRenderer($settings['template_path']);
};
.phtml templates are rendered within get requests.
[api_root]/src/routes.php
$app->get('/getting-started',
function (Request $request, Response $response) {
return $this->renderer->render($response, 'getting-started.phtml');
});
The getting-started.phtml file is located within [api_root]/templates/.
The root / is defined and successfully returns the index.phtml file located within the templates directory, but when I attempt to follow any links from the homepage, I recieve a 404 error. The anchor which points to the getting-started page successfully redirects to mywebsiteurl.com/getting-started, but the template file is not rendered and the browser responds with a 404 error.
All application files are stored privately on the server. I have created symlinks from the contents of the [api_root]/public folder to my website's public_html folder.
There is obviously something wrong with my definition of the path to the /templates directory, but I can't work out how to rectify it.
EDIT:
When I created the symlinks to the public_html folder, I had forgotten to include hidden files (namely, the .htaccess file). I have since created this symlink, though now when I attempt to access the homepage I see the default apache2 page which is displayed after apache is installed. I will note here that the website resides on a paid server. Apache is configured to use virtual hosts and I have edited the hosts file on my local machine properly. As stated, without an .htaccess file I can view the homepage, but other routes are not being found. When the .htaccess file exists in the public_html folder, I cannot view the homepage or any other routes.
.htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteCond %{HTTP_HOST} ^(www\.)?mywebsiteurl.com
RewriteRule ^(.*) - [E=BASE:%1]
# If the above doesn't work you might need to set the `RewriteBase` directive manually, it should be the
# absolute physical path to the directory that contains this htaccess file.
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>
The issue here was that I had not enabled mod_rewrite on the server, so my .htaccess file was not being read.
I've created a simple Slim microframework project using PHPStorm 8 on Windows 8.1 with WAMP Server installed. All WAMP Server settings are set by default.
I created a new project called pr1
I used 'Init Composer...' and then added some dependencies like slim/slim, slim/views, twig/twig.
Then I tried to create a simple application just like a given example on main Slim page:
I've created file called index.php in my project folder
index.php
code:
require 'app.php';
Then I've created file app.php
code
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/:name', function ($name) {
echo "Hello, $name";
});
$app->run();
After this I tried to run my project in Chrome and there an error 404 occured.
Then I tried to pass my name through url: http://localhost:63342/pr1/wade and there was PHPStorm error.
After this steps I've tried to close PHPStorm and my project in browser:
and it seemed like there's a typical Slim 404 error,but when I tried to pass my name through url again it gave me this error:
you need to include index.php for example http://localhost/pr1/index.php/test
to get rid of index.php use .htaccess or something equal based on your webserver
All it was because Apachi doesn't know what to do with all browser requests. For this reason I've created a simple .htaccess file:
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]
After this I needed to use rewrite_module in my WAMP settings.
It perfectly works with project when I open it in browser through the explorer.
And after this I set up my server like this:
And that allows me to preview all my changes through PHPStorm
I am trying to use the php fat free framework (aka F3), to quickly build a web application.
In theory (from reading the documentation), it should be a doddle (i.e. easy), however, I have been stuck on a single problem for days, and judging from similar questions here on stackoverflow, it seems I'm not the only one struggling with this issue.
Here are the salient facts:
I am using wamp server to run F3.
My F3 project resides under /location-to-wamp-folder/www/fatfree-master
I have setup a virtual host for Apache under wamp, so http://fatfree-master runs index.php
This is where the trouble begins. When I navigate to http/fatfree-master, I get the error which is the title of this question; namely:
Not Found
HTTP 404 (GET /) C:/wamp/www/fatfree-master/index.php:111 Base->run()
My index.php looks like this:
<?php // <- surprisingly, I had to add this line to the index.php example provided by F3, was this an oversight or a deliberate design feature?
$f3=require('lib/base.php');
$f3->set('DEBUG',3);
$f3->set('UI','ui/');
....
// custom PHP code defining routes etc ...
....
$f3->run(); // barfs here
Now, I would be the first to admit, that I do not understand the arcane syntax of Apache rewrites, so I have left my .htaccess file as it was (when I downloaded F3).
Here are the contents of my .htaccess (the default file provided by F3):
# Enable rewrite engine and route requests to framework
RewriteEngine On
# Some servers require you to specify the `RewriteBase` directive
# In such cases, it should be the path (relative to the document root)
# containing this .htaccess file
#
# RewriteBase /
RewriteRule ^(tmp)\/|\.ini$ - [R=404]
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L,QSA]
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
Can anyone explain to me, why I am getting the 404 error, and also how to fix it?
[[Additional Notes]]
I have two routes in my (edited) index.php file. My index.php looks like this now:
<?php
$f3=require('lib/base.php');
$f3->set('AUTOLOAD','app/controllers/');
$f3->set('DEBUG',3);
$f3->set('UI','ui/');
/* Tools */
$f3->route('GET #tools_calculator_dates: /tools/calculator/dates', 'Beer->list');
// Default route
$f3->route('GET /',
function() {
echo 'Hello, world!';
}
);
$f3->run();
When I access / in my browser, I get "Hello, world!" (as expected)
When I access /tools/calculator/dates in the browser, I get the following error:
Not Found
HTTP 404 (GET /tools/calculator/dates)
• C:/wamp/www/fatfree-master/index.php:119 Base->run()
Now, I have a class here: /path/to/wamp/www/fatfree-master/app/controllers/beer.php
The contents of the class are:
<?php_
class Beer
{
function list() {
echo "Beer::list() called!";
}
}
Why I am getting the 404 error?.
The error you're getting is not from Apache, it's from F3.
If you don't specify a route GET /, F3 will throw a 404.
The 404 error could be caused by one of the following reasons:
the route you're calling hasn't been defined
the class or method against which the route has been defined cannot be found
you're running the web app in a subfolder and for some reason, RewriteBase needs to be enabled
Concerning the point #1, see the documentation for details about route declaration.
Concerning the point #2, check out this answer if you're having trouble setting the framework's autoloader (AUTOLOAD variable).
Regarding the point #3: RewriteBase is usually optional when running in a subfolder, but in specific cases (for ex. when mod_userdir is enabled), it needs to be explicitly set.
So in your case, you could try to add the following directive in your .htaccess file, just after RewriteEngine On:
RewriteBase /fatfree-master/