Error 400 Your request is invalid in yii if i am creating link - yii

I'm pretty new to Yii, so this might be a silly question. I must be missing something somewhere. Plz help me out.
I have just written a simple code while I'm learning Yii.
I have a spark controller which has an action that looks like this:
public function actionDownload($name){
$filecontent=file_get_contents('images/spark/'.$name);
header("Content-Type: text/plain");
header("Content-disposition: attachment; filename=$name");
header("Pragma: no-cache");
echo $filecontent;
exit;
}
Now I have enabled SEO friendly URLs and echo statement in the view file to display the returned download file name.
But when I go to the URL,
SITE_NAME/index.php/spark/download/db5250efc9a9684ceaa25cacedef81cd.pdf
I get error 400 - your request is invalid.
Plz let me know if I am missing something here.

Yii keeps an eye on the params you pass into an action function. Any params you pass must match what's in $_GET.
So if you're passing $name then you need to make sure there's $_GET['name'] available.
So check your URL manager in /config/main.php, and make sure you're declaring a GET var:
'spark/download/<name:[a-z0-9]+>' => 'site/download', // Setting up $_GET['name']
Otherwise change your function to the correct param variable:
public function actionDownload($anotherName){
}

Did you create the URL correct? You should do it best with
Yii::app()->createUrl('/spark/download',array('name'=>$filename));

Make sure if you are properly supplying the parameter name ($name) in your request.
Use
SITE_NAME/index.php/spark/download/name/db5250efc9a9684ceaa25cacedef81cd.pdf
or
SITE_NAME/index.php/spark/download?name=db5250efc9a9684ceaa25cacedef81cd.pdf
instead of just SITE_NAME/index.php/spark/download/db5250efc9a9684ceaa25cacedef81cd.pdf

Related

How to rewrite rules NginX in this example?

I am creating an API to feed some apps.
So the app could call these possible URLs to get information from the database;
mysite.com/api/v1/get/menus/list_tblname1.json.php
mysite.com/api/v1/get/menus/list_tblname1.json.php?type=arr
mysite.com/api/v1/get/menus/list_tblname2.json.php
mysite.com/api/v1/get/menus/list_tblname2.json.php?type=arr
In php I have already the code that grabs the tblname from the URL and give me back all the table content. It works good (it is not the final version).
But now I find myself copying and pasting the same code for each page where the URL points to. Here is the code:
<?php
header('Content-Type:application/json');
include_once '../../../../class/db.php';
$verb=$_SERVER['REQUEST_METHOD'];
$filePath=$_SERVER['SCRIPT_NAME'];
$split1 = explode("/", $filePath);
preg_match("/(?<=_)[^.]+/", $split1[5], $matches);
$tableName = $matches[0];
if ($verb=="GET") {
header("HTTP/1.1 200 ok");
if(isset($_GET['type']) && $_GET['type']=="arr"){
echo db::get_list($tableName,'arr');//Reply ARRAY
}
else{
echo db::get_list($tableName);//Reply JSON
}
}
else{
die("Nothing for you at this page!");
}
I mean, I have the same code inside each these pages.
list_tblname1.json.php
list_tblname2.json.php
I am not sure how to solve this situation but I think that this is case for
rewrite rules.
So, I think a possible solution is to create one page that could call
returncontent.php for example and create rules in the server that should point to the same page when certanlly pages are requested and pass the parameter $tableName to the page. I think I should pass the regex to my server and grab the $tableName with $_GET[] (I think) inside returncontent.php.
I am not sure about it.
I am using NginX.
How to implement it in this scenario?
As a rule, it's bad practice to parse a URI in NginX and pass the result downstream.
Rather: mysite.com/api/v1/get/menus/returncontent.php?file=list_tblname2.json
No changes to NginX needed. Parse the query param (file) in PHP.

CakePHP 3.x I need to check prefix in model if admin

I want to check if the current address is admin area IN MODEL to change conditions:
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary) {
debug($this->request['prefix']);
}
It's not working. I need only to access to request vars IN MODEL.
Thanks.
I resolve it by using $_SERVER variable. It's works good
$_SERVER['REQUEST_URI']
but I still need to add beforefind for each Model... while I need only general conditions for all queries... I really feel bad about the accessibility of cakephp
Brother you can use the class in model
use Cake\Network\Request;
and Get path if you want

How can I access query string parameters for requests I've manually dispatched in Laravel 4?

