I've worked with laravel earlier this year and I liked the idea of using url to access REST client. I was wondering how I'd be able to redirect from non-existant URL to an existing url and keeping that GET data.
Is it even possible with the current php implementation?
Thanks in advance!
EDIT:
For example, let's say that I want to allow logged in users download a file. Said file would be downloaded from a following url: http://example.ex/image.png
But if I just put my image.png into the root of my webserver, it'd be downloadable by anyone, as it's a direct link. How would I use the same URL, but to supply index.php with $_GET['url'] = image.png, so I could give a temporary download link to a user if the user is logged in.
You can do it like this (in PHP) I don't code Laravel
$arr_url = parse_url('http://example.com/old_location?foo=bar');
$query = !empty($arr_url['query']) ? '?'.$arr_url['query'] : '';
header("Location: http://example.com/new_location{$query}");
exit;
OR you can use $_SERVER ( I forget if it includes the ?)
$query = !empty($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : '';
header("Location: http://example.com/new_location{$query}");
Two important things.
no output before calling header not so much as a single space
call exit after using header.
from non-existant URL
As I said I don't use Laraval, so I can't speak on to how it handles 404's so you would need to do the redirection in the controller that handles that, which would require some logic to decide to redirect or not.
UPDATE
I want to do it in PHP, but this doesn't really help if my URL ending with image.png isn't a valid php file.
Saying access REST implies that it will be a PHP file. If you just mean finding if a file exists and redirecting then use HTACCESS
#if not is a real file
RewriteCond %{REQUEST_FILENAME} !-f
//redirect
How you decide where to redirect is an open question, as this is to broad for me to give a specific answer.
One last thing is your .png example. It's possible to use a .php file to return image data, with the correct headers. I once built a site that stored user images in a Zip file and then only displayed images if a user was logged in, by streaming the contents of the file from the ZIP (no temp files).
Everything the server returns is text, the only reason it's seen as an image is because Apache knows that .png should have Content-type: image/jpng or something like that for the content header. Something that can be "faked" in PHP.
Related
I have a subfolder that holds user uploaded files. I want to redirect all direct file requests to this folder to another .php script...so i can check if the user is logged in before i send/show the file to him.
For example:
/mainsite/uploads/user/2324/file.pdf
needs to be forwarded to
/mainsite/uploads/permissions.php
But i need inside the permissions.php to be able to do:
$url = $_SERVER['REQUEST_URI'];
and see what was the initial request...in order to readfile() the file after all the 'checking'.
I've tried this:
RewriteEngine On
RewriteRule ^/uploads/user/?$ /uploads/permissions.php [R=301,L]
but this is just a simple forwarding...i got no idea what file or folder the user requested.
I know i can do this by creating an individual htaccess file inside every folder that is created under 'user/{userid}' but i wanted a simpler function. I dont want to have 10000 htaccess files, if i can do this with just one.
Thanks
try with this syntax: (i added the R=301 part, which wasn't necessary in my version, so it is not fully tested, works without the R option)
RewriteRule "^/uploads/user/(.+)$" "/uploads/permissions.php?file=$1" [R=301,QSA,L]
You can the get your file var in the $_GET array in permissions.php. However, i wouldn't recommend to use directly this value because it can be unsecure. The best way is to only allow fixed values, with a switch for example, having filtered the var as a string before.
As a precaution I am wanting to use PHP to create an easily reusable/modifiable means to redirect users to a specified URL.
I have the usual php header redirect:
<?php
header( 'Location: http://www.stackoverflow.com/' ) ;
?>
What I'd prefer to do however, as this file will be placed across a lot of directories, to make life easier, and have the url extracted from an external file, e.g.
http://www.stackoverflow.com/url.xml
This would of course contain the URL of the website in question, unless there is another way to capture the domain itself automatically? This I'm not sure.
Could anyone be kind enough to show how this would be done or provide the best approach?
Thank you.
I was thinking in the same approach as #adam , i don't recommend you to extract urls from a file because it can be read from an attacker. It's better to include them in a php file as variables, an array or any other data structure.
Store the urls once in a file called config.inc.php:
<?php
define('USER_PATH', '/redirect/user/path');
define('ADMIN_PATH', '/redirect/admin/path');
?>
Then in your php file:
<?php
include 'config.inc.php';
header( "Location: http://{$_SERVER['HTTP_HOST']} . USER_PATH ) ; //or whatever variable you want to use to redirect.
?>
If you want to redirect some folders due to security issues you can do it with an Apache's htaccess.
Just put this at root folder then add the last line as many as you want for each redirection.
Each folder mentioned here can only be accessed by scripts running on the server.
Using this every access request using HTTP gets redirected. So this only works for directories containing scripts to be included. It doesn't work for i.e. image directories whose index shouldn't be shown, but the images should stay accessible.
RewriteEngine on
RewriteBase /
RewriteRule ^includes/(.*) http://www.stackoverflow.com/ [R=301,L]
RewriteRule ^includes/(.*) http://www.stackoverflow.com/ [R=301,L]
If you aren't familiar with this you can use http://www.htaccessredirect.net/
If the file containing the url is on a domain you don't control, there are security risks.
Instead, store the url once in a file called config.inc.php:
<?php
define('REDIRECT_URL', '/redirect/path');
?>
Then include it in your project:
<?php
include 'config.inc.php';
echo REDIRECT_URL;
// /redirect/path
?>
this is my first post so go easy on me.
Basically I am doing some rewrites in my htaccess file to change my made up search friendly URLs into actual URLs, and for the most part they are working. For instance this:
http://www.negativeworld.org/7849/news/nintendo-download-for-may-24-2012
Will turn into this:
http://www.negativeworld.org/article.php?id=7849
Just fine... IF that article exists. If the article doesn't exist, the php code uses this:
header("Location: boarderror.php");
exit;
To bring the user to boarderror.php. This works fine if it the user gets there directly on article.php and the id is bad, but when I am trying to do the htaccess redirect from a search friendly url and the id is bad, the htaccess redirect just hangs for awhile before giving me this message: "The page isn't redirecting properly".
What I want is for it to go to my boarderror.php page when there is a bad id. So basically I want my htaccess page to take a server friendly URL, switch to the true URL, and well... just let go at that point, and the PHP will take it from there. Here is my htaccess line that does the switch:
RewriteRule ^([0-9]+)/(news|review|editorial|podcast)/(.*)$ /article.php?id=$1 [L]
What am I doing wrong? (BTW I realize that if I set up all of my search friendly URLs correctly there should never be a bad id anyway, but I want to be on the safe side...)
Your thoughts aren't wrong. For a wrong ID there is a double redirection which is OK. The problem is how the second redirection happens. Try
header("Location: http://www.negativeworld.org/boarderror.php");
or
header("Location: /boarderror.php");
With your redirection the browser is trying http://www.negativeworld.org/9999/news/boarderror.php (being 9999 the wrong ID) which falls in an endless redirection loop that the browser cuts after 10 tries.
The redirect rule is fine, the issue is in your header function call. When you only provide a file name, the header redirect will send the user to the file in the same folder, much like creating an html link using only the filename.
Let's say i try to load http://www.negativeworld.org/99999/news/nintendo-download-for-may-24-2012 and that id is invalid. In this case it would send send the user to http://www.negativeworld.org/99999/news/boarderror.php which triggers the redirect again and gets stuck in an infinite loop (or would if the browser wasn't smart enough to stop requesting the same URL over and over again).
Per RFC 2616 the location header should provide an absolute URI, so you should do something like this:
header("Location: http://www.negativeworld.org/boarderror.php");
exit;
I have a directory named "goto" and a file inside called index.php. Currently the following is inside the index.php file:
<?php
$url = $_GET['url'];
header("Location: $url");
?>
At the moment to redirect to another URL I have to type this into the address bar:
http://mysite.com/goto/?url=http://google.com
I would appreciate it if you could tell me how I could change that URL so that I could redirect the user to a website by typing this into the address bar:
http://mysite.com/goto/http://google.com
Use mod_rewrite and .htaccess to rewrite http://mysite.com/goto/http://google.com as http://mysite.com/goto/?url=http://google.com
RewriteEngine On
RewriteRule ^goto/(.+)$ /goto/?url=$1 [L]
Depending on your server configuration you may need to include a / in your rewrite path (i.e., ^/goto/(.+)$).
Unless you want to become a malware hub, I would wholeheartedly recommend you not doing this.
If you wish to allow redirect in such a manner, using http://mysite.com/goto/google and then work out the domain from a whitelist of available, allowed, destinations.
You will need to parse the data which could be a little tricky because you have to differentiate the difference between your URL and the other URL.
My suggestion is to not do so because the second that header is launched you will not see the url and it be better for you to just pass it as a get statement or a post.
EDIT
If you're determined then parse_url() is what you want. :)
#ide's method would work ... but you could also have the PHP script examine $_SERVER['PATH_INFO'], which is how that part of the URL would get passed to the CGI script.
(although, if there's a question mark in there, you'll also have to either make sure it's URI encoded, or also get the QUERY_STRING; you'll also lose any part after a hash, but you'd have the same problem with your current scheme)
I have designed a website, and within it I have a range of PHP scripts which interact with my system. For example, if a user uploads an image, this is processed by the script
image.php
and if a user logs in this is processed by the script
login.php
All these scripts are stored in the folder called: scripts
How do I ensure someone cannot access these pages, however still ensure they can be used by the system? I want to ensure the PHP pages will accept post values, get values and can redirect to other pages, but not be directly accessed via the address bar or downloaded?
I attempted to block access using .htaccess using deny from all and Limit GET, POST but this prevented the system from working as I could not access those files at all.
Blocking files with htaccess makes the files inaccessible to the requestor, e.g. the visitor of the page. So you need a proxy file to pass the visitor's request to the files. For that, have a look at the MVC pattern and the Front Controller pattern.
Basically, what you will want to do is route all requests to a single point of entry, e.g. index.php and decide from there, which action(your scripts) is called to process the request. Then you could place your scripts and templates outside the publicly accessible folder or, if that is impossible (on some shared hosts), protect the folders with htaccess like you already did (DENY FROM ALL) then.
To use the upload script you'd have a URL like http://example.com/index.php?action=upload.
A supersimple FrontController is as easy as
$scriptPath = 'path/to/your/scripts/directory/';
$defaultAction = 'action404.php';
$requestedAction = $_GET['action']; // you might want to sanitize this
switch($action) {
case 'upload':
$actionScript = 'image.php';
break;
case 'login':
$actionScript = 'login.php';
break;
default:
$actionScript = $defaultAction;
}
include $scriptPath . $actionScript;
exit;
Your actionScript would then do everything you need to do with the request, including redirection, db access, authentication, uploading stuff, rendering templates, etc - whatever you deem necessary. The default action in the example above could look like this:
<?php // action404.php
header('HTTP/1.1 404 File Not Found');
fpassthru('path/to/template/directory/error404.html');
There is numerous implementations of the FrontController pattern in PHP. Some simple, some complex. The CodeIgniter framework uses a lightweight MVC/FrontController implementation that might not be too overwhelming if this is new to to you.
Like Atli above suggested, you could use mod_rewrite to force all requests to index.php and you could also use it to pretty up your URLs. This is common practice with MVC frameworks and has been covered extensively here and elsewhere.
You can't really prevent direct requests to the files, and still have them remain accessible to other requests. The best you can do is mask their location, and control how they are accessed.
One way you could go is to create a PHP "switch" script, which would include the scripts for you, rather than have Apache request them directly.
For example, if you had your scripts/image.php rule target switch.php?file=image.php instead, somewhat like:
RewriteRule ([^\.]+\.(jpe?g|png|gif)$ switch.php?file=image.php&rw=1&meta=$1 [L,QSA]
You could add deny from all to the scripts/.htaccess file and do this in your switch.php file.
<?php
/** File: switch.php **/
$allowed_files = array(
'login.php',
'image.php'
);
$script_dir = 'scripts/';
if(isset($_POST['rw']) && in_array($_REQUEST['file'], $allowed_files)) {
include $script_dir . $allowed_files[$_REQUEST['file']];
}
else {
header('HTTP/1.1 404 File Not Found');
include 'error404.html'; // Or something to that effect.
}
?>
The $_POST['rw'] there is a weak check, to see if the rule came from a RewriteRule, meant to prevent direct requests to the file. Pretty easy to bypass if you know it is there, but effective against random requests by bots and such.
This way, direct requests to either scripts/image.php and switch.php?file=image.php would fail, but requests to any image file would trigger the scripts/image.php script.
You can set deny from all on .htaccess and include these files from some accessible directory
I want to ensure the PHP pages will accept post values, get values and can redirect to other pages, but not be directly accessed via the address bar or downloaded?
As long as Apache is configured to associate all .php files with the PHP application, no one can download the PHP content itself. So, if someone browsed to "mysite.com/image.php", PHP will run. The user will NOT see your PHP content.
This should already by done in your httpd.conf file as :
AddType application/x-httpd-php .php .phtml
Now, image.php will be expecting certain post parameters. Short of implementing an MVC architecture as Atli suggested above, you could gracefully and securely deal with any missing parameters if they aren't provided. Then, users can get to the page directly but not do anything with it.
A lot of applications just put files like your scripts not in the public (like /public_html/ or /www/) folder but in the same root folder as your public folder.
so not
root/public_html/ and
root/public_html/scripts/
but
root/public_html/ and
root/scripts/
Anything in a folder above the public folder can't be accessed by visitors, but by specifying in for example /public_html/index.php the file '../scripts/yourscript.php' PHP can access these files and visitors can't. (the folder ../ means "go up one step in the folder hierarchy")