Currently using this code:
str_replace(".php","",basename($_SERVER['REQUEST_URI']))
and it outputs like this:
Rusko%20-%20Skanker.mp3&sort=1
i need it to display so: Rusko - Skanker
you can use urldecode():
urldecode($_SERVER['REQUEST_URI']);
Say you have the following URL:
script.php?file=Rusko%20-%20Sanker.mp3&sort=1
Then, to get the result you are looking for, you would want:
echo htmlentities( urldecode( str_replace( '.mp3', '', $_GET['file'] ) ), ENT_QUOTES );
The other answers aren't quite complete because they will include the entire URL in the output. You seem to be looking for just one query string parameter.
Note: htmlentities() is VERY important in this case to protect your website and users. Printing any user submitted data on a page without properly sanitizing it first allows for code injection.
Related
I have (maybe) an unusual issue with using __FILE__ in a file within a file.
I created a snippet of code (in the php 5 my server mandates) to take elements of the current filename and put it into a variable to use later. After some headache, I got it working totally fine. However, I realized I didn't want to have to write it every time and realized "oh no, if I include this it's only going to work on the literal filename of the include". If I wanted to grab the filename of the page the user is looking at, as opposed to the literal name of the included file, what's the best approach? Grab the URL from the address bar? Use a different magic variable?
EDIT1: Example
I probably should have provided an example in the first draft, pfft. Say I have numbered files, and the header where the include takes place in is 01header.php, but the file it's displayed in is Article0018.html. I used:
$bn = (int) filter_var(__FILE__, FILTER_SANITIZE_NUMBER_INT);
…to get the article number, but realized it would get the 1 in the header instead.
EDIT2: Temporary Solution
I've """solved""" the issue by creating a function to get the URL / URI and putting it into the variable $infile, and replaced all former appearances of __FILE__ with $infile, like so:
function getAddress() {
$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
return $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];}
$infile = urlencode(getAddress());
$bn = (int) filter_var($infile, FILTER_SANITIZE_NUMBER_INT);
echo "$bn";
So if the file the user is looking at is called "005-extremelynormalfile.html", I can display the number 5 inside the page, e.g., to say it's article number five.
While it's not as bad as I initially thought based on your description your code is still very fragile, and really only works by accident. If you have any other digits or hyphens it's going to go wrong, as below.
$infile = 'https://example-123.com/foo/42/bar/005-extremelynormalfile.html?x=8&y=9';
var_dump(
filter_var($infile, FILTER_SANITIZE_NUMBER_INT),
(int)filter_var($infile, FILTER_SANITIZE_NUMBER_INT)
);
Output:
string(12) "-12342005-89"
int(-12342005)
Sanitize functions are a blunt instrument for destroying data, and should only ever be used as a last resort when all other good sense has failed.
You need to use a proper parsing function to parse the url into its component parts, and then a simple regular expression to get what you want out of the filename.
function getIdFromURL($url) {
$url_parts = parse_url($url);
$path = $url_parts['path'];
$path_parts = explode('/', $path);
$filename = end($path_parts);
if( preg_match('/^(\d+)/', $filename, $matches) ) {
return (int)$matches[1];
}
return null;
}
var_dump(
getIdFromURL($infile)
);
Lastly, a lot of people are tempted to cram as much logic as possible into a regular expression. If I wanted to the above could be a single regex, but it would also be rigid, unreadable, and unmaintainable. Use regular expressions sparingly, as there's nearly always a parser/library that already does what you want, or the majority of it.
Quickly threw together a function that gets the url from the page as a variable, and replaced all occurrences of __FILE__ with that variable, and it worked correctly. Assuming the user cannot edit the URL / URI in any way, this should work well enough.
I have a page that uses an input field to search, and then uses that same field to go across pages. It also accepts double quotes for exact searching.
The url needs to look like blahblah.com/search/%22querystuff%22, but it autodefaults to blahblah.com/search/"querystuff" which fails in the browser.
Is there any way to get it to stop doing that or do I need to look into a different method.
Try out the urlencode method.
Here is an example of how to use it:
<?php
$userinput = '"Hello world"';
echo '<a href="http://blahblah.com/search/', urlencode($userinput), '">';
?>
Fetch data from mysql.
Then echo with echo htmlspecialchars( $content['MainText'] , ENT_NOQUOTES, "UTF-8");.
Tried to echo without htmlspecialchars javascript like <script> alert('Hello');</script> and saw pop up box. So it is not good to echo without htmlspecialchars.
But with htmlspecialchars can not correctly display hyperlinks and images and also <h2>, <span> etc. Also not acceptable.
At the moment tried to replace some characters like
$content_main_text_modified =
str_replace(
array( '<br/>', '<br>', '</a>', ">", '<a', '<div', '<img', '</div', '<h2', '</h2', 'amp;amp;', '<span', '</span' ),
array( '<br/>', '<br>', '</a>', ">", '<a', '<div', '<img', '</div', '<h2', '</h2', '', '<span', '</span' ),
( htmlspecialchars( $content['MainText'] , ENT_NOQUOTES, "UTF-8") )
);
echo $content_main_text_modified;
My idea is not to replace sole < with <, but instead to replace < together br, a, <h2. So if in mysql would be like <script> it would not execute.
Want to check (get opions) if my idea is safe idea? And possibly some recommendations.
I think a different idea would be to stop it being stored that way in the first place so that you can just echo it. What you are referring to is an xss attack where someone can enter JavaScript that can then be executed on another users browser take a look at this link for more detailed information about xss click here.
As for a way to remove it what I would do is some form of validation on the imputed data there are so many ways to do this I would suggest reading the link above and that will give you an idea how to stop it and mean you can then just do a simple echo. Doing validation like this will also help to prevent sql injection attacks although that will require some more work.
This wont work every time and some people also suggest that you use htmlspecialchars but when you are working with html this causes issues as you know, you just have to make your best attempt no system can stop everything.
Not knowing exactly what your are doing it is impossible to say but you might find it useful to use some kind of template engine so the HTML is sepperate from the code and you can use the function htmlspecialchars() as you can then just pass out text to the template.
Take a look at http://htmlpurifier.org/ and the HTML.Allowed directive; where you can set tags that are allowed.
Use strip_tags($content['MainText'], '<a><h2><div><span><br><img>');
Or you can use htmlspecialchars then use this preg_replace('#<(/?(?:a|h2|div|span|br|img))>#', '<\1>', $html);, for example:
$content_main_text_modified = htmlspecialchars($content['MainText']);
$content_main_text_modified = reg_replace('#<(/?(?:a|h2|div|span|br|img))>#', '<$1>', $content_main_text_modified);
http://au1.php.net/manual/en/function.strip-tags.php
When I grab the title from my Word Press posts in code and pass them around as email, the punctuation gets a bit mangled.
For example "TAMAGOTCHI P’S LOVE & MELODY SET" comes out as "TAMAGOTCHI P’S LOVE & MELODY SET".
Any ideas how I prevent this?
Let me know if you need to see the specific code I'm currently using. (I'm not really sure if this is a WordPress issue, or a PHP issue.
EDIT
What happens is that this title is passed to a form via the query string. Then when the form is submitted, I take the string from the form field and email it.
So I guess I need to decode the html either before I pass it into the form field, or else before I email it.
EDIT 2
Weird, so I looked closer at the code and I'm already doing a urldecode before I pass the value into the form field
jQuery('#product_name').val("<?php echo urldecode(strip_tags($_GET['pname'])); ?>
Is there some default encoding happening when you serialize (for ajax formhandler)
var dataString = $(this).serialize();
EDIT 3
OK turns out the code is more complex. Title is also passed to some kind of wordpress session before it's hits the form. I'll figure it out where exactly I need to put urldecode. Thanks!
This is one WordPress "feature" I could do without.
Here's one down-n-dirty method to get the fancy quotes (or other entities) replaced:
$title = get_the_title( get_the_ID() );
$title = str_replace( '’', "'", $title );
echo $title;
We could integrate deeper, by hooking into the_title, if you want this same de-entities functionality throughout the site. This code block would belong in your theme's functions.php file.
function reform_title($title, $id) {
$title = str_replace( '’', "'", $title );
return $title;
}
add_filter('the_title', 'reform_title', 10, 2);
Im not really sure about wordpress, but the issue itself its that the text its coming out as URLENCODE instead of a UTF-8 or other encode.
You have two options
When you receive the text you never turn it back to normal encoding (Which is weird as usually is de-encoded by php when you access the $_GET or $_POST variables)
You are parsing the message with the urlencode() function.
I am trying to create mini CMS, where user can create new page and then that page become part of menu. Is it smart to insert full pages into database or there is better way to do so? Also I am having a bit of the problem with a tag when I am inserting.
Code for now:
For inserting page into db:
public function strana_insert()
{
$this->admin_login_check();
$clear = $this->str->clean_request();
$char = array('\n', '\n');
$strana = str_replace($char, '<br>', $clear['opis']);
$kljucna_rec = str_replace( ' ', '_', mb_convert_case($clear['naziv'], MB_CASE_LOWER, "UTF-8") );
$data = array(
'naziv' => $clear['naziv'],
'strana' => htmlspecialchars($strana, ENT_QUOTES , "UTF-8"),
'kljucna_rec' => $kljucna_rec,
'datum_kreiranja' => date("Y-m-d H:i:s")
);
$this->str->save($data);
$this->save_routes();
redirect('admin');
}
Code for clean_request function:
public function clean_request()
{
foreach($_POST as $key=>$value) :
$clean[$key]=mysql_real_escape_string(trim($value));
endforeach;
return $clean;
}
When I insert page with a tag I get following result:
www.example.com
After updating page everything between *\ * is deleted. What is going on here?
You can use Codeigniter's active class to insert this OR use the following method.
before inserting HTML data to database do this :
$html_for_db = addslashes($html_content);
and insert $html_for_db to database.
While displaying this content,
echo stripcslashes($data_from_db);
stripcslashes() - Un-quote string quoted with addcslashes
More info : http://php.net/manual/en/function.addslashes.php
it's because of escape function!!
htmlspecialchar change your code to just a simple string!!
if you'd like to save as html you should save the code without escaping!
BTW, This isn't an smart way to create a static pages, You may like to create a layout and simply let users put content in it ;)
If you want to store html in your DB I recommend using htmlpurifier to clean up your html code and also strip out unwanted html tags.
http://htmlpurifier.org/
There is also a helper which makes using htmlpurifier within CodeIgniter really easy: https://github.com/refringe/codeigniter-htmlpurifier
After you cleaned your input string with htmlpurifier you should use Codeigniters Active Record class to insert your data (http://ellislab.com/codeigniter/user-guide/database/active_record.html). This way the framework will do the escaping.
You have to prevent two types of attacks here: SQL injection and cross-side scripting. You considered both and used htmlspecialchars() against XSS and mysql_real_escape_string() against SQL injection.
But you used them in the wrong order. You first have to use htmlspecialchars, because that's the thing you want to store/output. To put it savely into the database you have to wrap it into its mysql_real_escape_string-ized presentation before storing it or use parameter binding instead.