Can a Directory alone load specific query on a page? - php

On websites such as facebook and many others you see URLs such as www.facebook.com/username. How does a URL such as this actually load the users information from a MySQL database? and what is the actual file it is displaying on? I would assume there's not really a folder for each user that it is referring to. If my question doesn't make sense can you at least point me in the right direction to set something like this up through PHP?
Again, I want example.com/username to load my users profile. How does this work?

By using apache's .htaccess file to manage a RewriteEngine, all of your pages can be funneled through an index.php file. After confirming that the requested page is not actually a page that you've intended to be a default part of your web page, you can fall back on the code below, to discover a user account. If a user account is not discovered, then the likelihood is that the page being accessed is simply a 404, which you could then redirect to as a catch-all scenario
.htaccess file
RewriteEngine on
RewriteBase /
RewriteRule !\.(xml|js|ico|gif|jpg|png|css|swf|php|txt|html|otf)$ index.php
php logic to run after confirming the requested page, isn't something like a contact-us page, or any typical web page an end user would be attempting to access.
if(preg_match("/^\/(?P<username>[^\/]*)/", $_SERVER['REDIRECT_URL'], $matches)) {
$result = mysql_query("SELECT * FROM users WHERE username = '" . mysql_real_escape_string($matches['username']) . "'");
if($user_record = mysql_fetch_row($result)) {
echo "DO WHATEVER YOUR HEART CONTENTS HERE :)";
} else {
header("Location: error-404.php");
}
}

It is all loaded dynamically via the database. For example, my Facebook name is "benroux". In facebook's user table, there is going to be a unique column called, lets say, nickname. When I visit Facebook, they are parsing the path info and essentially calling a query in the form:
select * from user where nickname = "{$nickName}"
Now, this is an over simplified example, but I hope it gives you an idea of what is going on here. The key is that there are 2 types of url vars, the facebook.com/pagename.php?id=blah and the restful style path info vars facebook.com/pagename/var1/var2/
If you are looking to have example.com/benroux load my user page, you need to make your index.php (I'll use PHP) load the path info ( http://php.net/manual/en/function.pathinfo.php ) and then query the database as I have described above.

try to
print_r($_SERVER);
you will get that parameters. Then you just need to split them.
Something like
$directory = $_SERVER['REQUEST_URI'].split('/')[1];
So, put $directory into query

Related

Redirect URL to correct user page

I was just looking for a little help on the following, unfortunately I haven't been able to find a solution, perhaps due to not knowing what to call it exactly. I can only find solutions for doing the reverse of what I require.
At present I have a user page set up, which can be accessed via a URL as follows:
[DOMAIN_NAME]/client/?client=3
I would like to be able for users to type:
[DOMAIN_NAME]/apples
and be directed to the the prior URL, assuming apples is a valid user name.
I am using PHP and I know I could have just set it up for users to have their own folders etc. but was wondering if there is a URL redirect solution for this. Preferably one that would keep the url as the user has typed it, but show the real information.
Thanks,
Cillian
$fullurl = explode('/',$_SERVER['SCRIPT_NAME']);
$username = $fullurl[count($fullurl)-1];
echo $username;
then check $username e.i it is valid user or not if valid user then redirect to your desire page.
header('Location: http://www.domain.com/userfolder/yourpage.php?userid=$userid');
You Should use .htaccess redirect Method
See http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

URL rewriting, same URL across multiple PHP files

Hey so I have create a login system to a website and I wish to have this login appear when I type in my address. When I have typed in details and logged in, I wish to be redirected to another PHP file, but with the same address.... this way, All I need to do is type in my address if I am allready logged in and I will go to the site which requires login.
I have made a transaction happen identifing if the session is created, if it is, it redirects me to another page, but also to another URL. I tried googleing it, but couldn't find anything exact and straight forward.
Currently:
Login page:
www.example.com
Member page:
www.example.com/members
What I wish for:
Login page:
www.example.com
Member page:
www.example.com
The program structure should look like this.
index.php
if (user is logged in)
display dashoard
else
display login page
Since you are using PHP, make use of session functions. Thus, URL rewriting is no longer necessary.
Update
Assuming if you have file structure in PHP like this:
- index.php
- login.php
+ template
- login.php
- dashboard.php
You can do the following structure in index.php file.
define('IN_FILE', true);
if (isset($_SESSION['user'])) {
require 'template/dashboard.php';
} else {
require 'template/login.php';
}
In template/dashboard.php
if (!defined('IN_FILE')) {
exit;
}
// Then your HTML, PHP and whatnot
And in login.php
if (!isset($_SESSION['user'])) {
require 'template/login.php';
} else {
header('Location: index.php');
}
Change the code according to your needs.
This can be achieved using several approaches.
a) Use session to determine the current page, so if a user click on a link, create a session store the value and on page load read the session data and include the file accordingly.
b) Use URL parameter to determine the page (this is the most common approach). for example in index.php you can add more parameters like index.php?page=somepage and by reading the value using $_GET and including the PHP file accordingly.
There are some more way to achieve what you want to, for instance using javascript/jQuery this is possible.

