Rewriting a URL of a custom page - php

I've made a page /module/hello/?id_category=123, and I need to make the id_category rewritten to a name such as 123 would = abc.
Is there a way to achieve this without making 1000 manual redirects in the htaccess?
I know this can be done with a RewriteRule [L], but as far as I know you can't ask the database to convert the id to a name and then tell htaccess to rewrite the URL.
Thanks,
Luke

Use the below function and add id_category as string, stringToNumURL function returns you it's numeric mapping.
Then just include your URL content like this.
<?php
//http://mypage.com/module/hello/?id_category=abc
$str_arr = stringToNumURL($_GET['id_category']); //return 123
include_once("http://mypage.com/module/hello/".$str_arr);
function stringToNumURL($url){
$arr = array('a','b','c');
$arr_values = array_flip($arr);
$url = str_split($url);
$url_to_call="";
foreach ($url as $value) {
$url_to_call.=$arr_values[$value]+1;
}
return $url_to_call;
}

Related

Modify function getdomain, would need it without subdomain in PHP

I would need help with my code:
I have a function which only replaces thee www. with a blank space.
For example:
If I add the url: www.testek.com
The user will see testek.com
But if I add the url: s.dada.testek.com
The user will see s.dada.testek.com
So if we use the domain s.dada.testek.com I would like that the end user sees only testek.com.
But I would like to get only the main domain without any subdomains.
Code:
function getdomain($url){
$parsed = parse_url($url);
return str_replace('www.','', strtolower($parsed['host']));
}
I saw a post but it won't work for me.
Thanks for the help!
Now I've changed the code to:
function getdomain($url){
$parsed = parse_url($url);
$bits = explode(".",$parsed["host"]);
$mainDomain = array_filter($bits, function ($i) use ($bits) {
return $i >= count($bits)-2;
}, array(
'www.rover.ebay.com' => 'ebay.com',
's.click.aliexpress.com' => 'aliexpress.com', );
return implode(".", $mainDomain);
}
Am I thinking the right way?
Because now the end user sees like this:
http://i.stack.imgur.com/JddKB.jpg
If you simply want to get the last 2 segments of a URL main domain name then you can do the following:
function getdomain($url){
$parsed = parse_url($url);
$bits = explode(".",$parsed["host"]);
$mainDomain = array_filter($bits, function ($i) use ($bits) {
return $i >= count($bits)-2;
}, ARRAY_FILTER_USE_KEY );
return implode(".", $mainDomain);
}
See how it works in https://eval.in/636860
Unfortunately most of the times there's no "catch all" solution and you have to do a lot of hard-coded things. e.g. the UK has .co.uk but France just .fr so depending on that you may need the last 3 or even 4 segments.
I've fixed it like this:
function getdomain($url){
$parsed = parse_url($url);
$replace = array ("rover.", "www.", "s.click.");
return str_replace($replace,'', strtolower($parsed['host']));
}
I've created an array with the "subdomains" which I don't want to be shown.
And now it works ok.
apokryfos thanks for your support and for opening my mind :)

Delete URI Segment in Codeigniter

I want to remove some url in CI
if any echo like:
www.blabla.co/content/5DRwA/6Yt54/bla-bla
so, replace to:
www.blabla.co/content/bla-bla
nb: 6Yt54 and 5DRwA is a random value
How I remove URI Segment 2 from behind like that?
How can I solve it?
Try the uri class. First retrive uri with:
$array = $this->uri->segment_array();
Then remove second segment:
unset($array[2]);
Unfortunately your url doesnt seem to follow CI convention (you could use then $this->uri->assoc_to_uri($array)). So iterate over array to create uri.
$my_uri = ''; //better name it $my_uri not to conflict with $this->uri
foreach ($array as $value) {
$my_uri.= '/'.$value;
}
And then you can use your new uri f.e. to redirect:
redirect($uri);

PHP: How can i read the second part of URL

How can I take out the part of the url after the view name
Example:
The URL:
http://localhost/winner/container.php?fun=page&view=eims
Extraction
eims
This is called a GET parameter. You can get it by using
<?php
$view = $_GET['view'];
If this is for a URL which is not part of your website (e.g. Not your domain), but you wish to parse it. Something like this will work
$url = "http://example.com/index.php?foo=bar&acme=baz&view=asdf";
$params = explode('?', $url)[1]; // This gets the text AFTER the ? Note: If using PHP 5.3 or less, this may not work. You would then need to split it into two lines with the [1] happening on $params.
$pairs = explode('&', $params);
foreach($pairs as $p => $pair) {
list($keys[$p], $values[$p]) = explode('=', $pair);
$splits[$keys[$p]] = $values[$p];
}
echo $splits['view'];
<?php echo $_GET['view']; ?> //eims
If that's current URL, the simple and rock solid approach is to use the filter functions:
filter_input(INPUT_GET, 'view')
Otherwise, you can use parse_url() with PHP_URL_QUERY as second argument. The resulting string can be split with e.g. parse_str().
Are sure you are writing this "echo $_GET['view'];" in the container.php file?
Maybe write why do you need that "view".

parsing SEO friendly url without htaccess or mode_rewrite

