SSL for selected controller and selected function name [CodeIgniter] - php

I am here with a serious issue of my site. I am not a php developer but I know the basics. So if I make any mistake here, please try to forgive me.
My site is built with CodeIgnitor and I have SSL for some selected pages which is controlled by controller or controller name or function name.
Like - I am having SSL for these
$ssl_controllers = array('controller1','controller2','controller3');
URL structure is like this - https://mysite.com/controller1
Now, I have several functions inside each controller. Like this - inside of "controller1", I have "function_1()"
So the url for will be - https://mysite/controller1/function_1
Now I dont need SSL for "funtion_1" which is written inside of "controller1"
If I need to remove the SSL for "function_1", I need to remove whole "controller1" from the array. But I don't need that as there is other functions that require SSL.
So how I can remove SSL for "function_1"?
Is there a way to remove a function name from the array?
like this - $ssl_controllers =
$ssl_controllers = array('controller1'==>'function_1','controller2','controller3');
Please help me!!
Thanks!
As I am not using htaccess for redirection, your method is not working in my case. If I use htaccess, it gives me endless loop that cannot be completed!! This is because I am using CodeIgnitor library for redirection and specific page SSL
Here is the PHP code -
class CI_ssl{
function check_ssl()
{
$CI =& get_instance();
$class = $CI->router->fetch_class();
$ssl_controllers = array('controller1','controller2','controller3');
if(in_array($class,$ssl_controllers))
{
$CI =& get_instance();
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 443)
redirect($CI->uri->uri_string());
}
else
{
$CI =& get_instance();
$CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] == 443)
redirect($CI->uri->uri_string());
}
}
This gives me SSL for specific pages and redirects other to only http://

Use rewrite rules in your .htaccess:
RewriteCond %{SERVER_PORT} !80
RewriteCond %{REQUEST_URI} controller1/function_1
RewriteRule ^(.*)$ http://www.yourdomain.com/controller1/function_1 [R=301,L]
Note: Your base_url must be set to "/" in your config file.

Well after a research today, I finally have resolved my issue. Here is the demo -
$CI =& get_instance();
$class = $CI->router->fetch_class();
$ssl_controllers = array('controller1','controller2','controller3');
In this code, I have called the specific function this way -
$CI =& get_instance();
$class = $CI->router->fetch_class();
$ssl_controllers = array('controller1','controller2','controller3');
$my_function = $CI->router->fetch_method(); // fetch method is used for getting the specific function name
$ssl_functions = array('function_1'); // specific function name in array
Then, I just added elseif statement to my condition -
if(in_array($my_function,$ssl_functions))
{
$CI =& get_instance();
$CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] == 443)
redirect($CI->uri->uri_string());
}
elseif(in_array($class,$ssl_controllers))
{
$CI =& get_instance();
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
//echo $CI->config->config['base_url']."=>".$CI->uri->uri_string()."=>".$_SERVER['SERVER_PORT'];exit;
if ($_SERVER['SERVER_PORT'] != 443)
redirect($CI->uri->uri_string());
}
else
{
$CI =& get_instance();
$CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] == 443)
redirect($CI->uri->uri_string());
}
}
Thus my new url comes without SSL! like this -
http://mysite/controller1/function_1

Related

Codeigniter https page on site

I have built a bespoke site in Codeigniter and my client is getting orders through PayPal.
The problem that is happening is that I have written the site so that if a PayPal order is complete and returns back to the site, The booking gets updated to paid.
I have noticed that some orders, The customer is not returning to the site due sometimes the "Insecure Data" popup you get in most browsers.
I think, The way to resolve this is to make the return page an https:// page.
So am wondering how do you change the config in your CI to the https:// link on just that one page.
There may be other ways and am open to suggestions.
I am also considering the IPN route to update the order, But not too sure on that one.
Thanks
Use MY_url_helper helper.
Add the following code to helper and use it whereever you want to force ssl.
<?php
function ssl_support() {
$CI = & get_instance();
return $CI->config->item('ssl_support');
}
if (!function_exists('force_ssl')) {
function force_ssl() {
if (ssl_support() && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off')) {
$CI = & get_instance();
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
redirect($CI->uri->uri_string());
}
}
}
if (!function_exists('remove_ssl')) {
function remove_ssl() {
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$CI = & get_instance();
$CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
redirect($CI->uri->uri_string());
}
}
}
}
I would say put everything in one folder and use SSL for everhting?
application/config/config.php, set base url:
$config['base_url'] = "https://www.yoursite.com/";

Codeigniter Rest server Digest or Basic auth cant login

