Symfony redirect user to url country - php

I'm looking for a PHP / Symfony code to redirect the user to another link according to his place of connection www.mondomain.fr/fr and www.mondomaine.fr/pt etc ... How can I do this ? I have included in my roads this already:
/**
* #Route("/{_locale}", name="homepage")
*
*/
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$boutton = $em->getRepository('AppBundle:Boutton')->findAll();
$image = $em->getRepository('AppBundle:Images')->findAll();
// replace this example code with whatever you need
return $this->render('default/index.html.twig', array(
'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
'boutton' => $boutton,
'images' => $image
));
}
Thank you

One of the solutions (not a PHP one) is to redirect based on browser language, you can find answer here.
You can also detect IP and redirect based on that, you can use this library to get the country/locale of the IP address and then redirect based on that.

Related

Laravel viewing picture in local disk

I am making like a dropbox clone for a school project, i made an upload fuction that uploads to the local disk so it cant be accessed by everyone.
Upload Function
public function updatedUpload($upload){
$object = $this->currentTeam->objects()->make(['parent_id' => $this->object->id]);
$object->objectable()->associate(
$this->currentTeam->files()->create([
'name' => $upload->getClientOriginalName(),
'size' => $upload->getSize(),
'path' => $upload->storePublicly('files', ['disk' => 'local'])
])
);
$object->save();
$this->object = $this->object->fresh();
}
But I want to put it in an in the home.blade.
How do I make this and only the person who uploaded it can access it?
You can create a specific link for the user that can see this resource.
For example in your routes/web.php
Route::get('/private_resource',[\App\Http\Controllers\PrivateResource::class, 'getLocalResource'])
->name('get_private_resource')->middleware('auth');
Define PrivateResource controller
class PrivateResource
{
public function getLocalResource($filename){
// Get your resource, for example
$file = File::where('name', $filename)->first();
// Check whether user can access this resource
// For example
if(\Auth::id() != $file->user_id) abort(403);
return \Storage::disk('local')->download($filename);
}
}
Extra: If you want extra privacy, you can use signed route using below function.
\URL::signedRoute('get_private_resource');
And add signed middleware to your route
Route::get('/private_resource',[\App\Http\Controllers\PrivateResource::class, 'getLocalResource'])
->name('get_private_resource')->middleware('auth','signed');

How to properly redirect in Symfony?

I have a route that creates several database entries. After the creation I'd like to forward to a route that fetches those entries and displays them.
This is the route for fetching/displaying:
/**
* #Route("/admin/app", name="appTourOverview")
*/
public function appTourOverviewAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
/* Get Network for User */
$network = $this->getUser()->getNetwork();
$tours = $em->getRepository('AppBundle:Tour')->toursTodayByNetwork($network);
return $this->render(':app:index.html.twig', array(
'tour' => $tours,
'imagePath' => Constants::IMAGE_PATH_DEV,
'imagePathGreen' => Constants::IMAGE_PATH_DEV_GREEN,
'imagePathYear' => Constants::IMAGE_PATH_DEV_YEAR,
));
}
and this is how I redirected from the "database route":
return $this->redirectToRoute('appTourOverview', array(), 301); but this gets cached and the database entries are never created...
I tried:
I copied everything from the "display route" and let it return the database stuff immediately.
/* Get Network for User */
$network = $this->getUser()->getNetwork()->getId();
$tours = $em->getRepository('AppBundle:Tour')->toursTodayByNetwork($network);
return $this->render(':checker:index.html.twig', array(
'tour' => $tours,
'imagePath' => Constants::IMAGE_PATH_DEV,
'imagePathGreen' => Constants::IMAGE_PATH_DEV_GREEN,
'imagePathYear' => Constants::IMAGE_PATH_DEV_YEAR,
));
instead of the redirect. Unfortunately this only works after a refresh? ($tours is empty the first time)
Any ideas?
the 301 redirect means he page was moved permanently and this information will be cached in your browser now. Please change that parameter to 302 or just remove (this is not necessary). Then, unfortunately you need to remove your browser's cache and the it should work.
302 means the redirect is temporary and browser won't cache it;

Adding GET input to my resourceful controller in Laravel