Can anyone suggest a method in php or a function for parsingSEO friendly urls that doesn't involve htaccess or mod_rewrite? Examples would be awesome.
http://url.org/file.php/test/test2#3
This returns: Array ( scheme] => http [host] => url.org [path] => /file.php/test/test2 [fragment] => 3 ) /file.php/test/test2
How would I separate out the /file.php/test/test2 section? I guess test and test2 would be arguments.
EDIT:
#Martijn - I did figure out what your suggested before getting the notification about your answer. Thanks btw. Is this considered an ok method?
$url = 'http://url.org/file.php/arg1/arg2#3';
$test = parse_url($url);
echo "host: $test[host] <br>";
echo "path: $test[path] <br>";
echo "frag: $test[fragment] <br>";
$path = explode("/", trim($test[path]));
echo "1: $path[1] <br>";
echo "2: $path[2] <br>";
echo "3: $path[3] <br>";
echo "4: $path[4] <br>";
You can use explode to get the parts from your array:
$path = trim($array['path'], "/"); // trim the path of slashes
$path = explode("/", $path);
unset($path[0]); // the first one is the file, the others are sections of the url
If you really want to make it zerobased again, add this as last line:
$patch = array_values($path);
In response to your edit:
You want to make this as flexible as you can, so no fixed coding based on a max of 5 items. Although you probably will never exceed that, just don't pin yourself to it, just overhead you dont need.
If you have a pages system like this:
id parent name url
1 -1 Foo foo
2 1 Bar, child of Foo bar-child-of-foo
Make a recursive function. Pass the array to a function which takes the first section to find a root item
SELECT * FROM pages WHERE parent=-1 AND url=$path[0]
That query will return an id, use that in the parent column with the next value of the array. Unset each found value of the $path array. In the end, you will have an array with the remaining parts.
To sketch an example:
function GetFullPath(&$path, $parent=-1){
$path = "/"; // start with a slash
// Make the query for childs of this item
$result = mysqli_query($conn, "SELECT * FROM pages WHERE parent=".$parent." AND url=".current($path)." LIMIT 1");
// If any rows exists, append more of the url via recursiveness:
if($result->num_rows!==0){
// Remove the first part so if we go one deeper we start with the next value
$path = array_slice($patch,1); // remove first value
$fetch = $result->fetch_assoc();
// Use the fetched value to go deeper, find a child with the current item as parent
$path.= GetFullPath($path, $fetch['parent']);
}
// Return the result. if nothing is found at all, the result will be "/", probs home
return $path;
}
echo GetFullPath($path); // I pass it by reference, any alterations in the function happen to the variable outside the scope aswell
This is a draft, I did not test this, but you get the idea im trying to sketch. You can use the same method to get the ID of the page you are at. Just keep passing the variable back up again c
One of these days im getting the hang of recursiveness ^^.
Edit again: Oops, that turned out to be quite some code.

Add/Replace URL GET parameter depending on current URL

I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.
The problem consists of this:
I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”
Male
Female
Front
Back
Now, the users can filter this by either viewing the male or female model but they can also filter by viewing front or back of both gender.
I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.
When firstly enter the page, the four links is like this:
example.com?gender=male
example.com?gender=female
example.com?site=front
example.com?site=back
This work because it’s the “default” view (the default view is set to gender=male && site=front) in the model.
But if I choose to view ?gender=female the users should be able to filter it once more by adding &site=back so the complete URL would be: example.com?gender=female&site=back
And if I then press the link to see gender=male it should still keep the URL parameter &site=back.
What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: example.com?gender=male&site=front&gender=female and so on…
I’ve tried but to use the parse_url function, the http_build_query($parms) method and to make my “own” function that checks for existing parameters but it does not work.
My latest try was this:
_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
function _setURL($url, $key, $value) {
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$query = $key."=".$value;
$url .= $separator . $query;
var_dump($url); exit;
}
This function works unless the $_GET parameter already exists and thus should be replaced and not added.
I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.
I hope I’ve explained myself otherwise please let me know and I’ll elaborate.
Any help or advice would be appreciated
You can generate the links dynamically using the following method:
$frontLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=front':'mydomain.com?site=front';
$backLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=back':'mydomain.com?site=back';
This is a 1 line if statement which will set the value of the variables $frontLink and $backlink respectively. The syntax for a 1 line if statement is $var = (if_statement) ? true_result:false_result; this will set the value of $var to the true_result or false_result depending on the return value of the if statement.
You can then do the same for the genders:
$maleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=male&site='.$_GET['site']:'mydomain.com?gender=male';
$femaleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=female&site='.$_GET['site']:'mydomain.com?gender=female';
Found this by searching for a better solution then mine and found this ugly one (That we see a lot on the web), so here is my solution :
function add_get_parameter($arg, $value)
{
$_GET[$arg] = $value;
return "?" . http_build_query($_GET);
}
<?php
function requestUriAddGetParams(array $params)
{
$parseRes=parse_url($_REQUEST['REQUEST_URI']);
$params=array_merge($_GET, $params);
return $parseRes['path'].'?'.http_build_query($params);
}
?>
if(isset($_GET['diagid']) && $_GET['diagid']!='') {
$repParam = "&diagid=".$_GET['diagid'];
$params = str_replace($repParam, "", $_SERVER['REQUEST_URI']);
$url = "http://".$_SERVER['HTTP_HOST'].$params."&diagid=".$ID;
}
else $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&diagid=".$ID;

Categories