Get URL As Shown In Address Bar - php

I'm using some URL rewriting, on top of the URL rewriting that Wordpress does natively.
The basic idea is that I use a category page with an address that appears like it belongs somewhere else, so /blog/type/kids is the true category in WP. I rewrite this with a .htaccess file in /kids/ to make the category look like its actually a page called /kids/programs with this code in the kids folder:
RewriteEngine on
RewriteRule ^programs$ /blog/type/kids/ [P]
This happens in two different locations in the site, but the both load the same WP page behind the scenes. This all works fine.
What I need to do now, is set a variable based on which location it is being loaded from, to ensure that the navigation highlights the proper section of the site, and shows the proper subnav. The problem is that I can't access the new, rewritten URL that the user sees.
Ideally, I'm looking for something like this:
if(strpos($_SERVER['PHP_SELF'],'kids//programs')) {
$top_nav_item_id = 'kids';
} else {
$top_nav_item_id = 'programs';
$subnav_item_id = 'kids';
}
PHP_SELF resolves to /blog/index.php and REQUEST_URI shows /blog/type/kids. So neither are showing me the /kids/programs location that is truly being displayed.
Any ideas how to get this? Maybe WP has a built in tag for this?
Cheers!

I'm also using Rewrite and this is working for me like a charm:
$_SERVER['REDIRECT_SCRIPT_URL']
you can also use
$_SERVER['REDIRECT_SCRIPT_URI']

