How can I create a dynamic URL in php? - 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]

Related

How to make codeigniter user profile url look pretty

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

SEO friendly URL's and querying a database php

I've searched for an answer to this question already and found an article relating to it but it does not give an exact answer. That can be found here: PHP - How can I replace dashes with spaces?
I am using this function to convert my blog titles into SEO friendly URL strings:
//SEO Friendly URLS
public static function Seo($input){
$input = str_replace(array("'", "-"), "", $input);
$input = mb_convert_case($input, MB_CASE_LOWER, "UTF-8");
$input = preg_replace("#[^a-zA-Z0-9]+#", "-", $input);
$input = preg_replace("#(-){2,}#", "$1", $input);
$input = trim($input, "-");
return $input;
}
which will convert titles like so "My Blog Title" to "my-blog-title", which is good. However I usually pass the blog ID in the URL to get the blog from the database, but I'm trying to keep really friendly urls.
I understand I can pass the blog ID as a second query string on the end of the title like mysite.com/page.php?post=my-blog-post&id=1 but that still looks bad. I WILL be using .htaccess to remove the .php and '?' from the URL's, but I am unsure how to keep a pretty URL while passing the ID too.
How can I query the database while using the blog title as the URL query?
URL friendly versions of titles are often referred to as slugs. If you store the slug in the database table you could use it to retrieve articles. It would be best to store the slug anyway so that once a slug is created it is never changed.
For example, let's say you find and fix a bug in the Seo function, there's a possibility that it could change your URL, which is obviously bad SEO. Storing the slug in the database avoids that issue.
If you store the slug, you'll probably want a slug for each blog category as well. This way you're more closely imitating a filesystem and would no longer have to ensure that every slug was completely unique. While it's unlikely you'd have articles with the same title in different directories, it's something to consider as you build your site.
You can use mod_rewrite module for Apache. This is the most common practice.
Using .htaccess rewrite rule
RewriteRule ^([^?]*) index.php?route=$1 [L,QSA]
URL http://example.com/en/my-life/first-impression
will be "rewritten" and passed to index.php as GET parameter route.
Exploded it in PHP by dashes.
$parts = explode('/', $_GET['route']);
This is how you will get all parts of url and make your PHP logic accordingly,
$parts[0] => language code
$parts[1] => category
$parts[2] => post SEO title

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.

PHP , htaccess: apply page title in URL

I want to apply the page HTML title in the URL
for example in here (stackoverflow) the url is something like that:
http://stackoverflow.com/questions/10000000/get-the-title-of-a-page-url
you can see the "get-the-title-of-a-page-url" part which is the page title
what i mean is when the user go to spowpost.php?post=1
the actual url that shows up when the pages load will be
spowpost.php?post=1$title=..the_title..
how can i do that?
EDIT: i was thinking about htaccess , but i don't know this very well so tutorial would help for this CERTAIN case..
You can use .htaccess for this. For example:
RewriteEngine On
RewriteRule ^questions/(\d+)/([a-z-]+) index.php?id=$1&title=$2 [L]
Your PHP page (index.php) receives the id and title as parameters in $_GET[]:
echo $_GET['title'];
// get-the-title-of-a-page-url
You can then use that (or the id, which is easier) to retrieve the correct item from your data source:
// Assuming you didn't store the - in the database, replace them with spaces
$real_title = str_replace("-", " ", $_GET['title']);
$real_title = mysql_real_escape_string($real_title);
// Query it with something like
SELECT * FROM tbl WHERE LOWER(title) = '$real_title';
Assuming you do have an id parameter in the URL of some sort, it's easier to query based on that value. The title portion can be used really only to make a readable URL, without needing to act on it in PHP.
In reverse, to convert the title to the format-like-this-to-use-in-urls, do:
$url_title = strtolower(str_replace(' ', '-', $original_title));
The above assumes your titles don't include any characters that are illegal in a URL...
$article_link = "http://example.com/spowpost.php?post=$postid&$title=$url_title";
Or to feed to .htaccess:
$article_link = "http://example.com/spowpost$postid/$url_title";
From what I understand, your title will be passed to the page as part of the URL. To show it in the title bar, put this in the section:
<?php $title=urldecode($_GET["title"]); echo "<title>$title</title>"; ?>
You might need to change parts of this, for instance dashes to spaces or something. If that is the case, use PHP's str_replace function: http://php.net/str_replace
Not sure about what's the problem you are facing but just according to what you say in your post the anwser would be:
1.You take the ID from the URL.
2.You search in your database for the original title
3. And then display it in the tag in the of your HTML.
Clarify if you have problem with any of the previous points.

Rewrite Youtube URL

I have some YouTube URLs stored in a database that I need to rewrite.
They are stored in this format:
$http://youtu.be/IkZuQ-aTIs0
I need to have them re-written to look like this:
$http://youtube.com/v/IkZuQ-aTIs0
These values are stored as a variable $VideoType
I'm calling the variable like this:
$<?php if ($video['VideoType']){
$echo "<a rel=\"shadowbox;width=700;height=400;player=swf\" href=\"" . $video['VideoType'] . "\">View Video</a>";
$}?>
How do I rewrite them?
Thank you for the help.
You want to use the preg_replace function:
Something like:
$oldurl = 'youtu.be/blah';
$pattern = '/youtu.be/';
$replacement = 'youtube.com/v';
$newurl = preg_replace($pattern, $replacement, $string);
You can use a regular expression to do this for you. If you have ONLY youtube URLs stored in your database, then it would be sufficient to take the part after the last slash 'IkZuQaTIs0' and place it in the src attribute after 'http://www.youtube.com/'.
For this simple solution, do something like this:
<?php
if ($video['VideoType']) {
$last_slash_position = strrpos($video['VideoType'], "/");
$youtube_url_code = substr($video['VideoType'], $last_slash_position);
echo "<a rel=\"shadowbox;width=700;height=400;player=swf\"
href=\"http://www.youtube.com/".$youtube_url_code."\">
View Video</a>";
}
?>
I cannot test it at the moment, maybe you can try to experiment with the position of the last slash occurence etc. You can also have a look at the function definitions:
http://www.php.net/manual/en/function.substr.php
http://www.php.net/manual/en/function.strrpos.php
However, be aware of the performance. Build a script which prases your database and converts every URL or stores a short and a long URL in each entry. Because regular expressions in the view are never a good idea.
UPDATE: it would be even better to store ONLY the youtube video identifier / url code in the database for every entry, so in the example's case it would be IkZuQ-aTIs0.

Categories