Wordpress - remove #! characters from URL - php

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 :-)

Related

Prestashop Quick Address Links to external URL

I have a small problem on the prestashop on adding custom url into the quick address.
The current status of prestashop is 1.7.4.2 fresh install.
As stated from the image above, I would like to redirect it to external URL http://www.google.com, after done creating it is shown in the quick address menu as shown below:
But when I clicked it, just redirect to:
http://localhost:8080/prestashop_1.7.4.2/admin067c8ousl/index.php/http://www.google.com
Note I have deleted the token as it provided the same result
In other words the token is self generated and differs everytime
I have saw original documentation for that specific issue in here.
When you see on the very bottom, it shows the exact issue I am facing:
Note that you can create links to other websites, for instance your PayPal account or your webmail. Simply paste the complete URL in the "URL" field, including the http:// prefix.
As I have written correct url, but it still thinks it is a controller.
I have no modified any code yet, is there a way to fix it.
Thank You and Have a nice day.
That was for v1.6, v1.7 doesn't allow external urls by default. I submitted an improvement for this, hope they approve the merge. Meanwhile, if you want to use them you can modify the classes/QuickAccess.php or add to the override (better option) and change the function getQuickAccessesWithToken to the following:
public static function getQuickAccessesWithToken($idLang, $idEmployee)
{
$quickAccess = self::getQuickAccesses($idLang);
if (empty($quickAccess)) {
return false;
}
$baselink = Context::getContext()->link->getBaseLink();
foreach ($quickAccess as $index => $quick) {
if(strpos($quickAccess[$index]['link'], 'http') !== 0 or strpos($quickAccess[$index]['link'], $baselink) === 0){
if ('../' === $quick['link'] && Shop::getContext() == Shop::CONTEXT_SHOP) {
$url = Context::getContext()->shop->getBaseURL();
if (!$url) {
unset($quickAccess[$index]);
continue;
}
$quickAccess[$index]['link'] = $url;
} else{
// first, clean url to have a real quickLink
$quick['link'] = Context::getContext()->link->getQuickLink($quick['link']);
$tokenString = $idEmployee;
preg_match('/controller=(.+)(&.+)?$/', $quick['link'], $admin_tab);
if (isset($admin_tab[1])) {
if (strpos($admin_tab[1], '&')) {
$admin_tab[1] = substr($admin_tab[1], 0, strpos($admin_tab[1], '&'));
}
$quick_access[$index]['target'] = $admin_tab[1];
$tokenString = $admin_tab[1].(int)Tab::getIdFromClassName($admin_tab[1]).$idEmployee;
}
$quickAccess[$index]['link'] = $baselink.basename(_PS_ADMIN_DIR_).'/'.$quick['link'];
if (false === strpos($quickAccess[$index]['link'], 'token')) {
$separator = strpos($quickAccess[$index]['link'], '?') ? '&' : '?';
$quickAccess[$index]['link'] .= $separator.'token='.Tools::getAdminToken($tokenString);
}
}
}
}
return $quickAccess;
}
Override is not a clean solution.
You can use free module to adding jquery to your "admin header hook" and do it by jquery to change URL of new created quickAccess

How to know if web page is returned from another website

I have website link http://example.com/link/
How can I handle if it returns from such as: http://facebook.com
I want to check and process event by something like this:
if(return from facebook) {
}
Jquery or PHP is ok.Thank you for your advice.
You could find the referer in PHP using:
$_SERVER['HTTP_REFERER']
if($_SERVER['HTTP_REFERER'] == 'https://facebook.com'){
}
However, you'd probably want to catch anything from facebook;
$sReg = '.facebook.+[a-zA-Z](\/*)';
if(preg_match( $sReg, $_SERVER['HTTP_REFERER'] == 1 ){
}
Note that HTTP_REFERER isn't a sure way of getting the referrer. Often it'll be missing.
See PHP manual for more info
The solution in javascript
if(document.referrer == 'https://facebook.com') {
/* Do somethings */
}
Using Regular Expression:
var myRe = new RegExp('facebook.+[a-zA-Z](\/*)');
if(myRe.test(document.referrer)) {
/* Do somethings */
}

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

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.

Get URL As Shown In Address Bar

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

Categories