I'm writing a simple API, and building a simple web application on top of this API.
Because I want to "consume my own API" directly, I first Googled and found this answer on StackOverflow which answers my initial question perfectly: Consuming my own Laravel API
Now, this works great, I'm able to access my API by doing something like:
$request = Request::create('/api/cars/'.$id, 'GET');
$instance = json_decode(Route::dispatch($request)->getContent());
This is great! But, my API also allows you to add an optional fields parameter to the GET query string to specify specific attributes that should be returned, such as this:
http://cars.com/api/cars/1?fields=id,color
Now the way I actually handle this in the API is something along the lines of this:
public function show(Car $car)
{
if(Input::has('fields'))
{
//Here I do some logic and basically return only fields requested
....
...
}
I would assume that I could do something similar as I did with the query string parameter-less approach before, something like this:
$request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET');
$instance = json_decode(Route::dispatch($request)->getContent());
BUT, it doesn't seem so. Long story short, after stepping through the code it seems that the Request object is correctly created (and it correctly pulls out the fields parameter and assigns id,color to it), and the Route seems to be dispatched OK, but within my API controller itself I do not know how to access the field parameter. Using Input::get('fields') (which is what I use for "normal" requests) returns nothing, and I'm fairly certain that's because the static Input is referencing or scoping to the initial request the came in, NOT the new request I dispatched "manually" from within the app itself.
So, my question is really how should I be doing this? Am I doing something wrong? Ideally I'd like to avoid doing anything ugly or special in my API controller, I'd like to be able to use Input::get for the internally dispatched requests and not have to make a second check , etc.
You are correct in that using Input is actually referencing the current request and not your newly created request. Your input will be available on the request instance itself that you instantiate with Request::create().
If you were using (as you should be) Illuminate\Http\Request to instantiate your request then you can use $request->input('key') or $request->query('key') to get parameters from the query string.
Now, the problem here is that you might not have your Illuminate\Http\Request instance available to you in the route. A solution here (so that you can continue using the Input facade) is to physically replace the input on the current request, then switch it back.
// Store the original input of the request and then replace the input with your request instances input.
$originalInput = Request::input();
Request::replace($request->input());
// Dispatch your request instance with the router.
$response = Route::dispatch($request);
// Replace the input again with the original request input.
Request::replace($originalInput);
This should work (in theory) and you should still be able to use your original request input before and after your internal API request is made.
I was also just facing this issue and thanks to Jason's great answers I was able to make it work.
Just wanted to add that I found out that the Route also needs to be replaced. Otherwise Route::currentRouteName() will return the dispatched route later in the script.
More details to this can be found on my blog post.
I also did some tests for the stacking issue and called internal API methods repeatedly from within each other with this approach. It worked out just fine! All requests and routes have been set correctly.
If you want to invoke an internal API and pass parameters via an array (instead of query string), you can do like this:
$request = Request::create("/api/cars", "GET", array(
"id" => $id,
"fields" => array("id","color")
));
$originalInput = Request::input();//backup original input
Request::replace($request->input());
$car = json_decode(Route::dispatch($request)->getContent());//invoke API
Request::replace($originalInput);//restore orginal input
Ref: Laravel : calling your own API

Yii framework urlManager rewrite rules

I have a url that looks like this:
<controller>/<action>/param/value
and I want it to like something like this:
param/value
How can it be achieved?
I tried this rule but not sure if it's ok (controller is account and action is index).
'user/<user:.*>' => 'account/index/user/test'
If I uderstand your question correctly, you want to handle URL's like this:
mysite.domain/user/username123
And call actionIndex in AccountController with param User, which (in this case) equals "username123"
In this case you can try the rule below:
'user/<user:.*>' => 'account/index/<user>'
But maybe you will need to change the declaration if your action:
function actionIndex($user){
// code
}
I would avoid putting params into action signatures as yii doens't go about processing actions with mismatching signatures [gracefully] at all... In fact, putting $user in will bind that action to always need a $user specified and if you ever decide to change your functionality, tracking down why your action isn't being called would be harder than determining why your $_GET isn't set... I would suggest in stead of adding the $user into the signature, just do something as follows in your action.
//will always run on /user/<USER:.*>
function actionIndex(){
$user = isset($_GET['user'])?$_GET['user']:NULL;
if(!is_null($user)){
//your user specific account action..
}else{
//handle your error gracefully..
}
}
This approach lets your action be more versatile. The URL rule should be as follows:
'user/<user:.*>' => 'account/index/user/<user>' //user is defined as a get...
Hope that helps && happy coding!

giving ID and/or other variables for each php page

Is there a simple php coding way how to add variable(s) "dynamic or fixed types" to include in a link so that the link doesn't show up as a clean url. And this an example of what I mean:
www.example.com/folder/sense/home
To
www.example.com/folder/sense/index.php?type=article&id=25&date_written=20100322
Or
www.example.com/folder/sense/index.php?id=25
I hope it is clear what I'm up to.
P.S: this is all in Apache
Thanks
The http_build_query function (http://php.net/manual/en/function.http-build-query.php) will convert an array of data into an urlencoded string of variables.
Example from the link above:
<?php
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data) . "\n";
?>
will output
foo=bar&baz=boom&cow=milk&php=hypertext+processor
I am not sure i get it, but if you use a form with post, $_POST array will keep variables and they will not be visible in the url