php GET variable gets interrupted with ampersand (&) - php

SOLUTION:
it seems htaccess requires 'B' for it to retain the ampersand
so using
RewriteRule ^album/([a-zA-Z0-9-=_.]+)$ view.php?album=$1 [L,B]
works
SOLUTION
I am trying to read the get value from the url which is:
view.php?album=something
This is one of my rules in my .htaccess file:
#this rewrite 'view.php?album=something' to 'album/something'
RewriteRule ^album/([^/\.]+)/?$ ^view.php?album=$1 [L]
The problem is that sometimes the album name ie 'something' may contain and & in the name and this causes $_GET to trip up.
**For example**
album name is 'football&basketball'
The view.php page will only read up to football and throw an error.
Without the rewrite rule it works perfectly fine, but with the rewrite rule it messes up for that one case.
I am using rawurlencode at the moment
If there is no & in the name then it also works fine - its only with the & when it messes up
Does anyone have any suggestions on how to overcome this? I have tried using htmlspecialchars and htmlentities etc.
EDIT: Added Code
htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
#rewrite view.php?album=whatever to album/whatever
RewriteRule ^album/([a-zA-Z0-9-=_.]+)$ view.php?album=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteBase /ShyamJoshi/dist/
#remove .php and .html extension
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteOptions Inherit
ReWriteCond %{HTTP:accept-encoding} (gzip.*)
ReWriteCond %{REQUEST_FILENAME} !.+\.gz$
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule (.+) $1.gz [QSA,L]
</IfModule>
PHP:
This function is being used twice. First it shows all directories and then it shows all images in directories (which is the 'else' part)
function getImagesOrImageDirs($dirOnly) {
$dirLoc = getcwd() . '/images/events/';
$allDirs = preg_grep('/^([^.])/', scandir($dirLoc));
echo '<div class="row">';
if ($dirOnly == true) {
foreach($allDirs as $dir) {
$innerDirImages = preg_grep('/^([^.])/', scandir($dirLoc.'/'.$dir));
$firstImageOfDir = reset($innerDirImages);
/* view.php?album=something -> rewritten by htaccess to albums/something*/
$href = 'album/'.$dir;
// $href = 'album/'.$dir;
$imageSrc = 'images/events/'.$dir.'/'.$firstImageOfDir;
echo albumAndPhotoTemplate($href, $imageSrc, true, $dir, 'col-xs-12 col-sm-3');
}
} else {
if (empty ($_GET['album']) ) {
return ;
}
$albumName = $_GET['album'];
print_r($albumName);
$dirLoc = $dirLoc .'/'.$albumName;
$allImages = preg_grep('/^([^.])/', scandir($dirLoc));
foreach($allImages as $image) {
$imgSrcAndHref = 'images/events/'.$albumName.'/'.$image;
echo albumAndPhotoTemplate($imgSrcAndHref, $imgSrcAndHref, false, '', 'col-xs-12, col-sm-3');
}
}
echo '</div>';
}

Try like this..
RewriteEngine On
RewriteRule ^album/([a-zA-Z0-9-=_.]+)$ view.php?album=$1 [L]
Get your variable using
$_GET['album'];
If you want to both variable and name:
print_r($_GET);
To escape & on url use %26 like this..
view.php?album=something%26basketball
See more here escaping ampersand in url

Related

Php get content without question mark?

I get mysite.com/?file=abc
<?php if(!empty($_GET['file'])) {?>
<?php echo $_GET['file']; ?>
<?php } ?>
it's possible get value like this:
mysite.com/file/abc
If you are using apache, and your config allows for htaccess overrides,
you can create an .htaccess file like this
# Turn on URL rewriting
RewriteEngine On
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?q=$1 [L]
URL
mysite.com/file/abc
In your php file do something like this
<?php
$query = explode('/', $_GET['q']);
if ($query[0] === 'file') {
echo $query[1];
}

Htaccess rewrite rules for this url

I just started to learn htaccess and i'd like to rewrite my current urls from this:
http://www.url.com/?location=script
To:
http://www.url.com/script
So far i've managed to do this but now i want to have a directory with more controllers so i can have something like this:
http://www.url.com/script/method
Structure: Script directory --> method.php
Currently my directory structure for includes its like this:
assets-->client(directory):
login.php
logout.php
register.php
something.php
And i'd like to access these using a url like:
url.com/client/login
url.com/client/logout
url.com/client/register
url.com/client/something
My .htaccess:
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?location=$1 [L]
</ifModule>
PHP based inclusion code:
####################################################################
# PARSE THE CURRENT PAGE #
####################################################################
$includeDir =".".DIRECTORY_SEPARATOR."assets/controllers".DIRECTORY_SEPARATOR;
$includeDefault = $includeDir."home.php";
if(isset($_GET['ajaxpage']) && !empty($_GET['ajaxpage'])){
$_GET['ajaxpage'] = str_replace("\0", '', $_GET['ajaxpage']);
$includeFile = basename(realpath($includeDir.$_GET['ajaxpage'].".php"));
$includePath = $includeDir.$includeFile;
if(!empty($includeFile) && file_exists($includePath)) {
include($includePath);
}
else{
include($includeDefault);
}
exit();
}
if(isset($_GET['location']) && !empty($_GET['location']))
{
$_GET['location'] = str_replace("\0", '', $_GET['location']);
$includeFile = basename(realpath($includeDir.$_GET['location'].".php"));
$includePath = $includeDir.$includeFile;
if(!empty($includeFile) && file_exists($includePath))
{
include($includePath);
}
else
{
include($includeDefault);
}
}
else
{
include($includeDefault);
}
All my controllers are in assets/controllers/ucp/login.php for example.
How about:
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^(/client/[a-zA-Z0-9_\-]+)$
RewriteRule ^[a-z]+ index.php?location=$2 [L]
</ifModule>
It does include a leading slash and doesn't have the PHP extension. But this can be altered in PHP to suit your needs.
Be wary though, your code gives access to all your PHP files. You might want to check $_GET['location'] against an array of allowed locations. Consider the following URL as example of how this could go wrong
http://example.com/index.php?location=../drop_database.php

