Zend - Get everything after base Url (Controller, Action, and any params) - php

I am trying to create a login system with Zend that when a user tries to access a restricted page they will be taken to a login page if they aren't signed in. The issue I'm having is getting the URL they were trying to access before hand. Is there a Zend Function that will return everything after the base Url? For example, I need "moduleName/controllerName/ActionName/param1/value1/param2/value2" etc etc. to be sent as a querystring param to the login page (ex: login/?redirect=controllerName/actionName/param1/value1/param2/value)
I can get the controller and action name, and I get get the params, but it already includes the module, controller, and action as well. I'd like to just get what I need. I worked out the long way of doing it like this:
$controllerName = Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
$actionName = Zend_Controller_Front::getInstance()->getRequest()->getActionName();
$paramArray = Zend_Controller_Front::getInstance()->getRequest()->getParams();
$params = '';
foreach($paramArray as $key => $value)
$params .= $key . "/" . $value;
$this->_redirect('/admin/login/?redirect=' . $controllerName . "/" . $actionName . "/" . $params);
but even then I end up with params like module/admin/controller/index/ etc which I don't want. So, how can I just get everything as a string like it is in the URL or at least just the params in a string without the controller and action as param values?
**EDIT: Here is my current solution, but there has got to be a more elegant way of doing this **
$moduleName = $this->getRequest()->getModuleName();
$controllerName = $this->getRequest()->getControllerName();
$actionName = $this->getRequest()->getActionName();
$paramArray = $this->getRequest()->getParams();
$params = '';
foreach($paramArray as $key => $value)
if($key <> "module" && $key <> "controller" && $key <> "action")
$params .= $key . "/" . $value . "/";
$this->_redirect('/admin/login/?redirect=' . $moduleName . "/" . $controllerName . "/" . $actionName . "/" . $params);

I think you can pass along the last request URI like this:
$this->_redirect('/admin/login/?redirect='.urlencode($this->getRequest()->REQUEST_URI));

i know its an old question but for future references:
$this->getRequest()->getRequestUri();
that should get you what you want..

No idea why Zend doesn't have this feature, but this is how I have accomplished it. My use case was that i wanted to redirect old URLs that went directly to controllers using the default routing, to a new API url structure that used routes.
$filtered_params = array_diff_key(
$this->_request->getParams(),
array_fill_keys( array('controller', 'module', 'action' ), 1)
);
$this->_redirect('/api/1.0/?' . http_build_query($filtered_params));

Old question but heres a solution thats worked for me. From here you may want to url encode it etc
$currentRoute = substr($this->getRequest()->getRequestUri(),strlen($this->getRequest()->getBaseUrl()));

You could try using urlencode() and urldecode() to encode/decode the individual param strings. An example would be:
// outputs %2Fpath%2Fto%2Ffile.php
$path = '/path/to/file.php';
echo urlencode($path);

Related

Remove subdomain from URL/host to match domains in affiliate link array

