Slim PHP custom http response pages - php

Ok I have read the docs on Slim PHP and read quite a few tutorials, and have an application nicely under way. However I am trying to get to grips with things such as customizing the HTTP response codes. I have managed to get the following :
$app->notfound('template.file', array(
'data' => 'passed'
));
This seems to work nicely (as it should as it is a Method directly within Slim), however not I am trying to control things such as the 403 response. I have controlled the not permitted using Apache as I usually would do, however I am wondering if there is a way with Slim that I can serve a custom Not Permitted page? Or because I have blocked it at the Apache level, will Slim not even notice?
I did read that I can manually halt certain routes? Is this the way I should do it? For example, I don't want people to access my JS directory so :
$app->group('/js', function () use($app) {
$app->get('/', functin () use($app) {
$app->halt(403, "You shall not pass!");
});
});
My reason for grouping this would be because I want access to my actual scripts, just not directory browsing.
Has anybody come across this before? What would you suggest? Or am I totally over thinking something simple....

You could simply redirect user to another route where you print your custom template. Example:
require 'vendor/autoload.php';
session_start();
$app = new \Slim\Slim();
$app->group('/js', function () use($app) {
$app->get('/', function () use($app) {
$app->flash('httpStatusCode', '403');
$app->redirectTo('NotAuthorized');
});
});
$app->get('/notAuthorized', function () use($app) {
echo 'You\'re here because you\'re Balrog!';
echo 'Http Status Code: ' . $_SESSION['slim.flash']['httpStatusCode'];
})->name('NotAuthorized');
$app->run();

Related

Slim 4 internal redirect, infinity loop

After upgrading to Slim v4 I'm trying to replace my simple $app->subRequest call with $app->handle as specified in the changelog. However there are no details on how to do this in either the changelog or upgrade guide and my best effort to fix it ends up creating an infinite loop:
$app->get("/foo", function (Request $req) use ($app) {
$uri = $req->getUri();
$newUri = $uri->withPath("/bar");
$barReq = $req->withUri($newUri);
// Here we get stuck in endless loop instead of ending up in the /bar route handler below
$app->handle($barReq);
});
$app->get("/bar", function (Request $req) use ($app) {
echo 'bar!';
die;
});
It's like even though $barReq is a new request object with a completely new uri (and path) the router does not resolve which route handler that should handle it, instead it's just handled by the same one again.
My previous simplified (v3) code looked like and worked fine to get the result of the /bar route when calling /foo:
$app->get("/foo", function (Request $req) use ($app) {
$app->subRequest('GET', '/bar');
});
I'm probably missing some central concept on how Slim 4 handles requests and routes internally and would appreciate some help!
Edit: Should perhaps add that what I mean with internal redirect is that client should not be aware that a redirect has been made. I.e. any regular redirect function returning something to client is not applicable here.
As #remy stated, use the ServerRequestFactory implementing ServerRequestFactoryInterface.
For slim/psr7 it is: Slim\Psr7\Factory\ServerRequestFactory
A silent redirect to another route is then as simple as:
use Slim\Psr7\Factory\ServerRequestFactory;
...
...
$app->get('/foo', function ($request, $response, $args)
{
global $app;
return $app
->handle((new ServerRequestFactory())->createServerRequest('GET', '/bar'));
});

Axios call to laravel backend in nuxt.js

I am trying to get a laravel-nuxt project running. I am stuck with creating route calls to my laravel backend using axios async call to serve up data to my nuxt frontend before loading the page.
I am constantly getting getting a 404 with my current laravel-nuxt setup even though I have the route defined in api.php.
I am using this as a template for the project and I have not changed anything in that template yet:
https://github.com/cretueusebiu/laravel-nuxt
So my frontend call is this here:
async asyncData ({ $axios }) {
if (process.server) {
return $axios.$get('/api/data')
.then((res) => {
this.data = res.data;
})
}
}
And my backend route is defined as follows in api.php:
Route::get('/data', 'HomeController#index');
It always gives me a 404, is there something missing that I should be aware of?
According to the Readme in the Github project you have mentioned, you have to add your routes manually to
client/router.js
Read this line under Notes and follow the structure well you'll be able to avoid this.
This project uses router-module, so you have to add the routes
manually in client/router.js.
hope this helps.

PHP routing a page using the Slim Framework

