Rewriterule with optional parameter - .htaccess

this is my .htaccess file
..
RewriteRule ^songbook(?:/([a-z]))?/?$ music/songbook.php?char=$1 [L]
with that rule i can use the following url's:
http://www.example.com/songbook
http://www.example.com/songbook/
http://www.example.com/songbook/a
http://www.example.com/songbook/a/
So far so good. The problem occurs when i try the get the char in PHP, like so:
if (isset($_GET['char'])) {
echo 'FOUND a char';
} else {
echo 'there is NO char';
}
For some reason, it always finds a char, even when there is no char provided.
My rewrite rule says that the char is optional, but i guess i'm doing something wrong.
How do i write the rewriterule so that the char is optional so the if condition in PHP works?
Thanks

Problem is that your rewrite rule always defines char in query string even if it's an empty string.
You have two options :
1- Edit your php:
if (isset($_GET['char']) && !empty($_GET['char'])) {
echo 'FOUND a char';
} else {
echo 'there is NO char';
}
2- Edit your .htaccess:

You can change the .htaccess:
RewriteRule ^songbook/?$ music/songbook.php [L]
RewriteRule ^songbook/([a-z])/?$ music/songbook.php?char=$1 [L]

Related

eslint enforce space after the single-line-if parentheses

I'm quite new to ESLint and I couldn't find a rule that does what I want. Consider the following code:
if(someCondition)i++;
I want to enforce a single space after the parentheses, so that we should have the following instead:
if(someCondition) i++;
However I simply couldn't find such a rule; it's not space-before-function-paren (obviously), keyword-spacing (which only affects the spacing after if) or space-before-blocks (since this is a single-line-if, there's no block). Please help. Thanks!
P.S. Same rule should apply to single-line-while as well.
https://github.com/eslint/eslint/discussions/15267#discussioncomment-1597748
I think we don't have that rule in the core.
keyword-spacing can disallow if (foo)return;, space-before-blocks can disallow if (foo){, but it seems that there is no rule that would disallow if (foo)bar; and enforce if (foo) bar;
Simple, but effective:
$ cat input
if (condition)i++;
if (condition)i--
while ( this ^ foo || bar )continue
for (true ||
true )z--
Naive solution, but probably ok.
$ cat input | busybox sed -e 's/)\([a-zA-Z_]\)/) \1/'
if (condition) i++;
if (condition) i--
while ( this ^ foo || bar ) continue
for (true ||
true ) z--
This will put a space between ) and the first letter of a variable name (a-z_).
Consider my answer here (and others') for tips on how to process all files that contain the undesired pattern:
https://unix.stackexchange.com/questions/675881/remove-trailing-spaces-from-text-files-only-when-necessary/676367#676367

php strips [[:char_class:]] from the string

When concatenating mysql regex character classes in php they disappear from the resulting string i.e.:
$regexp_arr = array('(word1)', '(word2)');
$value = 'word3';
$regexp_str = implode('[[:space:]]', $regexp_arr);
$v1 = '[[:<:]](' . $value . ')';
echo $regexp_str;
// gives
'(word1)(word2)';
// instead of
'(word1)[[:space:]](word2)'
echo $v1;
// gives
'(word3)'
//instead of
'[[:<:]](word3)'
I've tried with double quotation marks ", the result still the same.
Is there a special way to concatenate this in php? Why are the '[[:char_class:]]' getting stripped?
server php version is 5.6.36
In MODX, [[ and ]] are special characters used to indicate they are tags MODX needs to process. Even when you echo or retrieve it from the database, MODX will process them when rendering.
For debugging, you can follow-up your echo with an exit().
echo $regexp_str;
exit();
That short-circuits MODX and gives you the actual value of the string including the square brackets.
If you want the value to be visible in a MODX-rendered resource or template, then you'll have to replace them with their html entities first:
$regexp_str = str_replace(['[',']'], ['[', ']'], $regexp_str);

Can't understand this error using Xcart [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
We have a website which is built on Xcart 5.2. I imported database on my local system then I set database configuration under rootfolder/etc/config.php after that when I go to site using url "localhost/FSM/"
It showing :-
config.php
; <?php /*
; WARNING: Do not change the line above
;
; +-------------------------------------+
; | X-Cart 5 configuration file |
; +-------------------------------------+
;
; -----------------
; About this file
; -----------------
;
;
; ----------------------
; SQL Database details
; ----------------------
;
[database_details]
hostspec = "localhost"
socket = "/opt/lampp/var/mysql/mysql.sock"
port = "3306"
database = "florist_singapore"
username = "root"
password = ""
table_prefix = "xc_"
;
; ----------------------
; Cache settings
; ----------------------
;
[cache]
; Type of cache used. Can take auto, memcache, apc, xcache, file values.
type=file
; Cache namespace
namespace=XLite
; List of memcache servers. Semicolon is used as a delimiter.
; Each server is specified with a host name and port number, divided
; by a colon. If the port is not specified, the default
; port 11211 is used.
servers=
;
; -----------------------------------------------------------------------
; X-Cart 5 HTTP & HTTPS host, web directory where cart installed
; and allowed domains
; -----------------------------------------------------------------------
;
; NOTE:
; You should put here hostname ONLY without http:// or https:// prefixes
; Do not put slashes after the hostname
; Web dir is the directory in the URL, not the filesystem path
; Web dir must start with slash and have no slash at the end
; The only exception is when you configure for the root of the site,
; in which case you write single slash in it
; Domains should be listed separated by commas.
;
; WARNING: Do not set the "$" sign before the parameter names!
;
; EXAMPLE 1:
;
; http_host = "www.yourhost.com"
; https_host = "www.securedirectories.com/yourhost.com"
; web_dir = "/shop"
; domains = "www.yourhost2.com,yourhost3.com"
;
; will result in the following URLs:
;
; http://www.yourhost.com/shop
; https://www.securedirectories.com/yourhost.com/shop
;
;
; EXAMPLE 2:
;
; http_host = "www.yourhost.com"
; https_host = "www.yourhost.com"
; web_dir = "" (don't use "/")
;
; will result in the following URLs:
;
; http://www.yourhost.com
; https://www.yourhost.com
;
[host_details]
http_host = "localhost"
https_host = "localhost"
web_dir = "/FSM"
domains = ""
[clean_urls]
; String with one or more chars.
; It will be used to autogenerate clean URLs.
; By default, only the "-" or "_" characters are allowed.
; Empty string is also allowed.
default_separator = "-"
; Get clean URLs capitalized for every starting letter of a word
capitalize_words = Off
; Use canonical URL for product page
use_canonical_urls_only = On
;
; -----------------
; Logging details
; -----------------
;
[log_details]
type = file
name = "var/log/xlite.log.php"
level = LOG_WARNING
ident = "XLite"
suppress_errors = On
suppress_log_errors = Off
;
; Skin details
;
[skin_details]
skin = default
locale = en
;
; Default image settings
;
[images]
default_image = "images/no_image.png"
default_image_width = 110
default_image_height = 110
unsharp_mask_filter_on_resize = off
; Installation path of Image Magick executables:
; for example:
; image_magick_path = "C:\\Program Files\\ImageMagick-6.7.0-Q16\\" (in Windows)
; image_magick_path = "/usr/local/imagemagick/" (in Unix/Linux )
; You should consult with your hosting provider to find where Image Magick is installed
; If you leave it empty then PHP GD library will be used.
;
image_magick_path =
;
; Installer authcode.
; A person who do not know the auth code can not access the installation script.
; Installation authcode is created authomatically and stored in this section.
;
[installer_details]
auth_code = "3JT6GWX7"
shared_secret_key = "55a77ea79a7c93.31452261"
;
; Some options to optimize the store
;
[performance]
developer_mode = Off
skins_cache = off
compress_php_core = off
;
; Decorator options
;
[decorator]
time_limit = 600
use_tokenizer = Off
disable_software_reset = Off
use_output = Off
quick_data_rebuilding = Off
;
; Error handling options
;
[error_handling]
; Template for error pages
page = "public/error.html"
page_customer = "public/customer/error.html"
; Template for maintenance pages
maintenance = "public/maintenance.html"
;
; Marketplace
;
[marketplace]
url = "http://my.x-cart.com/index.php?q=api"
log_data = Off
upgrade_step_time_limit = 240
banner_url = "http://my.x-cart.com/xcinfo"
;
; Language options
;
[language]
default = en
;
; Installation parameters
;
[installation]
installation_lng = en
;
; AMQP server
;
[amqp]
host = "localhost"
port = "3306"
user = "guest"
password = ""
vhost = "/"
exchange = "xlite"
;
; HTML Purifier options
; See http://htmlpurifier.org/live/configdoc/plain.html for more details on HTML Purifier options
;
[html_purifier]
; Allow link 'target' attribute
Attr.AllowedFrameTargets = On
; List of allowed values for 'target' attribute
Attr.AllowedFrameTargets[] = _blank
Attr.AllowedFrameTargets[] = _self
Attr.AllowedFrameTargets[] = _top
Attr.AllowedFrameTargets[] = _parent
; Allow 'id' attribute
Attr.EnableID = On
; Allow embed tags
HTML.SafeEmbed = On
; Allow object tags
HTML.SafeObject = On
; Allow iframe tags
HTML.SafeIframe = On
; List of allowed URI (without http:// or https:// part) for iframe tags
; If there are no allowed URIs specified then any src will be allowed for iframe tags
;
; Examples:
;
; URI.SafeIframeRegexp[] = "www.youtube.com/embed/"
; URI.SafeIframeRegexp[] = "www.youtube-nocookie.com/embed/"
; URI.SafeIframeRegexp[] = "player.vimeo.com/video/"
;
; Other options
;
[other]
; Translation drive code - auto / gettext / db
translation_driver = auto
; Event driver code - auto / db / amqp
event_driver = auto
; List of trusted domains.
; This option prevents redirecting to untrusted URLs passed via returnURL parameter.
; Examples:
; trusted_domains = "google.com"
; trusted_domains = "google.com, yahoo.com"
trusted_domains =
; X-Frame-Options value
; For possible values see https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
; Examples:
; x_frame_options = 'disabled'
; x_frame_options = 'sameorigin'
x_frame_options = 'sameorigin'
; WARNING: Do not change the line below
; */ ?>
.htaccess at root folder
Options -Indexes
DirectoryIndex cart.php
FileETag none
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
<IfModule mod_rewrite.c>
RewriteEngine on
# #BUG-772 Add HTTP_AUTHORIZATION header for fastCGI (need for XC\Qiwi)
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteRule (^|/)\. - [F]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^sitemap.xml(\?.+)?$ cart.php?target=sitemap [NC,L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^((([/_a-z0-9-]+)/)?([_a-z0-9-]+)/)?([_a-z0-9-]+)(/?)(\.([_a-z0-9-]+))?$ cart.php?url=$5&last=$4&rest=$3&ext=$7 [NC,L,QSA]
RewriteBase /FSM
</IfModule>
<IfModule mod_expires.c>
# Expire images/js/css header
ExpiresActive On
ExpiresDefault A0
# Images expires in 2 weeks
ExpiresByType image/png A1209600
ExpiresByType image/gif A1209600
ExpiresByType image/jpg A1209600
ExpiresByType image/jpeg A1209600
ExpiresByType image/ico A1209600
ExpiresByType image/x-icon A1209600
# CSS/JS now work with dynamic unique query string. 1 year expires
ExpiresByType text/css A31104000
ExpiresByType text/javascript A31104000
ExpiresByType application/javascript A31104000
</IfModule>
# Clean URLs [[[
Options +FollowSymLinks -MultiViews -Indexes
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/(payment|admin|provider|partner)/
RewriteCond %{REQUEST_FILENAME} !\.(gif|jpe?g|png|js|css|swf|php|ico)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ dispatcher.php [L]
#/Clean URLs
I doubt it may be issue of .htaccess so I shared this files too Please help me to resolve this problem.
Can you please share the var/log/php_errors.log.<date>.php and xlite.log.<date>.php files?
The actual error should be there. Also, yon can set suppress_errors = Off and developer_mode = On in the etc/config.php file and run X-Cart again to see if it shows the actual error right in the browser.
You can check out the http://kb.x-cart.com/en/general_setup/moving_x-cart_to_another_location.html tutorial to see if you've completed each step correctly.

.htaccess Wildcard 301 redirect domain AND subfolders

So, I'm running into this problem with this relatively complicated wildcard 301 redirect. My .htaccess-foo is terrible, so I'm hoping for some help here!
I need to change any uppercase to lowercase.
I need to change "gfoldername" to "g"
I need to replace any "-" with "_"
To show an example, this is what I'm trying to accomplish
example.com/gfoldername/Another-Folder/
to
example.com/g/another_folder/
I've tried quite a bit with no luck. Again, any help is greatly appreciated!
EDIT:
Ended up resolving this myself with php. For those interested:
$urls = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$url = explode('/',$urls);
$f = $url[4];
$f = strtolower($f);
$f = str_replace("-", "_", $f);
$url = "http://example.com/g/".$f;
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$url);

How to do arithmetic operation in .rewriteRule function?

Is this possible to do arithmetic operation in .rewriteRule function?I want to rewrite my url.
From this
/view.php?id=2
To
/?p=6 (id*2+2)
You can use a rewrite map to call an external program, it's going to be a bit slower under heavy load though. The rewrite map can only be defined in the server's config or vhost config, not in an htaccess file. But it can be used in an htaccess file.
So you have a simple script that reads from stdin and does your math:
#!/usr/bin/perl
$| = 1; # Turn off I/O buffering
while (true) {
print <STDIN> * 2 + 2;
}
Then declare the mapping:
RewriteMap math prg:/path/to/script.pl
Then use the mapping in the htaccess file in your document root:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^view\.php$ /?p=${math:%1} [L]
To redirect http://example.com/view.php?id=2 to http://example.com/?p=6 you would do this:
in .htaccess:
RewriteEngine On
RewriteCond %{QUERY_STRING} id=([0-9]*)
RewriteRule view.php calc.php?id=%1 [L]
And in calc.php:
<?php
$base_url = 'http://example.com/?p=';
$id = $_GET['id'];
$new_id = $id * 2 + 2;
$url = $base_url.$new_id;
header("Location: $url");
exit();

Resources