ID variable from URL

Ok so when somebody types this into the URL mywebsite.com/?s1=affiliateid
I want to take the affiliateid part out of the URL. Every affiliate will put a different username into the address.
Then I want to create a link will point to differentwebsite.com/?id=affiliateid based on the username typed into the address bar.
Now so far, I know that I have to have something like this will get that affiliate id
$aff_id = $_GET['s1'];
Then I can use that variable to create a link or just redirect it to the next page
differentwebsite.com/?id=$aff_id
My question is, where do I place this code at? $aff_id = $_GET['s1'];
Do I have to make a page called ?s1.php or something?
Assuming s1 isn't used anywhere else but just to create a link:
<?php
$s1 = isset($_GET['s1']) && !empty($_GET['s1'])
? $_GET['s1'] // it's populated, use the passed value
: ''; // default value in case it's not present
//
// Maybe check $s1 is indeed valid
//
$newurl = sprintf('http://differentwebsite.com/?id=%s', urlencode($_GET['s1']));
?>
Then you can output that link somewhere on the page, like:
New Url Here
urlencode will make sure that if s1 has characters like &, =, ?, / (or others) it won't break the integrity of the url.
If you want the concise approach:
<a href="http://differentwebsite.com/?id=<?= urlencode($_GET['s1']); ?>">
New Url Here
</a>
You could place $aff_id = $_GET['s1'] anywhere before you want to use $aff_id. I tend to put stuff like that at the top of the page.
Or, simply put. "differentwebsite.com/?id=$_GET['id']"
I would suggess you do a check to see if the id parameter exists in the URL before you try to use it. Maybe even make sure it is the data type you expect, integer, string, etc. So as when you redirect users, you don't send them somewhere else in a broken way.
If you are not using this for SQL then no SQL Injection could occur #BlackHatShadow.
Append the $aff_id that you get from mywebsite.com to the url of the new web site. Presumably, $newurl = "differentwebsite.com/?id=".$aff_id.
Edit:
Do I have to make a page called ?s1.php or something?
You need to make a page that the user will land on when they hit the url: www.mywebsite.com/
I assume you are running a web server that can process PHP code. The code can go into a file called index.php in your server's document root directory. If you don't know what this is, I suggest googling a "how to" guide for your specific server.
Get the value of "s1" from the url and store it in $aff_id:
$aff_id = $_GET['s1'];
If you want to pass this variable into another web site which accepts an "id" parameter, then you can simply append $aff_id to the new web URL and redirect the user there.
Redirect the user to differentwebsite.com and also sends the $aff_id from mywebsite.com to the other URL:
header('Location: http://www.differentwebsite.com/?id='.$aff_id);

design of website with membership to restricted content

