PHP comment character escaping - php

I made a .htaccess file that redirects, for example, link:
website.com/module#controller
to:
website.com/?url=module#controller
As # is the PHP comment declarer, I get a problem when need to load:
$bootstrap->init($url) // $url = module#controller;
I tried to use addslashees($url);, but still when I:
echo $url;
I still get an output of:
module
How I should clear that string, to treat the # sign as part of the string?

$url = module#controller; is not valid PHP.
$url = 'module#controller'; will (correctly) not treat the # as a comment initiator.
Additionally, a # in a URL isn't going to work the way you expect. That's the marker for the URL hash/anchor, which is not passed to the web server. This is likely why you get output of module - your problem is at the browser level, not PHP.

The hashtag fragment identifier is a client-side concept only. The browser would never send a hashtag value to the server.
If you are relying on this functionality, your are going to be disappointed as server has absolutely no way to do redirection based on the hashtag, as it never even sees the hashtag.

Related

How do I find the second, or third instance of a character in a string in PHP

I am trying to parse out the middle of the referrer information just to check from where the form submission is coming from.
Consider that the referrer is "https://www.somewebsite.com/someform.php
And what I want to extract is the part between those first two "//" and the next one "/".
I can get the string position, but how can I do a quick piece of code that will just parse out the part I need without several steps?
$ref=strpos($_SERVER['HTTP_REFERER'],'://');
gives me 5 (as the position where the "://" is found.
I want to use something like substr(string,start,length) the part out that is needed to get the pure referrer
the part that says "www.somewebsite.com"
without all the extra lines of code
used it
echo $_SERVER['HTTP_HOST'];

file_get_contents not working on url with hashtag symbol in it

I have url which I want to parse:
http://www.ntvplus.ru/tv/#genre=all&channel=3385&channel=3384&channel=3416&date=22.02.2016&date=23.02.2016&date=24.02.2016&date=25.02.2016&time=day
I tried using both file_get_contents and CURL, but they both seem to only send request to http://www.ntvplus.ru/tv/ and ignore everything after hash symbol.
I tried escaping it but still no luck.
Can someone please provide working solution on this?
# elements are client-side only. They won't be parsed with a headless request such as file_get_contents() (or even cURL).
As #brevis has suggested in the comments, you have to use the query string version:
$content = file_get_contents('http://www.ntvplus.ru/tv/?genre=all&channel=3385&channel=3384&channel=3416&date=22.02.2016&date=23.02.2016&date=24.02.2016&date=25.02.2016&time=day');

PHP check if href is a file

I am using a script to check links on a given page. I am using simple html DOM to parse the information into an array. I have to check the href of all the a tags to find if they contain a file or something like # or JS.
I tried the following without success.
if(preg_match("|^(.*)|iU", $href)){
save_link();
}
I dont know it my pattern is wrong or if there is a better method to complete this function.
I want to be able to detect if $href contains .com .php .file extensions. This way it will filter out items like # "function()" and other items used in the href attribute.
EDIT:
parse_url will not work stop posting it. The value # returns as a valid url like I stated above I am trying to look for any string followed by .* with no more than 4 chars following the .
I believe that the function you're looking for is parse_url().
This function will take a URL string, and return an array of components, which will allow you to work out what kind of URL it is.
However note that it has issues with incomplete URLs in PHP versions prior to 5.4.7, so you need to have the very latest PHP to get the best out of it.
Hope that helps.
See http://php.net/manual/en/function.parse-url.php
I'm assuming you don't want to match fragments (#) because you are not concerned with following internal anchors.
parse_url breaks up the different parts of the url into an array. You can see the path component of the URL in this array and run your check against that.
You can use parse_url() , like this :
$res = parse_url($href);
if ( $res['scheme'] == 'http' || $res['scheme'] == 'https'){
//valid url
save_link();
}
UPDATE:
I've added code to filter only http and https urls, thanks to Baba for spotting this.

cutting special chars in folder name when using GET

I've been visiting stackoverflow.com for a long time and always found the solution to my problem. But this time it's different. That's why I'm posting my first question here.
The situation looks like this: My website provides a directory explorer which allows users to download whole directory as a zip file. The problem is I end up with error when I want to download a dir containg special characters in it's name, i.e. 'c++'. I don't want to force users to NOT name their folders with those special chars, so I need a clue on this one. I noticed that the whole problem comes down to GET protocol. I use ajax POST for example to roll out the directory content, but for making a .zip file and downloading it I need GET:
var dir_clicked = $(e.target).attr('path'); //let's say it equals '/c++'
window.location = 'myDownloadSite.php?directory_path='+dir_clicked;
I studied whole track of dir_clicked variable, step by step, and it seems that the variable in adress is sent correctly (I see the correct url in browser) but typing:
echo $_GET['directory_path']
in myDownloadSite.php prints
'/c'
instead of
'/c++'
Why the GET protocol is cutting my pluses?
You can use:
encodeURIComponent() //to get the url then use
decodeURIComponent() //to decode and access ur filename.
Use urlencode() and urldecode() on server side.
Try encoding your URI with encodeURI(url) JavaScript function.
window.location = encodeURI('myDownloadSite.php?directory_path=' + dir_clicked);
Maybe use encodeURIComponent() and then remove all %xx occurrences?
When the information is posted it is encoded with special chars, sounds like you just need to decode them before using the information.
You can use php function urldecode() to decode the folder names before using them...
$_GET[directory_path]=urldecode($_GET[directory_path]);

Cookies with extensions

I've seen cookies set by web pages with the "." character in them. I'm trying to maximize the dynamic use of a $_GET['url'] to set my cookies, and then include it in a next page as a conditional where it checks to make sure the cookie was set before it allows users to perform an action. Basically I'm using cookies and IP addresses in an anonymous voting action to make sure anyone who votes only gets one per day. IPs are reset through a cron job once a day, and the cookies are set to expire after 17 hours. I have no issues setting a cookie named with the .php extension, however after many hours of trial and error, I can't get it to accept it in an if(isset). No matter what I try, it will not recognize that the cookie is set. Without the extension everything works fine. I've tried a dozen configurations, but here's basically what I have trying to debug.
<?php
$cookie = "test.php";
setcookie("$cookie", "workdamnyou");
if (isset($_COOKIE[$cookie])) {
echo "is set";
}
else {
echo "not set";
}
?>
I've tried isset($_COOKIE["$cookie"]) and isset($COOKIE['$cookie']) as well. That said, I really wish you could run PHP without uploading it each time to your server.. --
setcookie doesn't change $_COOKIE immediately. It sets the headers to change the cookie in the browser, so the script won't see the test value until you refresh the page.
You CAN run PHP without uploading to a server; the easiest option is to install a xAMP stack (LAMP/MAMP/WAMP depending on if you're developing on Linux/Mac/Windows).
Well, I found the solution I guess... PHP doesn't like dots in variable names (http://www.php.net/manual/en/language.variables.basics.php). Now, since Register Globals could be on, it might be possible that a $_COOKIE["name.ext"] could turn into a $name.ext which would be invalid. Thus, "Dots and spaces in variable names are converted to underscores. For example becomes $_REQUEST["a_b"]." (http://www.php.net/manual/en/language.variables.external.php). Does a check for isset("name_php") work?
You cannot set and access a cookie in the same instance! You have to do a redirect, refresh or something, but you cannot both set and access at the same time. Also make sure your other parameters are set like hostname, expiry time. . e.t.c
Eg.
setcookie("TestCookie", $value, time()+3600, "/", "/", 1);
For debugging, just do a var_dump($_COOKIE)
Note that cookies only become available on the next pageload (when they have traversed from server to client and back).
Try setting the cookie directly with $_COOKIES["test.php"] = "test"; and see what happens with
var_dump($_COOKIE);
Also don't use the quotes around the $cookie variable. Thus make it
setcookie($cookie, "work");
instead of
setcookie("$cookie", "work");
Last, you can run PHP locally with your own server. The easiest way on Windows is the WAMPP stack. I find this one very easy to install and run: http://www.apachefriends.org/en/xampp.html
Good luck!
Why would you have a .php extension in the cookie name? It should be:
$cookie = 'test';
See http://www.ietf.org/rfc/rfc2109.txt point 4.1:
The two state management headers, Set-Cookie and Cookie, have common
syntactic properties involving attribute-value pairs. The
following grammar uses the notation, and tokens DIGIT (decimal
digits) and token (informally, a sequence of non-special, non-white
space characters) from the HTTP/1.1 specification [RFC 2068] to
describe their syntax.
av-pairs = av-pair *(";" av-pair)
av-pair = attr ["=" value] ; optional value
attr = token
value = word
word = token | quoted-string
Attributes (names) (attr) are case-insensitive. White space is
permitted between tokens. Note that while the above syntax
description shows value as optional, most attrs require them.
NOTE: The syntax above allows whitespace between the attribute and
the = sign.

Categories