CodeIgniter: How to set a controller function to be a post route? - codeigniter

I usually use something like:
class User extends CI_Controller {
public function save() {
if($this->input->is_post()) { //my own method
......
}
}
}
Is there any other way, eg. in Slim framework:
post("/user/save", function() {
......
});
or in .Net MVC:
[HttpPost]
public ActionResult save(User model) {
......
}
Or can CodeIgniter handle this in its route config file?
Thanks for answer.

Codeigniter has no built-in support for REST. If you want it, you need to use third-party library or write your own. For third-party library, Here is good one : codeigniter-restserver .
Hope it will be useful for you.

To remove index.php use this in your .htaccess file
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Related

Laravel Routing Always 404 on API Post

I'm in Laravel 5.8 in Windows trying to create an inbound API route. Postman always gives me a 404 when I try to hit this route:
http://MYHOSTISHERE/api/v1?event=NewDealerSetUp&api_key=MYKEYISHERE
CURL with
curl -X POST "http://rx-0-unicorn.local/api/v1?event=NewDealerSetUp&api_key=MYAPIKEYHERE"
also gives me a 404.
Can someone point me to what I'm doing wrong? I'm bald but I may start pulling out beard in a minute.
Details below, and thanks!
I have this route in app.php:
Route::post('v1?event={event}&api_key={api_key}', 'API\APIController#index');
The route shows in artisan route list:
| | POST | api/v1?event={event}&api_key={api_key} | | App\Http\Controllers\API\APIController#index | api |
VerifyCsrfToken Middleware (just to see if it would work):
protected $except = [
'api/*'
];
Controller start:
namespace App\Http\Controllers\API;
use App\Models\Log\LogAPI;
use App\Models\Members;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
class APIController extends Controller
{
public function index($event, $api_key, Request $request)
{
$data = filter_var_array((array)$request, FILTER_SANITIZE_SPECIAL_CHARS);
[...]
if($event == 'NewDealerSetUp'){
$setup = new NewDealerSetup();
return $setup->newDealerSetup($request);
}
.htaccess
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# ------------------------------------------------------------------------------------------------------
# NOTES:
# the log: strip per-dir prefix: C:/apache/htdocs/MYAPPNAME/public/ ->[EMPTY] ... takes the ^[EMPTY] and returns an empty
# ------------------------------------------------------------------------------------------------------
</IfModule>
Your route definition is the issue here. You've used query parameters in the route definition v1?event={event}&api_key={api_key} which is wrong. I'm not sure of it, but I've never seen any route definitions like this before as in route definition, we usually only define the endpoint and don't give any query params
Your controller definition is
public function index($event, $api_key, Request $request)
For this to work, your route would need to be something like
Route::post('v1/{event}/{api_key}', 'API\APIController#index');
or anything similar like
Route::post('v1/event/{event}/api_key/{api_key}', 'API\APIController#index');
If you must use query parameters, then you will have to use
Route::post('v1', 'API\APIController#index');
and handle the params in your controller
public function index(Request $request)
{
$event = $request->event;
$api_key = $request->api_key;
// Rest of code
}

Second url parameter is returning php error

There is no problem when I enter the first parameter but when I enter the second parameter I get the error I mentioned below
.htaccess
RewriteEngine on
RewriteCond $1 !^(index\\.php|resources|robots\\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
I enter this url: www.domain.com/first-parameter/second-parameter
Returned Error:
A PHP Error was encountered
Severity: Error
Message: Call to undefined function base_url()
Filename: _inc/_head.php
Line Number: 4
Backtrace:
routes.php
/*Ayarlar*/
$route['default_controller'] = 'Home';
$route['404_override'] = '';
/*Ayarlar*/
$route['(:any)'] = 'Home/index/$1';
$route['translate_uri_dashes'] = true;
I enter this url: www.domain.com/first-parameter/second-parameter
Example Local Url: http://localhost/sicacik-yemek-tarifleri-mobile/bilgi/assadad/asasad
controllers/Home.php
class Home extends public_Controller {
public function __construct()
{
parent::__construct();
}
public function index($s1='')
{
if(!empty($s1)){
if (!empty($data['anakategori'])) {
$this->load->view('example',$data);
} elseif (!empty($data['altkategori'])) {
$this->load->view('example',$data);
}elseif(!empty($data['tarif'])){
$this->load->view('example',$data);
} elseif(!empty($kacKalori)){
$this->load->view('example',$data);
}else{
show_404();
}
}else{
$this->load->view('Home',$data);
}
}
}
Don't post images instead of code. Code is used to be copied finding solution in more convinient/easier way.
First this (Important in RED on user guide):
The reserved routes must come before any wildcard or regular expression routes.
so your $route['translate_uri_dashes'] = true; has to be in different place.
Check default file to determine where to put it.
Also,
Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.
so you have to reorder last two
$route['soru-cevap/(:any)/(:any)'] = 'soru_cevap/index/$1/$2'; //this one is more specific one
$route['soru-cevap/(:any)'] = 'soru_cevap/index/$1';
//Take a look of controller and method names.
//Ones with dashes probably won't work.
You need to include $route['(:any)/(:any)'] = 'Home/index/$1/$2'; line in route.php
For www.domain.com/first-parameter/second-parameter url.

Laravel 5 shared hosting issue

please, I am trying to host Laravel 5 on a shared hosting.
When I access www.example.com/my_app_name, the page loaded correctly.
However, subfolders return 404 error. e.g. www.example.com/my_app_name/any_sub_folder or www.example.com/my_app_name/auth/login all return a 404 error.
shared_hosting_root
|--other_folders (not accessible via web domain)
|--applications (not accessible via web domain)
|--my_app_name
|--app
|--GoPublic.php <--I created this
|--bootstrap
|--config
|--database
|--public <--copied content to public_html
|--assets
|--index.php
|--resources
|--storage
|--tests
|--vendor
|--public_html
|--my_app_name
|--assets
|--index.php <-- I pointed here
I created a new file: shared_hosting_root\applications\my_app_name\app\GoPublic.php
<?php namespace App;
class GoPublic extends \Illuminate\Foundation\Application
{
/**
* Get the path to the public / web directory.
*
* #return string
*/
public function publicPath()
{
return $this->basePath.DIRECTORY_SEPARATOR.'../../public_html/my_app_name';
}
}
I edited bootstrap\app.php like so:
<?php
/* -- remove/comment this original code
$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);
-- until here */
/* -- add this new code -- */
$app = new App\GoPublic(
realpath(__DIR__.'/../')
);
I edited public\index.php like so:
I changed this:
require __DIR__.'/../bootstrap/autoload.php';
to
require __DIR__.'/../../applications/my_app_name/bootstrap/autoload.php';
and also changed this:
$app = require_once __DIR__.'/../bootstrap/app.php';
to
$app = require_once __DIR__.'/../../applications/my_app_name/bootstrap/app.php';
I then copied the content inside applications\my_app_name\public into public_html\my_app_name.
I followed the steps highlighted in this tutorial: http://blog.kongnir.com/2015/09/25/setting-up-laravel-5-on-shared-hosting-server/
The problem again:
I can access www.example.com/my_app_name.
But I get a 404 error on www.example.com/my_app_name/any_sub_folder or even a login redirect www.example.com/myapp_name/auth/login
What am I doing wrong? Help, please.
Thank you.
Update
www.example.com/my_app_name/sub_folder returns 500 internal server error
My .htaccess file in public_html directory:
# Do not change this line.
RewriteEngine on
# Change example.com to your domain name
# RewriteCond %{HTTP_HOST} ^(www.)?schoolsmart.com.ng$
# Change your_app_name to the subfolder name
# RewriteCond %{REQUEST_URI} !^/wbs/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change your_app_name to the subfolder name
# Change example.com to your domain name
# RewriteRule ^(.*)$ /wbs/$1
# RewriteCond %{HTTP_HOST} ^(www.)?schoolsmart.com.ng$
# RewriteRule ^(/)?$ wbs/index.php [L]
RewriteCond %{REQUEST_URI} !^wbs
RewriteRule ^(.*)$ wbs/$1 [L]
For me chmoding the bootstrap, storage and yajra folder which is under vendor directory to 775, as suggested in the official laravel documentation, did the trick.

how to forced https instead of http after user login in zend framework2

I want user redirect to https insetad of http just after login in my new website made in zend framework2. please help.
I there any method available in zend freamework2 to get current used protocol(http or https).
You can redirect the user to the https version of a page inside the application. Above solution simply redirects all requests to it's http variant, and only for Apache. I would rather do it inside the application (then you're more in control) and make it server agnostic (what happens when you switch to nginx?)
An example is based on an answer I gave earlier here: ZF2 and force HTTPS for specific routes
The solution: create a controller plugin which you can call every time you need it.
Specify the pages you need to force a redirect (i.e. the page you show the login form):
use Zend\Http\Response;
public function loginAction()
{
// If return value is response, this means the user will be redirected
$result = $this->forceHttps();
if ($result instanceof Response) {
return $result;
}
// code here
}
And then you could create a controller plugin (call it ForceHttps) to return a response when the user should be redirected:
use Zend\Uri\Http as HttpUri;
class ForceHttps extends AbstractPlugin
{
public function __invoke()
{
$request = $this->getController()->getRequest();
if ('https' === $request->getUri()->getScheme()) {
return;
}
// Not secure, create full url
$plugin = $this->getController()->url();
$string = $plugin->fromRoute(null, array(), array(
'force_canonical' => true,
), true);
$url = new HttpUri($string);
$url->setScheme('https');
return $this->getController()->redirect()->toUrl($url);
}
}
What happens is
Check if the current scheme is https. If not, continue
Grab the current used url from the url() plugin, use the current route name (hence the first parameter is null), force the canonical version (i.e. with a full scheme and domain name) and reuse the current route match parameters (the true as last parameter).
Import the url (as a string) in the Zend\Url\Http object
Reset the scheme to the https version
Pass the url to the redirect plugin to grab a response which will perform the redirect
on your .htaccess write these rules
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ public/index.php [NC,L]
note that public/index.php is the root so you have to modify it and www.yoursite.com too
for logged-in user you have to do with php
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {//redirection should be here//}

route codeigniter not load the page

my problem is about the route of codeigniter, I'm working with that and for each function i wrote the route. When i put the last route, this one not working and it give me 404 error. I don't know why? maybe i'm doing mistake about the order of route but i think is right.
This is my route:
//MATCH SHARE
// route not working
$routes['upload_image/upload_photo'] = "upload_image/upload_photo";
//all route working
//VOTATION//
$route['auth_social/fblogin'] = "auth_social/fblogin";
$route['votation/user_plus/(:any)'] = "votation/user_plus";
$route['votation/user_minum/(:any)'] = "votation/user_minum";
$route['finish_registration/(:any)/(:any)'] = "auth/activate"; // activate e-mail
$route['auth'] = "auth"; // index auth
$route['register'] = "auth/register";
$route['login'] = "auth/login"; // login
$route['logout'] = "auth/logout";
$route['default_controller'] = "auth/register"; // register
$route['(:any)'] = "profile/user";
$route['404_override'] = '';
htaccess
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
Try:
$routes['upload_image/upload_photo/?'] = "upload_image/upload_photo";
$routes['upload_image/upload_photo/(.+)'] = "upload_image/upload_photo/$1";
If you need to have extra uri segments, your current one won't work.
Your variable is wrong $routes it should be $route['upload_image/upload_photo'] = "upload_image/upload_photo";

Resources