site_url() with HTTPS prefix - codeigniter

*UPDATE
When I use site_url() it returns http://mysite.com
Is there a function or an option to get this to return the site URL with HTTPS ?
Example
So site_url( array('use_https' => 'on') ) to get https:mysite.com

Not specifically. But you could write your own function or just use:
https://<?php echo $_SERVER['SERVER_NAME']; ?>
or
function url_https($base_url)
{
return str_replace('http://', 'https://', $base_url);
}

2022 Answer
This question is old but still ranks high in the Google results.
This function accepts parameters:
https://developer.wordpress.org/reference/functions/site_url/
The second parameter sets the scheme. So you can use it as following:
site_url('/', 'https');

1 Hack is to change the codeignite definition of the base url to just // ... // will use what ever protocol is in use right now.
if you use https://example.com your links will use https if you use http://example.com your links will use http
/* Location: ./system/core/Config.php */
if (isset($_SERVER['HTTP_HOST']) && preg_match('/^((\[[0-9a-f:]+\])|(\d{1,3}(\.\d{1,3}){3})|[a-z0-9\-\.]+)(:\d+)?$/i', $_SERVER['HTTP_HOST']))
{
$base_url = /*(is_https() ? 'https' : 'http').'://'.*/"//".
$_SERVER['HTTP_HOST'].substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME'])));
}
else
{
$base_url = 'http://localhost/';
}

Related

Laravel 5.4 route wildcards

I was wondering how to create URL's in Laravel, without any prefix.
For Example:
How to transform following URL:
http://www.example.com/posts/some-post
To this URL:
http://www.example.com/some-post
I know this can be done as:
Route::any('/{slug}', function($slug) {
$page = App\Models\Page::firstByAttributes(['slug' => $slug]);
if($page) {
return Redirect::action('pagesController#find', array($page));
}
})->where('slug', '.*');
But for above code I've to maintain all unique slugs for each URL.
Any other way to do this right?
Thanks.
If you want to do it with Laravel:
Routes
Route::get('posts/{slug}', function($slug) {
// Does a 302 redirect, and the route below will handle it
return redirect($slug);
});
Route::get('{slug}', 'pagesController#find');
Controller
public function find($slug) {
$page = App\Models\Page::where('slug', $slug);
// ... your code
// ...
// return view('something', ['page' => $page]);
}
The redirection you describe can be easily done with an Apache rewrite rule, before you hit the application layer, which should be much more efficient. Eg, assuming Apache is set up to allow redirects from .htaccess, the following should be enough:
RewriteEngine On
RewriteRule ^posts/(.*) /$1 [R=301, L]
The R=301 indicates the redirect should happen with a 301 http response code, which will preserve your page rank etc.

Encrypting url(parameters only)

In one of projects i got recently have all the urls like
www.abc.com/controller/action/1222
I want to encrypt the url parameters only to achieve something like
www.abc.com/controller/action/saddsadad232dsdfo99jjdf
I know I can do it by changing all the urls one by one and sending the encrypted parameters and dealing with them all over the places in the project.
So my question is Is there a way I can encrypt all the urls at once without making changes to every link one by one ?
Just need a direction.I guess I put all the details needed.
thanks !
Here is a solution if you use the site_url helper function and you are sure that all your URLs comply this format www.abc.com/controller/action/1222:
All you need is to override the site_url method of the CI_Config class
class MY_Config extends CI_Config
{
public function site_url($uri = '', $protocol = NULL)
{
$urlPath = ltrim(parse_url($this->_uri_string($uri), PHP_URL_PATH), '/');
$segments = explode('/', $urlPath);
$numOfSegments = count($segments);
$result = [$segments[0], $segments[1]]; // controller and action
// start from the third segment
for($i = 2; $i < $numOfSegments; $i++)
{
// replace md5 with your encoding function
$result[] = md5($segments[$i]);
}
return parent::site_url($result, $protocol);
}
}
Example:
echo site_url('controller/action/1222'); will outputwww.abc.com/controller/action/3a029f04d76d32e79367c4b3255dda4d
I use a Hashids helper. I think this will do what you're after.
You can pass parameters to your functions like this:
base_url('account/profile/' . hashids_encrypt($this->user->id))
You can then decrypt it within the function and use it however you want:
$id = hashids_decrypt($id);

Share variable based on route group