I'm using Phil Sturgeon’s REST Server. I'm having trouble to set up the basic or digest authentication. When calling the method i get the dialog that prompts for username and password even if i write in the correct username and password it wont accept it. How do i troubleshoot this ? Is it my web host that doesnt allow it ?
This is how i set up the auth in rest.php:
The rest is default.
$config['rest_auth'] = 'Basic';
$config['auth_source'] = '';
$config['rest_valid_logins'] = array('admin' => 'password');
I found the solution myself. I had to add this on my .htaccess file.
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
Sorry for writing in such an old thread. Thought it may save somebody's time.
Please note that this solution is for basic auth only. I have not tested this with digest auth.
I required to tweak #Tan's answer a bit to get the .htaccess to work.
I removed the [L] from RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L] and placed the rewrite rule just after RewriteEngine on
The .htaccess file:
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#Other rules follow
Next, I required to change the rest.php config file inside application/config directory. The changes I made are as follows:
$config['auth_source'] = 'ldap' to $config['auth_source'] = 'library',
$config['auth_library_class'] = '' to $config['auth_library_class'] = 'api_auth'
$config['auth_library_function'] = '' to $config['auth_library_function'] = 'login'
Then, I created a new library file named Api_auth.php having the following code:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Api_auth
{
public function login($username, $password) {
if($username == 'admin' && $password == '1234')
{
return true;
}
else
{
return false;
}
}
}
Hope this helps someone someday.
this didnt work for me but this did
for me It related the the sever running php as a fastCGI, not a php5_module, like your localhost does. ( to find this out run phpinfo - Server API: CGI/FastCGI )
here was the solution
http://ellislab.com/forums/viewthread/173823/#825912
.htaccess
RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
libraries/REST_Controller.php
BEFORE
// most other servers
elseif ($this->input->server('HTTP_AUTHENTICATION'))
{
if (strpos(strtolower($this->input->server('HTTP_AUTHENTICATION')),'basic') === 0)
{
list($username,$password) = explode(':',base64_decode(substr($this->input- >server('HTTP_AUTHORIZATION'), 6)));
}
}
AFTER
// most other servers
elseif ( $this->input->server('HTTP_AUTHENTICATION') || $this->input- >server('REDIRECT_REMOTE_USER') )
{
$HTTP_SERVER_AUTH = ($this->input->server('HTTP_AUTHENTICATION')) ? $this->input->server('HTTP_AUTHENTICATION') : $this->input->server('REDIRECT_REMOTE_USER');
if (strpos(strtolower($HTTP_SERVER_AUTH),'basic') === 0)
{
list($username,$password) = explode(':',base64_decode(substr($HTTP_SERVER_AUTH, 6)));
}
}

CakePHP app in directory breaks redirects done with query string

