Hi I have the following page which sets a cookie with the current URL and also a simple external link.
<?php
function pageURL()
{
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on")
{
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
$CurrentPage = pageURL();
setcookie('linkback', $CurrentPage);
?>
<p>External Link</p>
What I want to do is using PHP add a prefix to all external links so that they have have the following structure:
localhost/outgoing?url=http://www.google.com/
This loads up an outgoing page like so:
<?php
if(!isset($_GET['url']))
{
header('HTTP/1.0 404 Not Found');
}
?>
<h1>Warning! Now leaving website</h1>
<ul>
<li><a title="Return to Website" href="<?php if(isset($_COOKIE['linkback'])) { echo $_COOKIE['linkback']; } else { echo 'http://localhost:8888/creathive/'; } ?>">Return to Website</a></li>
<li><a title="Continue to <?php echo $_GET['url']; ?>" href="<?php echo $_GET['url']; ?>">Continue to <?php echo $_GET['url']; ?></a></li>
</ul>
The idea is that using the cookie set in the previous page I can have a simple back button, and also grab the url from the query and allow the user to continue after being warned they are leaving the site.
The problems I have are:
1.) Prefixing external URLS so that they go to the outgoing page
2.) The isset on the top of the outgoing page is supposed to be throwing a 404 if a user visits the outgoing page without a url query string but isn't
3.) Need to make sure that URLS are valid so for example prevent this for happening: localhost/outgoing?url=moo
You will need to replace every external URL in your code according to the new scheme. There is no way doing this automaticalle for all outgoing links.
This is because, if the user clicks on an external URL, the request is not sent to your server, but the external one.
Edit:
The only thing you could do is caching all your output with ob_start() and then replace all links using a regexp, before printing them on your page.
But the better solution would be to replace all links yourself.
Can you elaborate?
Isset isnt exactly the "right" tool. try arrya_key_exists('url', $_GET)…. Code like this should do ya.
function haveUrl() {
if (array_key_exists('url', $_GET)) {
$url = $_GET['url'];
if (!empty($url)) return true;
}
return false;
}
You can simply check to see if they start with http:// or https://... This may be done best with a regex…. something like…
function validUrl($url) {
if (preg_match('\^(http:\/\/|https:\/\/)\mi', $url) {
if (preg_match('\localhost\mi', $url) return false;
else return trus;
}
return false;
}
1) I would create a class for all links, and use something like $links->create("http://...")
and there you place the redirection and everything you might need.
3)
You could use the code in the following link:
link text
1.) Prefixing external URLS so that they go to the outgoing page
You need a DOM tool for this. For instance SimpleXML or Simple HTML DOM parser or any of it's kind to manipulate the outgoing links on the page you are rendering. (Find more available options in this question.)
Optimally, you will cache the results of this operation as it can be quite expensive (read: slow) and update the cached version on update or after a defined period of time.
2.) The isset on the top of the outgoing page is supposed to be throwing a 404 if a user visits the outgoing page without a url query string but isn't
Yes it does, but you need to stop execution after this point if you don't want to render the rest of the page. A 404 error can - and should! - have a page body, it's a response like any other HTTP response.
3.) Need to make sure that URLS are valid so for example prevent this for happening: localhost/outgoing?url=moo
Even if you do so - and indeed you should, nothing will prevent anyone from accessing localhost/outgoing?url=foo by manual URL manipulation. Url parameters, or any other user input can never be trusted. In other words you need to check the outgoing url in the outgoing-script no matter what.
And don't forget to sanitize rigourously! Functionality such as this is screaming to be abused.
Related
I have a script that builds a document into a pdf after a form has been completed, it's a custom template script for Gravitypdf, after the user has submitted the form they click on a link to generate and download the pdf.
If I exit() the script at the very end of the template code it displays the plain text page generated for the compilation in the browser without making the pdf. So far so good.
I want to have working the existing link to the pdf and an alternative link to the html (text in browser) version on the confirmation page after submission.
I am trying to code that if the url happens to be xyz (the link for the html version) then execute the exit() command and output the html version. If it is anything other than that url then ignore that command and fully compile the pdf eg when the alternative pdf download link is chosen.
I thought initially I should be looking at using exit(header('Location: xxxxx.php')); but found this is a redirect, I then looked at <?php if
($_SERVER['REQUEST_URI'] === 'https://example.com/pdf/5a47cec7d4b62/{entry_id}/textversion') {
exit();
} but that's not working.
How should I go about doing this? (The {entry_id} part of the url varies for each fillout of the form when the link generates via Gravitypdf - that works fine).
Thanks in advance.
EDITED UPDATE: I managed to get it working and tied in preg_match using ([^&]*) for the variable in the url. My clickable link for user is eg. example.com/pdf/5a47cec7d4b62/{entry_id}/textversion
`<?php
function currentUrl( $trim_query_string = false ) {
$pageURL = (isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on') ?
"https://" : "http://";
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
if( ! $trim_query_string ) {
return $pageURL;
} else {
$url = explode( '?', $pageURL );
return $url[0];
}
}
?>
<?php if
(preg_match("#^https://example.com/pdf/5a47cec7d4b62/([^&]*)/textversion#",
currentUrl())): ?>
<?php exit() ?>
<?php endif; ?> `
I have read some stackoverflow hyperlinks about how to redirect to the previous browsed page after a user logs in or creates a new post in a forum. I have found that most of the answers mentioned about using AJAX or javascript or the like, because most of the answerers think that it should only happen on the client side. Furthermore, most of their codes provided helpfully advised how to redirect to a certain page like index.php after log-in.
For me, what i really want to do now is how to redirect to the previous browsed/visited page after clicking the submit button of the form by using PHP (PLEASE FORGET ABOUT AJAX OR JAVASCRIPT NOW). I don't redirect users to any certain assigned page, but to the page immediately before it. For example, a user visits the index.php, then clicks a hyperlink on it to go to the posts.php page to view the new posts, and then he's interested in the forum, he then goes to the login.php page from the http://domain.com/posts.php?qid=7, for instance, to sign in so that he can reply to the post if he wants to or does something else. In this scenario, after he logs in, the forum would *REDIRECT* him to the immediately previous posts.php page, which is http://domain.com/posts.php?qid=7. That is what I want to code now.
And this is the function I just created:
function str_url($a, $b) {
return substr($a, 0, strpos($a, $b));
}
function self_url() {
if(!isset($_SERVER['REQUEST_URI'])) {
$self = $_SERVER['PHP_SELF'];
}else{
$self = $_SERVER['REQUEST_URI'];
}
$secure = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s":"";
$protocol_secure = str_url(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$secure;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
$_SESSION['previous'] = $protocol_secure."://".$_SERVER['SERVER_NAME'].$port.$self;
header("Location: " . $_SESSION['previous']);
}
All I have to do is to place the functions in the head of the document and the self_url(); anywhere within the PHP code after the form checking and submission conditionals that I want.
The problem is that the function self_url(); just checks the domain.com/posts.php to redirect the logged-in users to (it truncates the rest part of the URL), but not the whole long URL of the previously visited page like http://domain.com/posts.php?qid=7 (in which the id=7 is the name=value pair of a certain post) he just visited before he signed in.
Can you help me to isolate the reason, please? Or If you have any handy PHP function to replace mine, I'll appreciate it.
The previous URL might be visible to you via $_SERVER['HTTP_REFERER'] so you could just take this as your redirection target. But this is not very reliable - from the docs:
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents
will set this, and some provide the ability to modify HTTP_REFERER as
a feature. In short, it cannot really be trusted.
The better approach would be to let the previous script insert a GET parameter of itself so your redirection script knows where the user was before.
Well, you could store every visited page a cookie or session and just read it from there but that doesn't make much sense in my opinion.
//edit some code:
if(!isset($_SERVER['REQUEST_URI'])) {
$self = $_SERVER['PHP_SELF'];
}else{
$self = $_SERVER['REQUEST_URI'];
}
Just append ?redir=$self to the action of your form.
I want to display different pages in iframe, according to the parent url loaded. I have a mysql DB, which will be used for this purpose. I use the following code to call the appropriate link from the DB, but instead of showing that page, the iframe shows nothing (blank space).
This is the code, which I insert in my php files:
function curPageURL() {
$pageURL = 'http://';
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
return $pageURL;
}
$conn=mysql_connect("localhost","user","password");
echo mysql_error();
mysql_select_db("db-name",$conn)or die(mysql_error());
$url=curpageURL();
$url=substr($url,0,strpos($url,'.',strpos($url,'?')));
$rs=mysql_query("select * from table-name where column1='".$url."'",$conn);
$affi=mysql_fetch_array($rs);
echo mysql_error();
echo '<iframe src="'. $affi['column2'].'" width="700" height="400"></iframe>';
As I said, this code shows only blank space and not the appropriate page. My site is running on SMF engine (Simple Machines Forum).
I hope someone can point me out what has to be changed in the code.
Thank you!
Let say we've the following
Objective : User will post certain exact URL $refere to lock viewing text content and only be allowed for view if the viwer is coming from the same exact URL $refere.
$refere = "http://www.site_site.com"; // User will post it
$r = $_SERVER['HTTP_REFERER']; // To get real referral
and i want to do the following
<?PHP
if(stripos($r, $refere) == false){
echo "Wrong";
} else { ?>
echo "Go";
}
?>
It always gives me $r = $_SERVER['HTTP_REFERER']; blank ! so does it deprecated on any PHP version 4 or 5 whatever !
Also
what is the user posted $refere like https:// or missed www. or only posted site_site.com while the $r = $_SERVER['HTTP_REFERER']; showing www.site_site.com
so can anyone help me to adjust this code to be working fine no matter the user posted the $refere link fully or only site_site.com.
The $_SERVER['REFERER'] variable will only be set when you click a link to your page from another page and if the browser (or an eventual proxy or firewall you're on) isn't removing the referer header.
To your second question: do some string comparisons. The functions strpos() and substr() will be of great help.
I have a custom 404 page which works fine except for the message I want to display on this page.
I would like it to say the url of the page which can't be found but instead it displays the url of the 404 page.
Here's what I have...
You were looking for <?php echo $_SERVER['REQUEST_URI'] ?>.
The htaccess file contains the line: ErrorDocument 404 /404/
You need to use $_SERVER['HTTP_REFERER'] instead - that will be the address they requested first.
This only works in the exact case described in the question - where the browser has actually been redirected to the 404 page. In that situation, $_SERVER['REQUEST_URI'] contains the URI of the 404 page rather than the originally requested page as described.
Using Apache's ErrorDocument 404 /handle404.php in the site config or .htaccess would mean that $_SERVER['REQUEST_URI'] would actually work, but a more robust solution is the option in the update below.
Update:
Apparently $_SERVER['REDIRECT_URL'] might be a better bet however, having searched around a bit.
For both cases, as mentioned by the commenters below, bear in mind that any headers are just as prone to malicious content as $_POST, $_GET and others, so process them before outputting anything.
Update 2:
Didn't see the post from #Janoz below - he correctly mentions REDIRECT_URL.
From the perspective of the php page, that really is the request uri. Showing the error page is done by the webserver. Apache for example will add some extra server variables. REDIRECT_URL is probably the one you are looking for.
I did not write this function but it is what I use to do the same thing:
function selfURL() {
$s = empty($_SERVER["HTTPS"]) ? ''
: ($_SERVER["HTTPS"] == "on") ? "s"
: "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? ""
: (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function strleft($s1, $s2) {
return substr($s1, 0, strpos($s1, $s2));
}
then to print it:
<?php print(selfURL()); ?>
If a page doesn't exist you redirect him to the 404 page? Idealy, I would display the 404 directly on the page which wasn't found. This way, you don't have to redirect, and you can correctly use REQUEST_URI. And the code for your 404 can still be centralized!
use file_exists to check whether the file your user is looking for exists or not. if it doesn't the redirect them to a custom made error page.