I have 2 versions of a site. One is located in the root URL of the site and one is using a route prefix. They use the same resources but provide different links when accessed from the prefixed route:
Route::get('/', function(){
View::share('outgoing_url','something.com');
//regular links here
});
and a few more of the above pointing to different routes or
Route::group(array('prefix'=>'tour'), function(){
View::share('outgoing_url','somethingelse.com');
//different links here
});
View::share doesn't work since it uses whatever is assigned last so I am trying to find a solution for this problem.
Also, when I use HTML::link() in the views that go through the prefix, everything still points to the root URI of the site instead of the 'tour' prefix. Is there any way to differentiate between the two? Right now I am stuck with this problem and the only solution seems to be to make identical copies of the views and controllers responding to the routes. But that approach seems stupid to say the least.
I hope I explained the problem understandably.
HTML Macro:
<?php
HTML::macro('myLink', function($url, $title = null, $attributes = array(), $secure = null)
{
if (Request::segment(1) === 'tour')
{
$url = 'tour/'.$url;
}
return HTML::link($url, $title, $attributes, $secure);
});
?>
Usage:
HTML::myLink(...);
Just use a before filter - and set it that way
App::before(function($request)
{
if (Request::segment(1) === 'tour')
{
View::share('outgoing_url','tour.com');
}
else
{
View::share('outgoing_url','other.com');
}
});

Handle URL in CodeIgniter

I have a url like
"www.site.com/index.php/details/productname"
and I get 404 error on that link in codeigniter but the URL www.site.com/index.php/details/ is working fine. I want handle url parameter in seo manner.
You have to add /index/ segment in part of your url:
http://www.site.com/index.php/details/index/productname/
If you want to open url such like that http://www.site.com/index.php/details/productname/:
1) you need to define _remap() method:
public function _remap($method)
{
if ($method == 'index')
{
$this->viewDetails($this->uri->segment(2));
}
else
{
$this->default_method();
}
}
OR
2) use application/config/routes.php file
$route['details/(:any)'] = "products/viewDetails/$1";
From User-Guide:
routers.php
_remap method

Codeigniter Page cache with GET parameter

I am newbie to CI cache. I am facing some weird problem with codeigniter page caching. $this->output->cache(300);
I was expecting that cached version would not load if arguments in GET[] would change. But it is loading cache without considering any GET[] parameters.
I have one page where it says whether comment has been saved or not [via get parameter],
/product/product-name/?saved=true redirecting to same page where comment form is located. But it is not working. How can i invalidate old cache and create new one depending upon the get parameter? or i need to change the behavior of my comment system?
Thanks.
EDIT
Should i simply use database cache instead of Web page cache in this case?
You just have to enable the cache_query_string option in the config/config.php file.
$config['cache_query_string'] = TRUE;
Create a cache_override hook to check if there are any GET[] variables set and then skip the cache_override.
[EDIT #1]
Here is an example:
Create this file in your hooks directory:
<?php
class GetChecker {
public function checkForGet()
{
global $OUT, $CFG, $URI;
if (isset($_GET) AND ! empty($_GET))
{
return;
}
if ($OUT->_display_cache($CFG, $URI) == TRUE)
{
exit;
}
}
}
Then add this to the config/hooks.php:
$hook['cache_override'][] = array(
'class' => 'GetChecker',
'function' => 'checkForGet',
'filename' => 'GetChecker.php',
'filepath' => 'hooks'
);
I haven't tested it, it might need a little tweaking to work...
I test on CI 3+ , file system/core/Output.php 559 line, change this
if ($CI->config->item('cache_query_string') && !empty($_SERVER['QUERY_STRING']))
{
$uri .= '?'.$_SERVER['QUERY_STRING'];
}
on this
if ($CI->config->item('cache_query_string') /* && ! empty($_SERVER['QUERY_STRING']) */ && !empty($_REQUEST))
{
// $uri .= '?'.$_SERVER['QUERY_STRING'];
$uri .= '?'.http_build_query($_REQUEST);
}
And add string to your application/config/config.php
$config['cache_query_string'] = true;
it will be work with GET, POST, COOKIE ....
If need only GET, just $config['cache_query_string'] = true; - enough
I found no easier way using Hooks to prevent writing cache, as its calling _write_cache() inside the _display() method itself of CI_Output class.
For quick and easiest solution I added two conditions to display cache and write cache, if Query String parameter has variable defined( offset in my case, as I wanted for pagination)
Edit: system/core/Output.php
Add Condition to prevent writing cache, if specific GET parameter found:
function _write_cache($output)
{
if (isset($_GET['offset']) AND ! empty($_GET['offset']))
{
log_message('debug', " Don't write cache please. As as its matching condition");
return;
}
...
...
}
Add Condition to prevent displaying cache, if specific GET parameter found:
function _display_cache(&$CFG, &$URI)
{
if (isset($_GET['offset']) AND ! empty($_GET['offset']))
{
log_message('debug', " Don't display cache please. As as its matching condition");
return FALSE;
}
...
...
}

Resources