Create personal page for every user, PHP - php

What I want to do is to create a web page for every user when they signup on my page.
For Example: www.someweb.com/username, and this will be their webpage.
I know that this can be done easily with mkdir() and other related functions, but the problem is that my root folder is not chmod 777 and I don't want to chmod 777 this root folder because of security reasons.
What is the best way to do this when a user registers on my web page.

You don't make physical directories for each user, you use URL rewriting. Take a look at this source:
HTML Source : HTML Tutorials, URL Rewriting

Most likely you don't need to create these directories in real.
Just make it virtual.
Pass a username using query string, like this:
www.someweb.com/index.php?user=username
And personalize this page according to particular username.
After that you can do some rewrite magic and make a page address like this www.someweb.com/username but all pages will remain virtual

Use mod_rewrite to make a request to /username actually be ?user=username. You can then get the appropriate user's data and display it in a template.

if you want to create personal page for each user after signup
->when a new user do the signup at ur site then create a new directory with the name of username at the location of user folder like
/user/username/
create a file under this directory with name of index by using create file function
/user/username/index
write the following code using read/write operations if ur using php
<?php
$myfile = fopen("\user\$_SESSION["username"].php", "w") or die("Unable to create file!");
$str = "<?php
\$p_username = ".$_SESSION['username'].";
include('../user-profile.php');
?>";
fwrite($myfile, $str);
fclose($myfile);
?>
this user-profile will have the functionality to retrieve the user info from the database with the help of variable $p_username. in this way an user can also visit the profile of other user

Related

How can a domain acces subdomain data?

I have a CMS for my website which is hosted on the subdomain (admin.example.com). Both are in a different directory on the server. On the subdomain I upload all my files (mostly images) that are later to use on the main domain (example.com).
From the subdomain I upload file information to the database which is also used by the main domain, file_url, file_id etc. etc.
The thing is, how can I get hold of this information from my main domain? The file_urls currently look like ../folder/image.png and I don't want people, using the main domain, knowing that I have a subdomain which holds the CMS.
I was thinking about throwing everything on the main domain and restrict the admin area for default users. But what are your thoughts about this? is this safe? is there somehow a work-around?
UPDATE
Within a page from the subdomain.example.com I call this piece of code
$dir = "/usr/share/nginx/html/example.com/public_html/images/thumbnail";
try {
// Creating directory
mkdir($dir, 0755, true);
} catch(ErrorException $ex){
// Failure
die($warnings[] = "Error: " . $ex->getMessage());
}
exit();
This works, folders have 755 and files 644. It may be a dirty workaround but I am not aware of the consequences this may have. Please let me know!
You can point to the sub domain but it will be tricky ti hide the fact
May I suggest you set the permissions for your sub domain to just execute for the public
Eg
Owner: read write execute
Group: read, execute
Everyone else, execute
This way they can use your site but cannot read the sub folder
Or set up a redirect header in your index.php file of your sub folder and direct them to the appropriate page
To clarify my answer update, I approach the folder of the wanted domain like
$dir = "/usr/share/nginx/html/example.com/public_html/images/..";
or this
$dir = "/usr/share/nginx/html/subdomain.example.com/public_html/..";
depending on what domain I want to manipulate data from.

Permalinks with PHP

I am currently working on a website I am making from SCRATCH :) Anyhow users will be able to create accounts (login and register pages already done), and then they will be able to view there profile. Now the problem I am running into is each user needs there own permalink for there profile's URL. I do not know how to go about doing this though! :( All I can find is using Wordpress to do it for me, but I do not want that. I would like to go about doing this with only PHP and HTML/CSS. Please help me out, thank you! :)
UPDATE 1
Thank you for the relpys, I am still a little confused though. Now if I use a GET, will that actually save the file? How exactly do permalinks work (sorry very confused! :O )? Like when I create the permalink is that creating a new file as well with the code inside of it? If so what would I be writing for that?
UPDATE 2
Sorry I am specifying what I am really asking. When a user created a account, I want it to AUTO create them a permalink (which would be a new file right?), how would I go about doing that?
UPDATE 3
Ok, so I am basically thinking of the same thing. So when a user creates a account this is the code that is executed:
//Create Account Page
$inputquery = "INSERT INTO users username VALUES :username";
$datasend = $connection->prepare($inputquery);
$datasend->execute(array(':username'=>utf8_decode($username),)); //Inputs it into the database
$username = $_POST["username"]; //The username input, then lets say that the account was created with that
$userprofile = fopen($username . ".php", "w"); //Makes a file with the users info, a PHP function
$text = include ('base.php'); //Grabbing the base layout
fwrite($userprofile, $text); //Setting the base layout to the userprofile page
So once that is one the code will be in the file. Then when the page is loaded, that so called "base" code is still there, and then is replaced with the details of the user. That is my rough attempt at this, it should work! :) Thank You for all of your help! :D
You can use a GET request, which will be stored in the URL. You just access it with $_GET['user'], and the url will be in the form my.site.on.the.net/user.php?user=3141. This URL can be stored in bookmarks, put in a webpage, or whatever else and it will link to that user's profile.
This will not save the file by itself. You will need to store the user information somewhere outside your web root, then use the PHP file to access that info based on the ID. You don't want to store the entire webpage; just store the information that is unique to that user (On SO, that would be stuff like their About Me, reputation, badges, etc.)
EDIT: Simple example (note that it doesn't have any password protection or anything else to prevent any random stranger from accessing it)
user.php:
<?php
function getPoints(){
// get the number of points from your data source
}
function getName(){
// get the name from your data source
}
?>
<!DOCTYPE html>
<html>
<body>
<img src="logo.png" alt="logo" />
<h1>Hello, <?php echo getName();?>!</h1>
<p>You have <?php echo getPoints();?> points.</p>
</body>
</html>
In this example, the data source only needs to store the user's name and number of points. The single PHP file fills in the rest of the page. To create a new user account, you will need to add the data for the user to your data source.

Can a Directory alone load specific query on a page?

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

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.

Diplay page directly with php

What is the best way to "NOT" display a page directly in php?
Edit
There is a page = register.php
a user cant open register.php directly. Only can access from index.php > Register.php
Thanks
Any PHP files containing sensitive data, such as database password, should be stored outside of the document root and included where needed. That way, if an admin makes a serious mistake and the web server starts sending PHP unparsed, that data will be inaccessible.
Edit
You edited your question and it now seems you wish to prevent access to page without them coming from a particular page. You should be able to get some ideas from these questions:
deny direct access to a php file by typing the link in the url
preventing direct access to a php page, only access if redirected
I think you want something like this:
if ( $_SERVER['HTTP_REFERER'] != 'http://YOUR_SITE/index.php' ) {
echo "Can't access this page from this referer";
die();
}
// go on with your register.php code
You can put
die();
or
exit();
At the top of your PHP document. However, your question is unclear as to what you wish to accomplish.
You can start a session in index.php and check for a certain variable from that session in the other pages.
make a file index.php
in it put
<?php
include 'register235235235235.php';
?>
make a file register235235235235.php
put whatever you want in there
As far as securing php includes, I only secure my database.php files which contain usernames and passwords.

Categories