Using Laravel 4 to create a "Read-it-Later" application just for testing purposes.
I'm able to successfully store a URL and Description into my application using the following curl command:
curl -d 'url=http://testsite.com&description=For Testing' readitlater.local/api/v1/url
I'm interested in using GET to accomplish the same thing but by passing my variables in a URL (e.g. readitlater.local/api/v1/url?url=testsite.com?description=For%20Testing)
Here is my UrlController segment:
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$url = new Url;
$url->url = Request::get('url');
$url->description = Request::get('description');
$url->save();
return Response::json(array(
'error' => false,
'urls' => $urls->toArray()),
200
);
}
Here is my Url model:
<?php
class Url extends Eloquent {
protected $table = 'urls';
}
I read through the Laravel docs on input types but I'm not certain how to apply that to my current controller: http://laravel.com/docs/requests#basic-input
Any tips?
You didn't apply what you correctly linked to...Use Input::get() to fetch anything from GET or POST, and the Request class to get info on the current request. Are you looking for something like this?
public function store()
{
$url = new Url; // I guess this is your Model
$url->url = Request::url();
$url->description = Input::get('description');
$url->save();
return Response::json(array(
'error' => false,
'urls' => Url::find($url->id)->toArray(),
/* Not sure about this. You want info for the current url?
(you already have them...no need to query the DB) or you want ALL the urls?
In this case, use Url::all()->toArray()
*/
200
);
}

YII framework user friendly URL

My yii PHP project has UserController and it has an action called actionView. I can access user view page using following URL
mysite.com/user/view/id/1
I want to change that one to
mysite.com/username
How Can I do it.
I know that i can simply create rule to be more user friendly to get url such as
mysite.com/user/username
But url scheme with database resource name as direct param (mysite.com/username) is whole different story.
Url rule:
array(
'<username:\w+>'=>'user/view',
)
Note that in such scheme, you must also create rules for all your controllers and place above rule at the end, so better prefix it with user:
array(
'user/<username:\w+>'=>'user/view',
)
Resulting url will be example.com/user/username
In action:
public function actionView($username) ...
Update:
To make rule which reacts on any input variable create custom url rule class, here is some example, modify to your needs:
class PageUrlRule extends CBaseUrlRule
{
public function createUrl($manager, $route, $params, $ampersand)
{
// Ignore this rule for creating urls
return false;
}
public function parseUrl($manager, $request, $pathInfo, $rawPathInfo)
{
// Ignore / url or any controller name - which could conflict with username
if($pathInfo == '/')
{
return true;
}
// Search for username or any resource in db
// This is for mongo so it should be tuned to your db,
// just check if username exists
$criteria = new EMongoCriteria();
$criteria->url->$lang = $url;
$criteria->select(['_id']);
$criteria->limit(1);
$model = PageItem::model();
$cursor = $model->findAll($criteria);
// Create route, instead of $url id can be used
$route = sprintf('content/page/view/url/%s', urlencode($url));
// If found return route or false if not found
return $cursor->count() ? $route : false;
}
}
Then place this rule in beginning of urlmanager config
'rules' => [
[
'class' => 'application.modules.content.components.PageUrlRule'
],
// Other rules here
Important: If user has username same as your controller, it will match username and controller will be inaccessible. You must forbid registering users with same names as controllers.

Symfony2 - PdfBundle not working

Using Symfony2 and PdfBundle to generate dynamically PDF files, I don't get to generate the files indeed.
Following documentation instructions, I have set up all the bundle thing:
autoload.php:
'Ps' => __DIR__.'/../vendor/bundles',
'PHPPdf' => __DIR__.'/../vendor/PHPPdf/lib',
'Imagine' => array(__DIR__.'/../vendor/PHPPdf/lib', __DIR__.'/../vendor/PHPPdf/lib/vendor/Imagine/lib'),
'Zend' => __DIR__.'/../vendor/PHPPdf/lib/vendor/Zend/library',
'ZendPdf' => __DIR__.'/../vendor/PHPPdf/lib/vendor/ZendPdf/library',
AppKernel.php:
...
new Ps\PdfBundle\PsPdfBundle(),
...
I guess all the setting up is correctly configured, as I am not getting any "library not found" nor anything on that way...
So, after all that, I am doing this in the controller:
...
use Ps\PdfBundle\Annotation\Pdf;
...
/**
* #Pdf()
* #Route ("/pdf", name="_pdf")
* #Template()
*/
public function generateInvoicePDFAction($name = 'Pedro')
{
return $this->render('AcmeStoreBundle:Shop:generateInvoice.pdf.twig', array(
'name' => $name,
));
}
And having this twig file:
<pdf>
<dynamic-page>
Hello {{ name }}!
</dynamic-page>
</pdf>
Well. Somehow, what I just get in my page is just the normal html generated as if it was a normal Response rendering.
The Pdf() annotation is supposed to give the "special" behavior of creating the PDF file instead of rendering normal HTML.
So, having the above code, when I request the route http://www.mysite.com/*...*/pdf, all what I get is the following HTML rendered:
<pdf>
<dynamic-page>
Hello Pedro!
</dynamic-page>
</pdf>
(so a blank HTML page with just the words Hello Pedro! on it.
Any clue? Am I doing anything wrong? Is it mandatory to have the alternative *.html.twig apart from the *.pdf.twig version? I don't think so... :(
Ok I got it.
For some reason, the example that comes in the bundle documentation didn't work for me. Nevertheless, there is this class in de bundle: http://github.com/psliwa/PdfBundle/blob/master/Controller/ExampleController.php, where I could find an example that did work for me. This is the code that I finally used:
/**
* #Route ("/generateInvoice", name="_generate_invoice")
*/
public function generateInvoiceAction($name = 'Pedro')
{
$facade = $this->get('ps_pdf.facade');
$response = new Response();
$this->render('AcmeStoreBundle:Shop:generateInvoiceAction.pdf.twig', array("name" => $name), $response);
$xml = $response->getContent();
$content = $facade->render($xml);
return new Response($content, 200, array('content-type' => 'application/pdf'));
}
Next challenge: store that PDF into disk.
It's because you've missed the "_format" option in the URL.
$this->render() shouldn't be used with the #Template annotation. The #Template will serve the correct template's format depending of the _format parameter.
...
use Ps\PdfBundle\Annotation\Pdf;
...
/**
* #Pdf()
* #Route ("/pdf.{_format}", name="_pdf")
* #Template()
*/
public function generateInvoicePDFAction($name = 'Pedro')
{
return array('name' => $name);
}
Should work fine.

Categories