How to make codeigniter user profile url look pretty - php

I am trying to figure out the best way to make a nice looking profile URL in codeigniter.
Normally i would just like to a controller with a third url paramter (the profile id) like so:
http://thesite.com/profile/4
======
This isn't going to work for the site i'm building now because I want a nice looking url with the company name, like so:
http://thesite.com/profile/some-company-name
=======
Their are 2 problems with this and maybe i'm just not thinking straight today and the answer is obvious, but if the url is a hyphenated version of the company name, if 2 of the same company are in the database for some weird reason, then the profile might not be the correct one, really the only good way is to provide a profile id and pull by the id, but then my url doesn't look good...
How would you handle this situation? I guess i could always link to /profile/id and then in the controller just look up the profile and redirect to /profile/company-name, but then the user that went to the site and typed in /profile/company-name would get a 404 page.
Any good ideas for me?

Just check the guide, it shows you with the URL Helper:
Setup a model to handle your getter / setter (for profile name).
Getter gets the proper content to display, setter sets the profile name and handles duplicates (same names by adding a 1 etc;). Think of a createive way to eliminate collisions, addding state name or zip if you don't want something ugly.
Use url_title() to handle clean urls and eliminate odd characters:
$title = "What's wrong with CSS?";
$url_title = strtolower(url_title($title));
// Produces: whats-wrong-with-css

use urlencode and urldecode of php and routing
add in route.php in config
$route['profile/(:any)'] = "controller_link/$1";
then you can use urldecode on your controller file like
public function controller_link($name=FALSE)
{
if ($name != FALSE) {//check if name is passed
$queryname = urldecode($name);
//then query on that name in the database
}
}
if not clear then add comment.

Use unique name of company in Database, search your company by name, i use this function (helper) to translate name in slug.
if(!function_exists('slug')){
function slug($text)
{
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
return (!empty($text)) ? $text : FALSE ;
}
}

Related

How can I create a dynamic URL in php?