I want to make a redirect file using php which can add Affiliates tag automatically to all links. Like how it works https://freekaamaal.com/links?url=https://www.amazon.in/ .
If I open the above link it automatically add affiliate tag to the link and the final link which is open is this ‘https://www.amazon.in/?tag=freekaamaal-21‘ And same for Flipkart and many other sites also.
It automatically add affiliate tags to various links. For example amazon, Flipkart, ajio,etc.
I’ll be very thankful if anyone can help me regarding this.
Thanks in advance 🙏
Right now i made this below code but problem is that sometimes link have extra subdomain for example https://dl.flipkart.com/ or https://m.shopclues.com/ , etc for these type links it does not redirect from the array instead of this it redirect to default link.
<?php
$subid = isset($_GET['subid']) ? $_GET['subid'] : 'telegram'; //subid for external tracking
$affid = $_GET['url']; //main link
$parse = parse_url($affid);
$host = $parse['host'];
$host = str_ireplace('www.', '', $host);
//flipkart affiliate link generates here
$url_parts = parse_url($affid);
$url_parts['host'] = 'dl.flipkart.com';
$url_parts['path'] .= "/";
if(strpos($url_parts['path'],"/dl/") !== 0) $url_parts['path'] = '/dl'.rtrim($url_parts['path'],"/");
$url = $url_parts['scheme'] . "://" . $url_parts['host'] . $url_parts['path'] . (empty($url_parts['query']) ? '' : '?' . $url_parts['query']);
$afftag = "harshk&affExtParam1=$subid"; //our affiliate ID
if (strpos($url, '?') !== false) {
if (substr($url, -1) == "&") {
$url = $url.'affid='.$afftag;
} else {
$url = $url.'&affid='.$afftag;
}
} else { // start a new query string
$url = $url.'?affid='.$afftag;
}
$flipkartlink = $url;
//amazon link generates here
$amazon = $affid;
$amzntag = "subhdeals-21"; //our affiliate ID
if (strpos($amazon, '?') !== false) {
if (substr($amazon, -1) == "&") {
$amazon = $amazon.'tag='.$amzntag;
} else {
$amazon = $amazon.'&tag='.$amzntag;
}
} else { // start a new query string
$amazon = $amazon.'?tag='.$amzntag;
}
}
$amazonlink = $amazon;
$cueurl = "https://linksredirect.com/?subid=$subid&source=linkkit&url="; //cuelinks deeplink for redirection
$ulpsub = '&subid=' .$subid; //subid
$encoded = urlencode($affid); //url encode
$home = $cueurl . $encoded; // default link for redirection.
$partner = array( //Insert links here
"amazon.in" => "$amazonlink",
"flipkart.com" => "$flipkartlink",
"shopclues.com" => $cueurl . $encoded,
"aliexpress.com" => $cueurl . $encoded,
"ajio.com" => "https://ad.admitad.com/g/?ulp=$encoded$ulpsub",
"croma.com" => "https://ad.admitad.com/g/?ulp=$encoded$ulpsub",
"myntra.com" => "https://ad.admitad.com/g/?ulp=$encoded$ulpsub",
);
$store = array_key_exists($host, $partner) === false ? $home : $partner[$host]; //Checks if the host exists if not then redirect to your default link
header("Location: $store"); //Do not changing
exit(); //Do not changing
?>
Thank you for updating your answer with the code you have and explaining what the actual problem is. Since your reference array for the affiliate links is indexed by base domain, we will need to normalize the hostname to remove any possible subdomains. Right now you have:
$host = str_ireplace('www.', '', $host);
Which will do the job only if the subdomain is www., obviously. Now, one might be tempted to simply explode by . and take the last two components. However that'd fail with your .co.id and other second-level domains. We're better off using a regular expression.
One could craft a universal regular expression that handles all possible second-level domains (co., net., org.; edu.,...) but that'd become a long list. For your use case, since your list currently only has the .com, .in and .co.in domain extensions, and is unlikely to have many more, we'll just hard-code these into the regex to keep things fast and simple:
$host = preg_replace('#^.*?([^.]+\.)(com|id|co\.id)$#i', '\1\2', $host);
To explain the regex we're using:
^ start-of-subject anchor;
.*? ungreedy optional match for any characters (if a subdomain -- or a sub-sub-domain exists);
([^.]+\.) capturing group for non-. characters followed by . (main domain name)
(com|id|co\.id) capturing group for domain extension (add to list as necessary)
$ end-of-subject anchor
Then we replace the hostname with the contents of the capture groups that matched domain. and its extension. This will return example.com for www.example.com, foo.bar.example.com -- or example.com; and example.co.id for www.example.co.id, foo.bar.example.co.id -- or example.co.id. This should help your script work as intended. If there are further problems, please update the OP and we'll see what solutions are available.

Redirect with PHP and skip specific parameter

Since I've started using friendly URLS in my website, I'm redirecting every page to the new version, only if the registered user has a "username" in his profile.
So, I'm redirecting from:
https://tribbr.me/post.php?id=850
with:
header("Location:/".$if_username."/post/".$post_id."?".$_SERVER['QUERY_STRING']); exit();
To keep all GET parameters.... but the problem is that this header request, obviously with $_SERVER['QUERY_STRING'] is adding the post id too to the URL, and when redirected, this is the final URL:
https://tribbr.me/TribeMasters/post/850?id=850
Is it possible to just skip the id=850 parameter to the URL redirection? Since it is a duplicated parameter: post/850 and id=850 are the same.
Thanks for helping me :)
#DE_'s answer is best. But If you are not familiar with Regex, This is an alternative way.
function removeGetParam($param){
$params = $_GET;
// removing the key
unset($params[$param]);
// joining and returning the rest
return implode(',', array_map(function ($value, $key) {
return $key.'='.$value;
},$params, array_keys($params))
);
}
$filtered_params = removeGetParam('id');
header("Location:/".$if_username."/post/".$post_id."?".$filtered_params);
David Walsh did a good article on this
https://davidwalsh.name/php-remove-variable
function remove_querystring_var($url, $key) {
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
return $url;
}

What is the correct way to use fileGetContents?