I haven't found many questions and answers relating to this so far, so thought I would ask the question as it will greatly help me out as a beginner learning PHP and the Slim framework. It's pretty straightforward (i think).
So, I want to route my home page to another page called about.php. I'm using the Slim/Slim framework which is installed in my vendor folder. And I have an index.php file with the following code:
<?php
require '/vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/', function() use($app){
$app->render('about.php');
});
$app->run();
?>
I also have an about.php file, which does exist.
This is what's currently in my composer.json file:
"require": {
"monolog/monolog": "^1.22",
"slim/slim": "^3.7",
"twig/twig": "^1.32",
"slim/views": "^0.1.3"
}
When I run MAMP (set-up to access the project I am working on) to see the page, it's blank. Can anyone help me understand what I'm doing wrong?
I've then run this (removing the leading '/' from the require statement, and adding a line to display errors), and it displayed a 500 error:
<?php
ini_set('display_errors', 1);
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$view = $app->view();
$view->parserOptions = array(
'debug' => true
$app->get('/', function() use($app){
$app->render('about.php');
});
$app->run();
?>
I'm unclear if you want about.php to be separate from your Slim application or not.
i.e. when someone goes to http://example.com/ do you want the browser's URL to change to http://example.com/about.php where about.php is a completely independent PHP file in the same directory as your index.php?
If you do then you need to redirect:
$app->get('/', function ($request, $response) {
return $response->withRedirect('/about.php');
});
More usually, Slim is used to route to and display all pages in your application and in this situation, you wouldn't see the .php in the URL. This is because our app always runs index.php regardless of the actual URL in the the browser's address bar.
In this situation, you would probably still redirect, but without the .php:
$app->get('/', function ($request, $response) {
return $response->withRedirect('/about');
});
You would also need a handler for /about otherwise Slim won't know what to do:
$app->get('/about', function ($request, $response) {
return $response->write("This is my about page");
});
We don't actually tend to write the HTML directly in our handler though. We use a renderer. There's two in the Slim project: PhpView and TwigView. The Skeleton application shows how the PhpView version works. You may also find the tutorial in the documentation useful.
Finally, if you see a 500, then you have a PHP error somewhere. The easiest way to find this is to ensure that the php.ini setting error_reporting is set to E_ALL and that display_errors is set to On.
As you've already discovered, Slim 3's main class is called App. You can also enable detailed error displays within Slim using:
$app = new Slim\App(['settings' => ['displayErrorDetails' => true]]);
Again, usually we have a separate settings.php file containing this configuration information as shown in the skeleton application.

File extensions in Slim routes

Why does Slim 404 when I try to add an extension to the route?
<?php
require_once 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/test', function () {
echo 'route 1';
});
$app->get('/test.html', function () {
echo 'route 2';
});
$app->run();
http://localhost:8080/test works
http://localhost:8080/test.html throws a 404
I assume you are running the example using internal PHP webserver. Built-in server will consider request as a static file request if there is a dot in the SCRIPT_NAME. It is considered a feature and not a bug. See PHP bug #61286 for more info.
Your code should work fine with Apache or other webservers, assuming rewrite rules are set up correctly.

Route::get('(:any)',function() not working properly in laravel 4

The program is a URL shortener that I am just trying out from some tutorial ( for Laravel 3 but i am using laravel 4) and it is supposed to give me the "some URL" as output when I click on the shortened URL.
<?php
Route::get('/', function()
{
return View::make ('home.index');
});
Route::post('/',function(){
$url = Input::get('url');
// If the url is already in the table, return it
$record=Url::whereurl($url)->first();
if ($record) {
//then return it
return View::make('home.result')
->with('shortened', $record->shortened);
}
});
Route::any('{shortened}',function($shortened)
{ echo "Everything is ok with: ".$shortened; })
->where('shortened', '.*');
Rather it is going to a error page saying
"Not Found The requested URL /asdf was not found on this server."
I think it is a very simple error on my part. I am not sure whether they have changed the syntax or the keyword. I am not able to find any solution from the laravel docs as well.
I use the following for my CMS to catch all requests with a Regex filter:
Route::get('{uri}', 'PublicController#init')
->where('uri', '.*');
In your case it would probably look like this:
Route::get('{uri}', function($uri) {
return 'Hello, world!';
})->where('uri', '.*');
You can use the first one to load a method inside of a controller. The controller being PublicController and the method init. There you can handle your errors initiate any other processes based on the request.
This works really well, you can add reserved routes before ths route so it becomes the last route catching all requests that are not catched by previous routes.
In Laravel 4, you do:
Route::get('{shortened}', function($shortened)
instead of
Route::get('(:any)',function($shortened)
You can read more about route parameters in Laravel 4, here: http://laravel.com/docs/routing#route-parameters
Lauch Laravel
go to you'r application root,run the command PHP artisan serve
Put the routing
-Comment evrything in routing.php, add these routes:
Route::get('/', function()
{
echo 'hello';
});
Route::any('{shortened}',function($shortened){
echo "Evrything is ok with: ".$shortened;
})->where('shortened', '.*');
Launch you application
-go to http://localhost:8000/asdf

Categories