How to find the last instance of a character - php

I'm building this real estate script using PHP and I want the listing page url's to be like /listing/this-is-the-title-436. This url is generated in PHP and the last part of the url, after the last instance of ' - ' is the listing id. But I cannot find a way to find the last instance of a dash and use the rest as a variable in .htaccess.
Note that the title can have any amount of spaces therefore any amount of dashes but the listing id will always be at the end, after the last dash.
To summarize, I want urls like /listing/this-is-the-title-436 to redirect to /assets/inc/listing.php?listing=436 with .htaccess.
Any help would be appreciated, thanks!

The easiest way is to test a numerical value at the end:
RewriteEngine on
RewriteRule ^listing/.+-(\d+)$ /assets/inc/listing.php?listing=$1 [L,QSA]
But if you're not just using numeric values, you can also test for the absence of - in the last part:
RewriteRule ^listing/.+?-([^-]+)$ /assets/inc/listing.php?listing=$1 [L,QSA]

Related

Grabbing a domain name from URL as a variable by htaccess

Imagine in my website I want to show some analytic about domains, working URL example of what I need:
http://whois.domaintools.com/google.com
As you see in the above URL, it's handling google.com as a variable and pass it to another page to process the given variable, that's exactly what I want.
So for detecting that kind of variable, here is my regex:
/^[a-zA-Z\d]+(?:-?[a-zA-Z\d])+\.[a-zA-Z]+$/
The above RegEx is simple and accepts everything like: google.com, so in my .htaccess file I have:
RewriteRule (^[a-zA-Z\d]+(?:-?[a-zA-Z\d])+\.[a-zA-Z]+$) modules/pages/page.php?domain=$1
The above rule do what I want, but it also redirects my homepage to page.php while there is nothing in the URL, forexample: http://mysitename.com is now being forwarded to page.php
How can I fix this?
Thanks in advance
It redirects also the base domain to page.php because of the regex. You are using the + on all places, the meaning of the plus is "Matches the preceding pattern element one or more times.". (http://en.wikipedia.org/wiki/Regular_expression) If you request the homepage, it redirects because all the elements are appearing zero times, like you defined in the regex.
Instead of the + you should define a minimum and a maximum amount of characters (so the zero occurrences are not evaluated). BTW, a quick search in google for "regex domain" will output a lot of results, which are tested. Use the following for example:
RewriteEngine on
RewriteRule (^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$) modules/pages/page.php?domain=$1
Reference:
Domain name validation with RegEx
Update 1:
If you want to use your own regex, exchange the last "+" with {2,}. The top-level domains have usually at least 2 characters.
RewriteEngine on
RewriteCond %{REQUEST_URI} !(\.html|\.php|\.pdf|\.gif|\.png|\.jpg|\|\.jpeg)$
RewriteRule (^[a-zA-Z\d]+(?:-?[a-zA-Z\d])+\.[a-zA-Z]{2,}$) modules/pages/page.php?domain=$1

How to load a specific page for any given pathname URL

Let's say I have a web-page called www.mysite.com
How can I make it so whenever a page is loaded like www.mysite.com/58640 (or any random number) it redirects to www.mysite.com/myPHPpage.php?id=58640.
I'm very new to website development so I don't even really know if I asked this question right or what languages to tag in it...
If it helps I use a UNIX server for my web hosting with NetWorkSolutions
Add this to your .htaccess file in the main directory of your website.
RewriteEngine on
RewriteBase /
RewriteRule ^([0-9]+)$ myPHPpage.php?id=$1 [L]
Brief explanation: it says to match:
^ from start of query/page
[0-9] match numbers
+ any matches of 1 or more
$ end of page requested
The parentheses part say to look for that bit and store it. I can then refer to these replacement variables in the new url. If I had more than one parentheses group then I would use $2, $3 and so on.
If you experience issues with the .htaccess file please refer to this as permissions can cause problems.
If you needed to capture something else such as alphanumeric characters you'd probably want to explore regex a bit. You can do things such as:
RewriteRule ^(.+)$ myPHPpage.php?id=$1 [NC, L]
which match anything or get more specific with things like [a-zA-Z0-9], etc..
Edit: and #Jonathon has a point. In your php file wherever you handle the $_GET['id'] be sure to sanitize it if used in anything resembling an sql query or mail. Since you are using only numbers that makes it easy:
$id = (int)$_GET['id']; // cast as integer - any weird strings will give 0
Keep in mind that if you are not going to just use numbers then you will have to look for some sanitizing function (which abound on google - search for 'php sanitize') to ensure you don't fall to an sql injection attack.

Add - instead of white spaces in url rewriting

I have this url:
http://www.site.com/en/about.php?id=112&name=andrew marshall dickens
and i would like to rewrite it like this:
http://www.site.com/112/andrew-marshall-dickens.html
so far:
RewriteRule ^([^/]*)/([^/]*)\.html$ /en/about.php?id=$1&name=$2 [L]
I'm having trouble with the '-' character.Any suggestions ? Thanks!
Well you're attempting to use a Regex to remove characters from the middle of a string which could have any number of that character in it in the middle of a RewriteRule. On one hand that's not really possible, on the other hand, you're passing the ID in, so I assume you can get the name using the id in your PHP script, so there's not really a need to parse the name from the URL variables, and as a 3rd option, why not just str_replace the - characters in PHP and ucwords() the string before outputting it if you want to use the name variable?
I believe you don't need to pass name param because id can get that.
Anyway:
RewriteRule ^([0-9]+)/([a-z-]+)\.html$ /en/about.php?id=$1&name=$2 [L]
But hey, reading the comment, i just realized: what's your problem? Your regex should already work

php & .htaccess clean url problem

i wanna use clean url for my site but i have an big problem!
i have urls like :
index.php?lang=en&mod=product&section=category
index.php?lang=en&mod=product&caption=fetch&id=45
index.php?lang=pe&mod=blog&section=category&id=560
index.php?lang=pe&mod=blog&section=category&id=564
index.php?lang=pe&mod=blog&section=category&id=567
index.php?lang=pe&mod=blog&section=category&id=571
index.php?lang=pe&mod=blog&id=556
index.php?lang=pe&mod=page&id=537
index.php?lang=pe&mod=blog&id=558&o_t=cDate_ASC
index.php?lang=pe&mod=product&caption=fetch&id=7804
As you see i have a problem that my varibale's order is diference toghether and my 3rd or 4th variable are not stable sometimes it's id or sometimes is caption.
i want to set my template url to ( e.g en/product/category ) but when i want to set it in .htaccess it's not clear that theird depth is "id" or is "caption" !
do i should put all variables in my url like this ? :
index.php?lang=en&mod=product&section=category
|
|
|
V
index.php?lang=en&mod=product&section=category&caption=&id=&o_t=&v_t=&offset=
EDIT :
So i use smarty as my template engine.i should change my link address in templates like my clean url ( e.g en/product/category/324 ) . my problem is when i set a link to en/product/34 or en/product/category/23 according to my .htaccess rewrite rules it's not clear that 3rd part is id or category
in this case :
RewriteRule ^/(en|pe)/(product|blog|page)/(category)/([0-9]{1,})/$ index.php?lang=$1&mod=$2&section=$3&id=$4
3rd variable is category an .htaccess define 3rd part as category but as you can see sometimes url has not category and instead of it has id !
My big problem is this
You'd need to make a few rewrite rules I think.
E.G.
RewriteRule ^/(en|pe)/(product|blog|page)/([0-9]{1,})/$ index.php?lang=$1&mod=$2&id=$3
Would rewrite index.php?lang=en&mod=page&id=22 to /en/page/22 (so long as ID was > 1 character)
RewriteRule ^/(en|pe)/(product|blog|page)/(category)/([0-9]{1,})/$ index.php?lang=$1&mod=$2&section=$3&id=$4
Would rewrite index.php?lang=en&mod=blog&section=category&id=22 to /en/blog/category/22
You may need to fiddle with the ^/ at the start depending on if you have a RewriteBase set or not.
EDIT:
Explanation:
^ indicates the starting position
of the URL from the base i.e.
site.com/(whatever here is in the
URL)
(en|pe) means that first
value in that particular rule can be
EITHER en OR pe. To add more is easy
(en|pe|ru|jp) etc. Same goes for the
product/blog/page part. I included
(category) just incase you had other
'section' types that were not
'category'.
[0-9] is any
numeric character 0 to 9. {1,} means
1+ character in length. If you want
between 2 and 4, do {2,4} for
example. Exactly 3 characters? {3}.
It's useful when targetting specific
things.
$ Means the end of the matched
string. If you intend on having
nothing after the id except a /
(could even remove that /) then use
that example as is. If you intend on
having a title of a blog past
afterward, you can do (.*)$ which
means anything can be after the page
id e.g.
/en/blog/category/22/oheyoheyoheyohey
would be the same as
/en/blog/category/22/abcjhrefgwgrjurgh.
If you pass the title as a parameter
&title=this is the title, just do the
same thing as I did in the example
for ID except use [a-zA-Z0-9-+_.] to
include alphanumeric characters, +,
-, _, .
$1 is the order of the paranthesis arguments in the
first argument of the rule. E.G. $1
refers to (en|pe), so lang can either
be en or pe.
IF you want the rule to apply to multiple pages, and not just the index.php, make it:
RewriteRule ^/([a-zA-Z])/(en|pe)/(product|blog|page)/([0-9]{1,})/$ $1.php?lang=$2&mod=$3&id=$4
So in that case, site.com/blah/en/product/22 would relate to site.com/blah.php?lang=en&mod=product&id=22
Why should you do so? I see no problems with your urls, normal user does not mind and those who inspet your site can read it all without problems ...
You have to agree on some ordering of parameters, and use mulitple rewrite rules.
For the order lang > mod > section > caption > id > o_t > v_t > offset you want to have something like this:
RewriteRule ^/(\w+)$ index.php?lang=$1
RewriteRule ^/(\w+)/(\w+)$ index.php?lang=$1&mod=$2
RewriteRule ^/(\w+)/(\w+)/(\w+)$ index.php?lang=$1&mod=$2&section=$3
RewriteRule ^/(\w+)/(\w+)/(\w+)/(\w+)$ index.php?lang=$1&mod=$2&section=$3&caption=$4
RewriteRule ^/(\w+)/(\w+)/(\w+)/(\w+)/(\d+)$ index.php?lang=$1&mod=$2&section=$3&caption=$4&id=$5
...
and so on
Above, I assume lang, mod, section and caption are made up of alphabet characters (no digits or special chars), and the id is made of digits.
The real file index.php does not care about the order of variables in the query string, or if a value is missing, because it receives couple with name-value: the right association is ensured by the presence or absence of the full couple.
To be clear, for index.php is the same if the query string is "?lang=en&mode=blog" or "?mode=blog&lang=en" or if it is only "?lang=en", because the variables are managed inside the script by use of the $_GET associative array, independently by their order or presence inside the array.
What is important is that you plan a correct order of variables inside the new virtual URL's to rewrite because they contain only the variable content, while the variable name is taken from the position inside the virtual URL. That is (note this is pseudo-code):
yourdomain/val1/val2/val3/...etc
to be rewritten in:
index.php?var1=val1&var2=val2&var3=val3&...etc
so in the new URL's you are going to plan, there cannot be missing values.
You can solve this problem by assigning fake values to the missing variables that will not be taken as valid by your script.
As example, if the mode variable is missing, you can put in that position a string that will not be considered valid by the script, so to be managed as if it was empty.
If you have an array of allowed values, you can just add a control *if (in_array())* instead of (or other than) if(empty()).
When you build the links to other page, you can just add this control for a missing value:
*if (empty(val3)) val3 = 'fake_value';*

PHP - How to add a pages title to the URL? And how to create a clean url using PHP

I was wondering how can I create clean urls using PHP. Do I do this all in PHP or do I need to use mod_rewrite in some way? Can someone explain this to me in laymans terms?
Here is my current url a element link and how it looks in the browser
http://www.example.com/members/1/posts/page.php?aid=123
But I want it to read the pages title.
http://www.example.com/members/1/posts/title-of-current-page/
First you need to generate "title-of-current-page" from PHP, using this function eg:
function google($string){
$string = strtolower($string);
$string = preg_replace('/[^a-zA-Z0-9]/i','-',$string);
$string = preg_replace("/(-){2,}/",'$1',$string);
return $string;
}
Second thing, you need to make a rewrite, but you should keep aid in form of "/123-title-of-current-page"
Rewrite would go something like this (I am ignoring your entire URL)
RewriteRule ^([0-9]+)-(.*?)$ page.php?aid=$1 [L,QSA]
You can do this using mod_rewrite:
You'll need to edit a file called .htaccess at the top level of your web folder. This is where you can specify certain settings to control the way Apache accesses items in this folder and below.
First things first. Let's turn on mod_rewrite: RewriteEngine On
RewriteRule ^([a-z]+)/([a-z\-]+)$ /$1/$2.php [L]
The rule matches any URL which is formed of lower case letters, followed by a /, then more lower case letters and/or hyphens, and appends .php to the end. It keeps track of anything wrapped in brackets () and refers to them later as $1 and $2, i.e. the first and second match. So if someone visits these URLs:
http://example.com/weblog/archive
it will be converted to following:
http://example.com/weblog/archive.php
You will find more details on :
http://wettone.com/code/clean-urls
You have to use a rewrite to direct all requests to an existing php file, otherwise you get all 404 not found errors because you are trying to get a page that simply is not there.
Unless you rewrite your 404 page to handle all requests and you definitely donĀ“t want to go there...

Categories