Get params not being passed

I have an API based application written in slim. I have been testing on my local computer and things have been working OK.
I pushed to the server and I noticed that i cant retrieve the parameters passed via a get request
While debugging, i observed the following
Post requests are working fine
An attempt to use $_GET['param'] fails as i get an undefined index error.
To get a parameter value in slim, i write
$app->request()->get('param');
URL request : {api}/hospital/get_locations?hospital_id=1
var_dump($_GET): array(1) { ["/hospital/get_locations"]=> string(0) "" }
Any pointers as to why this might be happening?
Content of .htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
EDIT
There might be a way of getting get request params using the $_SERVER['REQUEST_URI']. I did a quick test on my localhost and came up with the following. Try it out, might work for you.
php
<?php
// Function
function getParams() {
$params = array();
$urlParts = parse_url($_SERVER['REQUEST_URI']);
if (isset($urlParts['query'])) {
$query = $urlParts['query'];
if (-1 !== strpos($query, '&')) {
$query = explode('&', $query);
} else {
$query = array($query);
}
foreach ($query as $queryStr) {
list($key, $val) = explode('=', $queryStr);
$params[$key] = $val;
}
}
return $params;
}
// Usage
$params = getParams();
// Debug
echo "<pre>";
print_r($params);
echo "</pre>";
?>
output
Array
(
[hospital_id] => 1
)
.htaccess (similar to yours)
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php [L]
</IfModule>

How to get the URI of the frontpage?

I use the following code to request the URI in order to display multi-language content variables. That works fine for every page that has an URI. My problem is the frontpage: For the pure domain www.domain.com without URI it doesn't work, however it works for www.domain.com/index.php. I can't figure out the right syntax for the frontpage, please help.
if (stripos($_SERVER['REQUEST_URI'],'index') !== false ) {
// Frontpage
$lang['META_TITLE'] = 'Welcome to the frontpage';
$lang['META_DESCRIPTION'] = '';
$lang['META_KEYORDS'] = '';
$lang['PAGE_TITLE'] = '';
$lang['BREADCRUMB'] = '';
}
Create a .htaccess file in main root and paste this code .... i hope its work for you
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

Rewrite Url Parameters - Change http://myweb/?dept=dept&app=app to http://myweb/dept/app

I've currently got a web application that I need optimizing, and one of methods or something I'm trying to achieve is such:
http://myweb/dept/app
from
http://myweb/?dept=dept&app=app
I've currently this as the PHP code for it:
if(empty($_REQUEST['dept'])) {
$folder = "apps/";
} else {
$folder = str_replace("/", "", $_REQUEST['dept']) . "/"; }
if(empty($_REQUEST['n'])) {
include('user/home.php');
} else {
$app = $_REQUEST['n'];
if(file_exists($folder.$app.".php")) {
include($folder.$app.".php");
} else {
include("global/error/404.php");
}
}
How do I do this?
I'm currently half there with:
RewriteRule ^([A-Za-z]+)$ /index.php?app=$1
but that only rewrites part of it.
Thanks
The way many frameworks do this is with one of the following rules:
RewriteRule ^(.*)$ /index.php?q=$1
RewriteRule ^(.*)$ /index.php
In the 1st case you get the query string in $_GET["q"].
In the 2nd case you have to get the query string from $_REQUEST or something. (just do some var_dumps till you find what you need).
Then you explode("/") this and you're all set.
Have a look at how TYPO3, eZPublish, Drupal do this.
You should also add the following conditions to allow the site to open your static files (like images/css/js/etc). They tell apache to not do the rewrite if the URL points to a location that actually matches a file, directoy or symlink. (You must do this before the RewriteRule directive)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
This should work:
RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&app=$2 [QSA]
You need the QSA part in order for any GET parameters to be appended to the rewritten URL.
You might find that it can be more flexible to rewrite everything to index.php, and then handle splitting up the url there, e.g.
.htaccess:
#only rewrite paths that don't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1
PHP:
<?php
$parts = explode('/', $_SERVER['PATH_INFO']);
$dept = isset($parts[0]) ? $parts[0] : 'someDefault';
$app = isset($parts[1]) ? $parts[1] : 'anotherDefault';

Categories