The WordPress get_permalink() function is fully described at http://codex.wordpress.org/Function_Reference/get_permalink. Here is the usage:
<?php echo get_permalink( $id ); ?>
Since you are operating outside the loop, as you mentioned, you cannot just call get_permalink(), you have to pass the $id to the function. You could set the value of $id from inside the loop, and then use ISSET($id) — to be safe — before calling get_permalink($id).
If there are any issues after trying that with get_permalink (I was able to test it outside the loop, but I don't have a setup with your mod_rewrite rules), you could use still set $id from inside the loop and then manually construct the URL with the category using something like this, concatenated after 'http://yourservername/':
<?php if(ISSET($specpostid)) {
$catarray = get_the_category($id);
echo $catarray[0]->cat_name; } ?>

Try this
$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
$url = $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
The url variable $url will give you the url as shown in the address bar of the browser.

Returns the current url:
<?php
function curPageURL() {
$pageURL = 'http';
if (#$_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>

Related

Wordpress - remove #! characters from URL

The question seems to be easy but after 3 days of searches I gave up. I thought that I will find it here and it seems to have similar ones but it doesn't work for this stuff.
Currently I have a customer that has a really advanced marketing based on his previos JS/AJAX driven website. All the back link to his website is like
SERVER /#! LINK
I have built a wordpress website and I need so that cross links open pages properly.
But if I get this link
SERVER /#! LINK
I get following URL when Wordpress process it
SERVER /
I have explored that the only way, or at least the only I know is to do it with wordpress but that doesn't seems to be easy.
I have following script that can ADD #! but is need to remove (just found it somewhere)
<?php
$webSiteUrl = get_bloginfo('url')."/";
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
};
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
};
if($webSiteUrl!=$pageURL){
$pageHash = substr($pageURL, strlen($webSiteUrl), strlen($pageURL));
header("location:".$webSiteUrl."#!/".$pageHash."");
exit;
};
?>
Thanks to squeamish ossifrage I am almost there.
I used this script as the one you provided had some issues with condition
if ('' !== window.location.hash && '#!' !== window.location.hash) {
hash = location.hash.match(/^#!(.*)/)[1];
/* ... do something with hash, like redirecting to */
/* another page, or loading page content via AJAX. */
/* If all you want to do is remove everything from */
/* the URL starting with `#!', then try this: */
location.href = location.protocol+'//'+location.host+location.pathname;
}
It seems to work but I get root page.
e.g. I open
myweb.com/#!thisone
and I get
myweb.com/
AND JUST TO SUMMARIZE so somebody can save lots of time - working script is
if ('' !== window.location.hash && '!' !== window.location.hash) {
hash = location.hash.match(/^#!(.*)/)[1];
/* ... do something with hash, like redirecting to */
/* another page, or loading page content via AJAX. */
/* If all you want to do is remove everything from */
/* the URL starting with `#!', then try this: */
location.href = location.protocol+'//'+location.host+location.pathname+'/'+hash;
}
You can't do this in PHP because the the server will never see the fragment part of the URL (i.e., the # symbol and everything that follows it).
You'll have to use client-side Javascript instead. Something like this perhaps:
if /^#!/.test(location.hash) {
hash = location.hash.match(/^#!(.*)/)[1];
/* ... do something with hash, like redirecting to */
/* another page, or loading page content via AJAX. */
/* If all you want to do is remove everything from */
/* the URL starting with `#!', then try this: */
location.href = location.protocol+'//'+location.host+location.pathname;
}
EDIT: If I understand correctly, you want to put the hash value at the end of the redirect URL. That's quite easily done. Just change the penultimate line of the above code to
`location.href = location.protocol+'//'+location.host+location.pathname+'/'+hash;`
The additional '/' may be unnecessary; I'll leave you to figure out the details :-)

remove GET parameter in URL after processing is finished(not using POST), PHP

I have url like this http://localhost/join/prog/ex.php
When i use GET method the url address like this http://localhost/join/prog/ex.php?name=MEMORY+2+GB&price=20&quantity=2&code=1&search=add
My question is :
so, I still use the GET method but I want to after processing in GET method is finished, I want to the url back(remove parameter) into http://localhost/join/prog/ex.php, as previously (not using POST method). How can i do it?
Put this in your HTML file (HTML5).
<script>
if(typeof window.history.pushState == 'function') {
window.history.pushState({}, "Hide", "http://localhost/join/prog/ex.php");
}
</script>
Or using a backend solution using a session for instance;
<?php
session_start();
if (!empty($_GET)) {
$_SESSION['got'] = $_GET;
header('Location: http://localhost/join/prog/ex.php');
die;
} else{
if (!empty($_SESSION['got'])) {
$_GET = $_SESSION['got'];
unset($_SESSION['got']);
}
//use the $_GET vars here..
}
SIMPLE ANSWER
Just place this in the top of the file you need to make the GET querys disappear from the browser's URL bar after loading.
<script>
if(typeof window.history.pushState == 'function') {
window.history.pushState({}, "Hide", '<?php echo $_SERVER['PHP_SELF'];?>');
}
</script>
i guess after calling the url you want to redirect to the file ex.php , but this time without any parameters.
for that try using the following code in ex.php
<?
if($_GET['name']!='' || $_GET['price']!='' ||$_GET['quantity']!='' ||$_GET['code']!='' || $_GET['search']!=''){
/* here the code checks whether the url contains any parameters or not, if yes it will execute parameters stuffs and it will get redirected to the page http://localhost/join/prog/ex.php without any parameters*/
/* do what ever you wish to do, when the parameters are present. */
echo $name;
print $price;
//etc....
$location="http://localhost/join/prog/ex.php";
echo '<META HTTP-EQUIV="refresh" CONTENT="0;URL='.$location.'">';
exit;
}
else{
/* here rest of the body i.e the codes to be executed after redirecting or without parameters.*/
echo "Hi no parameters present!";
}
?>
here what u did id just redirect redirect to the same page without checking if any parameter is there in the query string. the code intelligently checks for the presence of parameters, id any parameters are there it will redirect to ex.php else it will print "Hi no parameters present!" string!
If you're using apache, consider using a .htaccess file with mod_rewirte.
Here a quickstart. I think this result can be obtained on iis as well with web.config file
You can use removable_query_args filter for that.
add_filter( 'removable_query_args', function( $vars ) {
$vars[] = 'name';
$vars[] = 'price';
$vars[] = 'quantity';
$vars[] = 'code';
$vars[] = 'search';
return $vars;
} );
But you should add specific conditions for your case, otherwise, it will remove these Get-parameters from all other URLs on your site as well.
More info here

How can I enforce a descriptive URL with CodeIgniter?

It's possible this question exists elsewhere, and if so, I apologize. After searching for an hour without success, I can't help but think I'm on the wrong track.
Essentially what I am looking for is a method to enforce a description or title in a page's URL. I am using CodeIgniter, so it is pretty simple to make a pretty URL go where ever I wish.
I could have:
http://mysite.com/controller/function/what-ever-i-want/can-go-here
and it will always go to:
http://mysite.com/controller/function/
with the variable values what-ever-i-want and can-go-here
What I would like is for the URL to be automatically rewritten to include the title if only the controller/function is given.
So, if someone went to:
http://mysite.com/controller/function/
it should automatically rewrite the url as
http://mysite.com/controller/function/a-more-descriptive-title/
A great example of the functionality that I am talking about is the SO URL. if you go to https://stackoverflow.com/questions/789439 it will automatically rewrite it to https://stackoverflow.com/questions/789439/how-can-i-parse-descriptive-text-to-a-datetime-object
I suspect that mod_rewrite is involved, but I would like to come up with the solution that works most gracefully with CodeIgniter.
I am very new to the pretty-url scene and desperately call upon the advice of someone with more experience. Thanks in advance for any help given!
I used Fiddler2 to see how Stackoverflow does this.
Part of the respnse from http://stackoverflow.com/questions/12205510/
HTTP/1.1 301 Moved Permanently
Location: /questions/12205510/how-can-i-enforce-a-descriptive-url-with-codeigniter
Vary: *
Content-Length: 0
So basically when we go to controller/function/ we need to redirect user to controller/function/my-awesome-title. I've written simple controller that does just that:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controller extends CI_Controller
{
protected $_remap_names = array();
function __construct()
{
parent::__construct();
$this->_remap_names['func'] = "My Awesome Title";
}
function _remap($method, $arguments)
{
if(
isset($this->_remap_names[$method])
&& sizeof($arguments) == 0
&& method_exists($this, $method)
)
{
$this->load->helper("url");
$title = str_replace(" ", "-", $this->_remap_names[$method]);
$title = strtolower($title);
$url = strtolower(__CLASS__)."/$method/$title";
$url = site_url($url);
// if you dont want to have index.php in url
$url = preg_replace("/index\.php\//", "", $url);
header("HTTP/1.1 301 Moved Permanently");
header("Location: $url");
header("Vary: *");
}
else
{
call_user_func_array(array($this,$method), $arguments);
}
}
function func()
{
echo "<h1>";
echo $this->_remap_names[__FUNCTION__];
echo "</h1>";
}
};
Docs for CodeIgniters _remap function can be found here in Remapping Function Calls section.
I don't use CodeIgniter, but you should be able to place code in a controller's __construct, or in some kind of pre-action event if CI has those.
You just look up the appropriate URL for the entity being viewed and do a 301 redirect if necessary.

Facebook Opengraph Read Action

Right I asked a similar question but didn't word it coherently so here goes.
I'm trying to use Facebook opengraph to instigate a read action for articles on my site using php code.
I want to use the opengraph to post a read action for the current url. I've tried this so far but with no joy
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
<?php
$facebook->api('https://graph.facebook.com/me/:read?
article='echo curPageURL();'','POST')
?>
As many clever cloggs have pointed out I am a novice and this is my best attempt so please be patient
The API calls looks to be incorrect. If you are using the build-in 'read' action, try something like:
$facebook->api('/me/news.reads?article=' . curPageURL(),'POST');
You don't need to use the full graph URL in the API call. Make sure you have permission to publish actions for the user too or the API call will fail. If the call is successful, you will get the ID of the published action back.

CakePHP app in directory breaks redirects done with query string

My CakePHP 2.0 application url is: http://localhost/testapplication/
and when I do redirects on a login from a link I use a query string e.g.
localhost/testapplication/login?continue=/testapplication/admin/posts
The redirect is done using:
if(isset($this->params['url']['continue']))
{
$pathtoredirect = $this->params['url']['continue'];
}
else
{
$pathtoredirect = $this->Auth->redirect();
}
return $this->redirect($pathtoredirect);
However when I do the redirect I will end up at a URL like:
localhost/testapplication/testapplication/admin/posts
As you can see it redirects to the passed url but because the passed url also contained the base directory it duplicates it breaking the url redirect and ending up at a 404!
Any ideas on how to get around this problem?
Just to confirm:
The url does start with a / so it does redirect at the root level, but the problem is that root level is a directory so it duplicates it as it's also passed in the query
If you construct a path in either of the following ways:
$continue = Router::url(array('controller' => 'admin', 'action' => 'posts'));
$continue = Router::url('/admin/posts');
then Router::url will prepend the base path /application. Then if you call Router::url again on the resulting url (or redirect to it) Router::url will prepend it again. That's the way it works, and there's nothing you can do about it.
In reality, the url /application/admin/posts is ambiguous, but CakePHP reads it as controller=application, action=admin, and the first argument is posts.
The only ways to circumvent this are:
Use an absolute url:
$continue = Router::url(array('controller' => 'admin', 'action' => 'posts'), true);
Or make sure Router::url is only called once, e.g.:
$continue = '/admin/posts';
Or after login
$pathtoredirect = FULL_BASE_URL . $this->params['url']['continue'];
Okay the fix was to do the following:
Get the full URL (as mentioned by others) here using a helper:
class LinkHelper extends AppHelper
{
public function selfURL()
{
$pageURL = 'http';
//if ($_SERVER["HTTPS"] == "on")
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
{
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
$pageURL = urlencode($pageURL);
return $pageURL;
}
}
Then when using the URLs making sure to encode and decode them for use in the address bar
e.g. $pathtoredirect = urldecode($this->params['url']['continue']);
It seems like you have a couple options here. If $this->params['url']['continue'] is exactly what you pass in with your query string, is it possible for you to modify your query string so it is just /admin/posts so the complete URL will be application/admin/posts?
You may not have to do this, but I'd need to see exactly what $this->params['url']['continue'] looks like. Please do a die(debug($this->params['url']['continue'])); somewhere before your redirect so we can investigate further.

Categories