I have a web site which currently has over 900 html articles currently viewable to anyone. I want to change it to restrict viewing of certain articles by membership only. I have the articles in sql database with flag if restricted. There is an article index with links to each article. The process will be to check if article is restricted, check if user is member logged in, then display, otherwise send to login or subscribe pages. Since there is so many articles, I can't just add some php to not display if the article is accessed directly. My question is where in my web directory to I put these article pages, and how do you protect someone from directly accessing the page, but allow access once the user is authenticated? Any input is appreciated. Anyone know of good reference books on this either?
Move the files so that they're above your document root, and therefore inaccessible through the web server. Or, move the files to a directory which you protect with a password (.htaccess/.htpasswd pair). You never give out that password, it's only there to prevent direct access of the files.
Then, write a script which proxies the articles. That script checks if the user is logged in. If not, it redirects them to the login page. If it is, it reads the article HTML from its actual location, and sends it through.
Ex: http://www.example.com/article.php?view=cooking.html
session_start();
if (!isset($_SESSION['logged_in'])) {
header("Location: login.php");
} else {
readfile("/path/to/articles/" . $_GET['view']);
}
You'll want to do some kind of sanitation on $_GET['view'] to make sure it doesn't contain anything but the name of an article.
You can even keep your current URLs and links to the articles by rewriting them to the proxy script in your .httaccess/httpd.conf with mod_rewrite. Something like this:
RewriteEngine On
RewriteRule article/(.*)\.html articles.php?view=$1 [L]
If you don't already have any existing framework for PHP development that would help with security matters, you might consider something simpler than even using PHP to restrict access. Read up about .htaccess files, and how you can create a protected directory in which you could place all the restricted articles. Then you can setup user account and require people to authenticate themselves before they can read the restricted articles.
Here's a tutorial on how to setup .htaccess for user authorization/authentication:
http://www.javascriptkit.com/howto/htaccess3.shtml
You have a couple of basic options:
Add the code to each page. You can probably automate this, so its not as bad as it sounds. It really shouldn't be more than a single include.
Figure out how to get your web server software (e.g., apache) to do the authentication checks. Depending on how complicated your checks are, a mod_rewrite external mapping program may be able to do it. Other than that, there are existing authentication modules, or writing a fairly simple shim isn't that hard (if you know C)
Feed all page loads through PHP. This will probably break existing URLs, unfortunately. You pass the page you want to see as a parameter or part of the path (depending on server config), then do you checks inside your script, and finally send the page if the checks pass.
The simplest way would probably be to move all the aricle files outside the web root, and then use PHP to fetch them if the client is allowed to see it.
For example:
<?php
if (isset($_GET['id']))
{
$articleDir = "/var/articles/";
// Assuming a "?id=1" query string is used to pass a numberic ID of
// an article. (Like: example.com/showArticle.php?id=1)
$articleID = (int)$_GET['id'];
$articleFile = "article_{$articleID}.html";
// Look through your SQL database to see if the article is restricted.
// I'll leave the codeing to that up to you though.
if (!$isRestricted || $isLoggedIn)
{
$path = $articleDir . $articleFile;
if (file_exists($path))
{
include $path;
}
else
{
echo "The requested article does not exist.";
}
}
else
{
echo "You have to be logged in to see this article.";
}
}
else
{
echo "No article ID was passed. Did you perhaps follow a bad link?";
}
?>
Note that if you want to keep the old links alive, you can use Apache's mod_rewrite to rewrite incoming requests and route them to your PHP file.
Edit
This may help if you are new to mod_rewrite and/or regular expressions:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^article_(\d+)\.html$ fetchArticle.php?id=$1 [L]
</IfModule>
Routs any link such as example.com/article_123.html to example.com/fetchArticle.php?id=123 without the client noticing it.
Similar to what Dan Grossman did, but this one fetches only numbers.

How do you create domain.com/?stringhere without a .php extension

I want to create a link like the following:
http://www.myurl.com/?IDHERE
What i want to be able to do is be able to goto the above link, and then pull whats after the ? (in this case IDHERE) and be able to use that information to perform a MySQL lookup and return a page.
Can anyone point me into the right direction? please know this is using PHP not ASP
The issue here is not with your scripting language, but with your web server setup. I'll refer to these by their Apache names, but the features should be available in most web servers.
There are three features you might want to use:
1) content negotiation (mod_negotiation), which allows your web server to try a specified list of extensions in a specified order, for example: http://example.com/foo might be http://www.example.com/foo.html or http://example.com/foo.php
2) DirectoryIndex, which tells the web server that when a client asks for http://example.com it should look for a specified list of files in order, so it might server up http://example.com/index.html or http:/example.com/index.php
3) mod_rewrite, which allows you to basically rewrite the URL format received by the server. This allows you to do things like translate http://example.com/foo/bar/baz to http://example.com/foo/bar.php?page=baz
The rest is done by the backend script code as normal.
Create a default PHP file in that directory that will get loaded when no file name is specified (e.g. index.php). In your PHP script you can get the part after the question mark from the variable $_SERVER['QUERY_STRING'].
Do the following in your site's main index.php:
list($id) = array_keys($_GET);
// right now, $id represents the ID you're looking for.
// Do whatever you want with it.
In the link, form or whatever - index.php?id=someid
In your index.php file:
$_GET['id'] = $id
Now you can use it:
e.g.
echo $id;
Since it's your default page, it will work without the extension.
list($id) = array_keys($_GET);
// right now, $id represents the ID you're looking for.
// Do whatever you want with it.
this was exactly what i was looking for, though now i just need to create something to notify if nothing is there or not. Thank you all for your responses.
I would solve it by using .htaccess file if possible.
create a .htaccess file in the main directory with the content:
RewriteEngine on
RewriteRule cat/(.*)/(.*)/(.*)/$ /$1/$2.php?$3
that should translate "example.com/foo/bar/baz" to "example.com/foo/bar.php?page=baz"

Categories