Encrypting url(parameters only) - codeigniter

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);

Related

Random unique ids

I'm trying to generate something like 6B6E23518 using randomString() which I'm calling inside my controller
function randomString($chars=10) //generate random string
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < $chars; $i++) {
$randstring .= $characters[rand(0, strlen($characters))];
}
return $randstring;
}
public function store(TicketsCreateRequest $request)
{
$ticket = $user->tickets()->create([
'ticket_hash' => $this->randomString(10),
// ....
]);
}
but this keeps on storing 0 into 'ticket_hash' and nothing gets generated??
Looking at your source code, is randomString() a public method of your controller class or is it a global function declared elsewhere outside of the class? I ask because it's entered above without the public visibility qualifier and with slightly different indentation to the method below it.
If this function is not an instanace method of your class, then your call to $this->randomString() is probably not calling the method you're expecting it to call. If your randomString() function is a global function defined elsewhere you should call it directly (eg. 'ticket_hash' => randomString(10),)
For what it's worth, for random strings like this it might be best to use the Laravel framework's Str class, only because it may be more stable and is definitely more widely used.
The Str::random() method achieves the output you're looking for in this case.
column ticket_hash was an integer type ,changed it to varchar and it works now.

How to create user-friendly and seo-friendly urls in codeigniter?

i want to change my codigniter url which looks like
http://dev.hello.com/about/updateVision/9
to
http://dev.hello.com/about/updateVision/this-is-test-edit/
i have no idea how to make looks like that anyone can help please
thanks !
This all depends on you database structure. I would introduce a field called reference or slug. This will contain a unique string for your record. When creating the record you can use the url_title function to remove spaces as mentioned by #Rooneyl
This reference must be unique so I would create a function that creates a reference in a loop, checks it against the database. When it returns false, it is unique.
public function unique_reference($name)
{
$name = trim(strtolower($name));
$unique_reference = url_title($name);
$counter = '';
do {
$result = $this->db->select('id')
->from('your_table')
->where('reference', $unique_reference)
->get()->row();
if ($result)
$counter++;
$unique_reference = url_title(trim("{$name} {$counter}"));
} while ($result);
return $unique_reference;
}
You can then retrieve record using this unique value

CodeIgniter URL_TITLE model?

Here is example of URl_title CI, i know this code is do this
$title = "Whats wrong with CSS";
$url_title = url_title($title, '_', TRUE);
// Produces: whats_wrong_with_css
But hot to revers, is there a function in Ci to reverse something like this and return the true value?
like this ?
// Produces: Whats wrong with CSS
hi you can do it just with simple way
$title = ucfirst(str_replace("_",' ',$url_tilte));
echo $title;
I would "extend" CI's URL helper by creating a MY_url_helper.php file in application/helpers and create a function similar to what umefarooq has suggested.
/*
* Un-create URL Title
* Takes a url "titled" string as de-constructs it to a human readable string.
*/
if (!function_exists('de_url_title')) {
function de_url_title($string, $separator = '_') {
$output = ucfirst(str_replace($separator, ' ', $string));
return trim($output);
}
}
Providing you have loaded the url helper, you will then be able to call this function throughout your application.
echo de_url_title('whats_wrong_with_css'); // Produces: Whats wrong with css
The second ($separator) paramater of the function allows you to convert the string dependent on whether it's been "url_title'd" with dashes - or underscores _

How to build an anchor in CodeIgniter where you want to change a variable that is already present in the URI?