I am new in PHP and MySQL.
Here's what I've tried so far and I can't understand how to make URL with PHP.
What I want to do is to create a dynamic web page about a particular book. I already created and have some data in my MySQL database to play with.
I've got a function to clear the special characters in the book titles.
function seo($s) {
$tr = array('ş','Ş','ı','İ','ğ','Ğ','ü','Ü','ö','Ö','Ç','ç');
$eng = array('s','s','i','i','g','g','u','u','o','o','c','c');
$s = str_replace($tr,$eng,$s);
$s = strtolower($s);
$s = preg_replace('/&.+?;/', '', $s);
$s = preg_replace('/[^%a-z0-9 _-]/', '', $s);
$s = preg_replace('/\s+/', '-', $s);
$s = preg_replace('|-+|', '-', $s);
$s = trim($s, '-');
return $s;
}
Example
echo seo($booktitle);
.htaccess
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^/(.*)-(.*)$ /book.php?id=$1 [L,NC]
Link type
echo "<a href='http://sitename.com/".$bookid."-".seo($booktitle)."'>".$booktitle."</a>";
Output I want
http://sitename.com/id-book-title
The thing is, I don't understand how I can pass the $bookid from the url to the php itself dynamically. I think I need to retrieve book_id from my database and assign it to $bookid variable, is that correct? But how can I connect it to the URL?
For instance, when I type the url http://sitename.com/5-the-trial I need to get the page for the book that has the id of 5.
What's missing here? Can you guide me to the right direction to create dynamic urls? I am both in need of guidance (learn this, search that, etc) and a specific answer to my question, if that's possible.
Its not quite clear what your asking. If you want to create a page that lists the urls of your books, then you are not far off with your echo statement. You just need to populate $bookid and $booktitle from the database. .htaccess is not involved.
echo "<a href='http://sitename.com/".$bookid."-".seo($booktitle)."'>".$booktitle."</a>";
But if you want to unpack the URL of the link the user clicked, then you need to look at the query string passed to the page. .htaccess breaks up the URL for you and passes the $1 parameter into your script. To read the url in PHP try the following
parse_str($_SERVER['QUERY_STRING'],$query);
if (array_key_exists('id',$query)) {
$books = explode("-",$query['id']);
}
This will create an array with the book id in the first element ($books[0]), and the first word of the title in the second etc. (If you wanted to use this approach and have the whole title in the second you might want to use a different character to delimit the id from the title to the character you use to replace spaces.
Replace your rewrite rule to this:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^([^-]+)-(.+)$ /book.php?id=$1 [L,QSA]

How to format url for database query

I'm new here I and need your help.
I started playing with .htaccess and php and I came across a problem.
When doing url rewriting, I pass into the url a string which is the title of an article extracted from the database. The problem is that the string(title) has a lot of characters who in the url are misspelled. EG: localhost/news/php%5%is%out
Here % are the blank spaces. I tried to format every title with preg_replace and I replaced every space with '-' but there are a lot of characters and I wanted to know if there is any way of doing this without preg_replace so any string can be good for a query.
In news.php I get the string from the url and I use it for the query in the database from which I extract the body of the entire article.
RewriteRule ^news/([a-zA-Z0-9._]+)/?$ /news.php?news_title=$1
This is my .htaccess file so in the news.php i get the 'news_title' variable through $_GET and then query the database to find the articol with this title.
So my question is, am I doing this all wrong? Is there any other way of doing this? I started working with htaccess only 2 days ago and I want to make my urls more friendly.
I hope my question is clear.
Thank everyone who helps me.
Just for an example, this is what I use to transform the normal tile in a string that won't be change with symbols(;amp, %, ?, etc) in the url
function generateUrl($url) {
$v1 = preg_replace("/[\s\:\;\,\_\'\`\"\?\!\%\(\)\+\=\#\#\[\]\{\}\/]/", "-", $url );
$v2= preg_replace('/[-]{2,}/', '-', $v1);
$v3 = preg_replace('/^[-]/', '', $v2);
$final = preg_replace('/[-]$/', '', $v3);
return $final;
}
I think the answer for your problem is here URL Friendly Username in PHP?. When you add article to the table, use this function (Slug) to convert article title and store converted title in column "slug". When user enters the address (.....)/article.php?name=some-title, use $slug = $_GET['title'] and find article by a slug. Before you save article you should check whether the article with this slug exists. If exists add to slug some number and then save to db. You can't allow to exists two record with the same slug in the table.

Handle slash ('/') in a URL CodeIgniter

I am creating a site using CodeIgniter. I have an url like http://mysite.com/albums/MJ/Dangerous.html where MJ is the artist name and Dangerous is the name of the album. Both of these are dynamic and fetched from a database.
In the database there are some albums which have a slash ('/') character in them. So, such an URL becomes http://mysite.com/albums/50-cent/Get+Rich+or+Die+Tryin%27%2FThe+Massacre.html. On decoding, it turns out as http://ringtones/albums/50-cent/Get Rich or Die Tryin'/The Massacre.html. Here the artist is 50-cent and the album name is Get Rich or Die Tryin'/The Massacre
My question is, what do I do so that I get the entire album name, i.e. Get Rich or Die Tryin'/The Massacre.html as a single argument with the slash character? Currently CodeIgniter shows an error as "Page not found" when I click on such an URL. All other URL's which doesn't have the / works fine.
Try double URLencoding the album name (i.e. urlencode(urlencode($album))). I was trying to pass a URL once to a CodeIgniter controller and it constantly gave me troubles. So I just double encoded it, and then it popped through on the other side no problem. I then ran an urldecode() on the passed parameter.
Let me know if that helps you.
As per current SEO trend no need to bring the quote in url or to fetch on page.
instead during saving (in slag kind of field) and retrieving you can use this kind of option.
$base_url = "http://ringtones/";
$controller = "albums";
$artist = "50 cent";
$album = "Get Rich Or Die Tryin' / The Massacre";
$link1 = $base_url.$controller.'/'.url_title($artist,'-',TRUE).'/'.url_title($album,'-',TRUE);
echo $link1;
Result:
http://ringtones/albums/50-cent/get-rich-or-die-tryin-the-massacre
encode the value before passing
$value = str_replace('=', '-', str_replace('/', '_', base64_encode($album)));
decode the value after receiving
$value = base64_decode(str_replace('-', '=', str_replace('_', '/', $value)));
You will want to urlencode the album name when the data is retrieved from the model so that blackslash is escaped.
You need to use the HTML escaped version of the characters in your URL...
See below for a reference.
http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
After HTML encoding, your URL should look something like:
http://ringtones/albums/50-cent/Get Rich or Die Tryin'/The Massacre.html
I hope this helps!
N
Extending the #MikeMurko answer to include how to work with Javascript and PHP.
Simply go for double encoding and decoding;
JS:
var id = encodeURIComponent( encodeURIComponent('mystring/&-34') );
PHP:
$id = urldecode( urldecode('mystring/&-34') );

take facebook page url and store id and slug separately

I'm developing a web app where users enter their facebook page url either in this format:
http://www.facebook.com/pages/Graffiti/119622954518
or
http://www.facebook.com/thefirkinandfox
With php - how do I detect which format automatically, then split (explode?) the parts (the slug and the id or just the slug if the second version).
There is sometimes query data at the end of the url when viewing your own facebook page as an administrator, how do I detect and remove that? I think the answer will be regex of some kind - but I've really only used this to make sure an input is email and still didn't understand it that well... thanks in advance.
Possible entires may or may not include http:// at the beginning... I'd like to account for this...
If you want to use one regexp, try this:
$url = 'www.facebook.com/pages/Graffiti/119622954518';
if(preg_match('#^(https?://)?(www\.)?facebook\.com/((pages/([^/]+)/(\d+))|([^/]+))#', $url, $matches)) {
$slug = isset($matches[5]) ? $matches[5] : (isset($matches[7]) ? $matches[7] : null);
$id = isset($matches[6]) ? $matches[6] : null;
}
Two parts:
^http://www.facebook.com/pages/([^/]+)/([^/]+)(?:\?.*)$
If the first one doesn't match, use this:
^http://www.facebook.com/([^/]+)(?:\?.*)$
The explosion, you mention is the value of the capturing group.
So the code might look something like this:
$subject = "my string";
if (preg_match ('#^http://www.facebook.com/pages/([^/]+)/([^/]+)(?:\?.*)$#', $subject))
print ($groups[1] + ' ' + $groups[1]);
else if (preg_match ('#^http://www.facebook.com/([^/]+)(?:\?.*)$#', $subject))
print ($groups[1]);

Is there a generic way to route URLs in Kohana when there is the hyphen character in them?

Kohana automatically sets up URLs like so
http://www.example.com/controller/method/argument1/argument2/etc
Now I like to use the dash to separate my words in the URL, and I have an address like so
http://www.example.com/business-hub
My controller is titled BusinessHub_Controller. What is annoying me, is for /business-hub/ to match the BusinesHub controller, I need to add a custom entry into the routes.php under the application/config folder. It also seems I have to add one for every method, which is really annoying. For example, here is an excerpt,
$config['business-hub'] = 'businesshub/index/';
$config['business-hub/logout'] = 'businesshub/logout';
$config['business-hub/media-releases'] = 'businesshub/mediareleases';
Obviously, this is really annoying. Is there anyway I can tell Kohana to convert the URL into the camelCase name, something like
$urlController = 'business-hub';
$correctController = str_replace('-', ' ', $urlController);
$correctController = ucwords($correctController);
$correctController = str_replace(' ', null, $correctController);
$correctController = $correctController . '_Controller';
Rather than just stripping out dashes, I'd convert them to underscores; and I'd do it using a hook. Make sure hooks are enabled in config/config.php and then create a file in hooks called, say, dashes_to_underscores.php:
function convert_dashes_to_underscores_in_url()
{
Router::$current_uri = str_replace('-', '_', Router::$current_uri);
}
Event::add_before(
'system.routing',
array('Router', 'setup'),
'convert_dashes_to_underscores_in_url');
For the camelCase variant I don't know but something like this should work
$config['(a-z)+-?(a-z)*/(a-z)+-?(a-z)*'] = '$1$2/$3$4';
As the route part in kohana is a regular expression.
Of course this is severly limited to the cases provided by you.

Categories