There are so many ways to enter a URL that I just created an array and tried them all ...
This happens to be for domains only:
private function pageFoundGet( $domain )
{
$types = array(
"file_get - 1"=>$domain,
"file_get - 2"=>'www.' . $domain,
"file_get - 3"=>'http://www.' . $domain,
"file_get - 4"=>'https://www.' . $domain,
"file_get - 5"=>'http://' . $domain,
"file_get - 6"=>'https://' . $domain
);
foreach ($types as $code => $value) {
if ($this->domain_file = $this->fileGetContents( $value ))
{
$this->file_start_code = $code;
return true;
}
}
return false;
}
But what is the correct way ?
You have to provide the protocol and the domain. So in your case, you shouldn't use 1 and 2.
Now it's important, that each of the variants 3-6 could show completly different content and each of them is correct. You could show two different pages for http and https and you could even show different content for www and non www urls.
Usually, there's a redirect, which redirects every of these requests to the same location, but that is not neccessary.
file_get_contents is smart enough to follow this redirects on his own, so you even don't need to know, that an redirect exists.
What I usually do is: Just put the url in the browser and use that for file_get_contents.

Differentiate between Subdomains and Subdirectories

I've got a site that is pretty customized, set up on subdomains; sitename.domain.com and it's got some pages (that are the same for ALL subdomains) sitename.domain.com/this-page. Every single site has "/this-page".
We've got someone interested in using some of the stuff we've developed, but they are MARRIED to using subdirectories; domain.com/sitename which would, of course, have domain.com/sitename/this-page as well.
My question is, I've got some code
$sN = 'http://www.' . $_SERVER['HTTP_HOST'];
$PAGE = $sN . '/this-page/';
but of course this does not work for the subdirectory install (it looks for domain.com/this-page/ instead of domain.com/sitename/this-page
is there a way I can differentiate between subdomains and subdirectories?
$setup = "GET THE HOME PAGE, REGARDLESS OF SETUP"
if($setup ( CONTAINS www.X.X.com)) { //do the code above }
else if ($setup ( CONTAINS www.X.com/X)) { //do different code }
[EDIT] Tried the solution from http://www.php.net/manual/en/reserved.variables.server.php#100881 but didn't work for me, so I did this:
<?php
$sitename = 'sitename';
if (strpos($_SERVER['HTTP_HOST'],$sitename)!==false){
echo 'you are in http://'.$_SERVER['HTTP_HOST'] . '/';
// you are in http://sitename.domain.com/
} else {
$path = explode('/',$_SERVER['PHP_SELF']);
unset ($path[count($path)-1]);
echo 'you are in http://' . $_SERVER['HTTP_HOST'] . implode('/',$path) .'/';
// you are in http://www.domain.com/sitename/
}
?>
The answer from #elcodedocle is the better way of doing this. While they came up with that solution, I had ended up with a (yuckier) solution as well.
//Let's grab the current url for other uses
$cur = 'http://www.' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
//Is this subdomains or subdirectories?
$TYPE = explode('.', $cur);
if(isset($TYPE[3])){
//Yay! It's subdomains! not stupid subdirectories!
$this_root = 'http://www.' . $_SERVER['HTTP_HOST'];
} else {
//Boo.... It's stupid subdirectories.... ;o(
$chunks = explode('/', $TYPE[2]);
$this_root = 'http://www.' .$TYPE[1]. '.' .$chunks[0]. '/' .$chunks[1];
}
?>
This works as well, but it's a less graceful solution. I ended up using a slightly modified version of the code above, but for those of you wondering, this is how I got there before reloading SO. :)

How to pass GET variables from php to php on another server

In a php script I am receiving some data:
$data = $_POST['someData'];
How can I do something like this:
goToThisUrl( "http://someDomain.com/someScript.php?data = ".$data );
or if it is easier how can I do it by POST?
BTW.
This is not happening in a browser, the first php script is getting called by a cart when the order is paid for (if it makes any difference)
Replace goToThisUrl with the real function file_get_contents and remember to urlencode($data) and that would work just fine.
If you want to POST the data instead, look at cURL. Typing "[php] curl post" into the search box will get you the code.
If you want to send the user there, then:
header('Location: http://someDomain.com/someScript.php?data='.$data);
exit;
Or if you just want to call the other server, you can do:
$response = file_get_contents('http://someDomain.com/someScript.php?data='.$data);
Both assume data is already a urlencoded string, you might want to use 'data=' . urlencode($data) or just http_build_query($data) otherwise.
foreach ($_POST as $key => $val) {
$qs = urlencode($key) . "=" . urlencode($val) . "&";
}
$base_url = "<url here>";
$url = $base_url . "?" . $qs;
header('Location: $url'); exit();

Categories