Normally I would just use URL GET parameters but CodeIgniter doesn't seem to like them and none of the URL helper functions are designed for them, so I'm trying to do this the 'CodeIgniter way'.
I would like to build a page where the model can accept a number of different URI paramters, none necessarily present, and none having to be in any particular order, much like a regular URL query string with get parameters.
Let's say I have the following url:
http://example.com/site/data/name/joe/
Here not including the controller or the method there would be one parameter:
$params = $this->uri->uri_to_assoc(1);
print_r($params);
// output
array( [name] => [joe] )
If I wanted 'joe' to change to 'ray' I could do this:
echo anchor('name/ray');
Simple enough but what if there are more parameters and the position of the parameters are changing? Like:
http://example.com/site/data/town/losangeles/name/joe/
http://example.com/site/data/age/21/name/joe/town/seattle
Is there a way to just grab the URL and output it with just the 'name' parameter changed?
Edit: As per landons advice I took his script and set it up as a url helper function by creating the file:
application/helpers/MY_url_helper.php
Basically I rewrote the function current_url() to optionally accept an array of parameters that will be substituted into the current URI. If you don't pass the array the function acts as originally designed:
function current_url($vars = NULL)
{
$CI =& get_instance();
if ( ! is_array($vars))
{
return $CI->config->site_url($CI->uri->uri_string());
}
else
{
$start_index = 1;
$params = $CI->uri->uri_to_assoc($start_index);
foreach ($vars as $key => $value)
{
$params[$key] = $value;
}
$new_uri = $CI->uri->assoc_to_uri($params);
return $CI->config->site_url($new_uri);
}
}
It works OK. I think the bottom line is I do not like the 'CodeIgniter Way' and I will be looking at mixing segment based URL's with querystrings or another framework altogether.
You can use the assoc_to_uri() method to get it back to URI format:
<?php
// The segment offset to use for associative data (change me!)
$start_index = 1;
// Parse URI path into associative array
$params = $this->uri->uri_to_assoc($start_index);
// Change the value you want (change me!)
$params['name'] = 'ray';
// Convert back to path format
$new_uri = $this->uri->assoc_to_uri($params);
// Prepend the leading segments back to the URI
for ($i=1; $i<$start_index; $i++)
{
$new_uri = $this->uri->segment($i).'/'.$new_uri;
}
// Output anchor
echo anchor($new_uri);
I'd recommend wrapping this in a helper function of some sort. Happy coding!
Why not use CodeIgniter's built in URI Class? It allows you to select the relevant segments from the URL which you could use to create the anchor. However, unless you created custom routes, it would mean that your methods would need to accept more parameters.
To use the URI Class, you would have the following in your method:
echo anchor($this->uri->segment(3).'/ray');
Assuming /site/data/name are all CodeIgniter specific (/controller/method/parameter)
Now, I think this could be made a lot easier if you were using routes. Your route would look like this:
$route['site/data/name/(:any)'] = 'site/data/$1';
Effictively, your URL can be as detailed and specific as you want it to be, but in your code the function is a lot cleaner and the parameters are quite descriptive. You method would defined like this:
function data($name) { }
To extend your route to accept more parameters, your route for the the example URL "http://example.com/site/data/age/21/name/joe/town/seattle" you supplied would look like this:
$route['site/data/age/(:num)/name/(:any)/town/(:any)'] = 'controller/data/$1/$2/$3';
And your function would look like this:
function data($age, $name, $town) { }

Codeigniter, where to run model save code if not in the destructor?

I have a model that works with one user in the database.
It is designed to do a lot of small changes to the user, so instead of querying the database multiple times I decided to get all of the user's information in the constructor of the model, and then work on that information through out the rest of the model (so instead of updating the database, it would be updating the array I got). Then I would just save that array back to the database in the destructor.
This works fine, but I've been reading a bit more, and it turns out you shouldn't run any non-cleanup code in the destructor (which is where I'm running the update query to the database). So I was curious, is there a better way to do this? Am I missing a better solution?
Thanks, Max
EDIT:
Here is an example of what I am doing (Note: This example is a shopping cart class, not a user class though):
<?php
class cartmodel extends CI_Model
{
private $sessionPrefix = 'Cart_';
private $CartCache = array();
function __construct ()
{
if ($this->session->userdata($this->sessionPrefix.'data') === FALSE)
$this->session->set_userdata($this->sessionPrefix.'data', array());
$this->CartCache = $this->session->userdata($this->sessionPrefix.'data');
parent::__construct();
}
function __destruct ()
{
$this->session->set_userdata($this->sessionPrefix.'data', $this->CartCache);
}
function AddItem ($id, $count)
{
if ($count == 0 || $count == '' || !is_numeric($count))
return;
if (!isset($this->CartCache[$id]))
$this->CartCache[$id] = 0; //Initialize it so that += works
$this->CartCache[$id] += (int)$count;
}
?>
You can directly manipulate session data in your AddItem() method. Something like this:
function AddItem ($id, $count)
{
// UPDATE CartCache VARIABLE
$this->CartCache = $this->session->userdata($this->sessionPrefix.'data');
// YOUR CODE BELOW
if ($count == 0 || $count == '' || !is_numeric($count))
return;
if (!isset($this->CartCache[$id]))
$this->CartCache[$id] = 0; //Initialize it so that += works
$this->CartCache[$id] += (int)$count;
// SAVE CartCache IN SESSION AGAIN
$this->session->set_userdata($this->sessionPrefix.'data', $this->CartCache);
}
This way if you want to manipulate the Cart_data session variable in other methods, you can still do it. Just update the CartCache array in every method and save it again to the session variable once you've done manipulating data in it.

Resources