My CakePHP 2.0 application url is: http://localhost/testapplication/
and when I do redirects on a login from a link I use a query string e.g.
localhost/testapplication/login?continue=/testapplication/admin/posts
The redirect is done using:
if(isset($this->params['url']['continue']))
{
$pathtoredirect = $this->params['url']['continue'];
}
else
{
$pathtoredirect = $this->Auth->redirect();
}
return $this->redirect($pathtoredirect);
However when I do the redirect I will end up at a URL like:
localhost/testapplication/testapplication/admin/posts
As you can see it redirects to the passed url but because the passed url also contained the base directory it duplicates it breaking the url redirect and ending up at a 404!
Any ideas on how to get around this problem?
Just to confirm:
The url does start with a / so it does redirect at the root level, but the problem is that root level is a directory so it duplicates it as it's also passed in the query
If you construct a path in either of the following ways:
$continue = Router::url(array('controller' => 'admin', 'action' => 'posts'));
$continue = Router::url('/admin/posts');
then Router::url will prepend the base path /application. Then if you call Router::url again on the resulting url (or redirect to it) Router::url will prepend it again. That's the way it works, and there's nothing you can do about it.
In reality, the url /application/admin/posts is ambiguous, but CakePHP reads it as controller=application, action=admin, and the first argument is posts.
The only ways to circumvent this are:
Use an absolute url:
$continue = Router::url(array('controller' => 'admin', 'action' => 'posts'), true);
Or make sure Router::url is only called once, e.g.:
$continue = '/admin/posts';
Or after login
$pathtoredirect = FULL_BASE_URL . $this->params['url']['continue'];
Okay the fix was to do the following:
Get the full URL (as mentioned by others) here using a helper:
class LinkHelper extends AppHelper
{
public function selfURL()
{
$pageURL = 'http';
//if ($_SERVER["HTTPS"] == "on")
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
{
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
$pageURL = urlencode($pageURL);
return $pageURL;
}
}
Then when using the URLs making sure to encode and decode them for use in the address bar
e.g. $pathtoredirect = urldecode($this->params['url']['continue']);
It seems like you have a couple options here. If $this->params['url']['continue'] is exactly what you pass in with your query string, is it possible for you to modify your query string so it is just /admin/posts so the complete URL will be application/admin/posts?
You may not have to do this, but I'd need to see exactly what $this->params['url']['continue'] looks like. Please do a die(debug($this->params['url']['continue'])); somewhere before your redirect so we can investigate further.

Issuing a redirect from a Joomla module

I am not really familiar with Joomla but I have been tasked with writing a module which functionality is irrelevant to the question.
One of the requirements is that if the module is loaded, it should check if the user is logged in and if not - redirect him into a specific URL.
After some searching I came up with something like this, but it's obviously not a working answer:
$user =& JFactory::getUser();
if (!$user->id) {
include_once JPATH_COMPONENT . DIRECTORY_SEPARATOR . "controller.php"; // assuming com_content
$contentController = new ContentController();
$link = JRoute::_("my url");
$contentController->setRedirect($link);
return;
}
I think the problem lies in getting to the controller. Creating a new controller certainly isn't the way to go. Is there a way to get the current controller from a Joomla module and the issue a redirect?
Thank you for any answers.
i call this static function in each of my controllers construct
static function forceLoggedIn(){
$user = JFactory::getUser();
if($user->guest||$user->id == 0)
{
$error = JText::_('YOU MUST BE LOGGED IN');
//base xkè altrimenti andrebbe in loop di redirect
JFactory::getApplication()->redirect(JURI::base(), $error, 'error' );
return false;
}
}

https request on some pages but not on all pages zend framework

I need to put https on some of the URL but not on all the URL. I am using zend URl view helper for all the links. I have a *.example.com SSL certificate for whole site. Now I open site with https://www.example.co, then all the link on home page or other pages contains https in URL. How can I make some specific request on the https url and other page should be opened normal.
I also need to pt some redirection so that if somebody open the specific pages in normal URL then they redirected on https url. I think the .htaccess redirection will work for that.
Any help ????
Thanks in advance!!!
the URL ViewHelper only assembles paths, absolute from the hostname. so you need to explicitly prefix your https links
<? $url = $view->url(array('some' => 'params') /*, $route, $reset*/) ?>
my explicit https link
you should maybe create a an own small viewhelper which does that work for your and also checks if HTTP_HOST is set etc, maybe also take it from the config instead from $_SERVER.
$view->httpsUrl(array('some' => 'params')/, $route, $reset/);
to be secure that defined reqeust must be https can easily be done by adding a front controller plugin or even an abstract controller-class you base all your otehr controller on.
a plugin could look like this
My_Controller_Plugin_HttpBlacklist extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
// when /foo/bar/baz is requested
if (($request->getModuleName() == 'foo' &&
$request->getControllerName() == 'bar' &&
$request->getControllerName() == 'baz')
/* || (conditions for more requests)*/) {
//very basic confifiotn to see if https is enabled, should be done better...
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
// should be done with Zend_Http_Reponse instead
header('Location: https://'. $_SERVER['HTTP_HOST] . $_SERVER['REQUEST_URI']);
exit;
}
}
}
}
then simply plug it in
$frontController->registerPlugin(new My_Controller_Plugin_HttpBlacklist);
I rather used a simple method and that does not required any change in urls generation/route. I wrote following lines in routeStartup function of a plugin and haven't made any change in URLs route.
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
$controller=$this->_controller = $this->_front->getRequest()->getControllerName();
$action=$this->_controller = $this->_front->getRequest()->getActionName();
if($_SERVER['SERVER_PORT']!=443)
{
//controller and actions array to check ssl links
$actionArr=array('index'=>array('registration'),'account'=>array('editacc','edit'),'dealer'=>array('*'));
if(array_key_exists($controller,$actionArr)!==false)
{
if(in_array($action,$actionArr[$controller]) || $actionArr[$controller][0]=='*')
{
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->gotoUrl(SITE_LIVE_URL_SSL.$controller."/".$action);
}
}
}
else
{
//controller and action array that should not be on ssl.
$notAactionArr=array('usersearch'=>array('mainserarch'),'account'=>array('index'),'onlineusers'=>array('*'));
if(array_key_exists($controller,$notAactionArr)!==false)
{
if(in_array($action,$notAactionArr[$controller]) || $notAactionArr[$controller][0]=='*')
{
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->gotoUrl(SITE_LIVE_URL.$controller."/".$action);
}
}
}
}

Categories