Dynamic pages / links in php how does it work - php

I made a small login system for users, they can log in and change their userinformation on the account_setting page.
But since im pretty new to php I wonder how can I give each user their own page? A page that is public.
Ex, User "Steven" has user_id=17.
How can I create a page for that user, so his information gets displayed there.
Something like website.com/user=17 ... His information.
And also if the page could act as a template, just diffrent information/url depending on user.
Im not asking anyone to write this for me, a link to a good tutorial would work just fine :)
But please, no 5year old posts on the topic.

you need userprofile.php?userid=17 and use $_GET['userid'] to draw the information based on that user. HTML should be same on userprofile.php only data will change depending on the user id. If userid is not set then show an error message or something

Generally saying:
if (!empty($_GET['user']) && is_numeric($_GET['user'])){
//Find him in database
if (user_found($_GET['user'])){
include "left_column.php" ;
include "user_info.php" ;
} else {
echo "Page is not found" ; //or set header error 404
}
} else {
include "news_column.php" ;
}

website.com/index.php?user=17
<?php
require_once 'db/connect.php';
//Pull in 'user' from the query string.
$user = isset($_GET['user']) ? trim($_GET['user']) : null;
//Try to pull that user's info from the database.
$stmt = $dbh->prepare("SELECT * FROM user WHERE user_id = :user_id");
$stmt->bindParam(':user_id', $user);
$stmt->execute();
$user= $stmt->fetch(PDO::FETCH_ASSOC);
if(!is_array($user)){
//User not found. Throw 404 or redirect.
header('HTTP/1.0 404 Not Found');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php echo htmlentities($user['name'], ENT_QUOTES, "utf-8"); ?></title>
</head>
<body>
<h1><?php echo htmlentities($user['name'], ENT_QUOTES, "utf-8"); ?></h1>
<p>
<?php echo nl2br(htmlentities($user['bio'], ENT_QUOTES, "utf-8")); ?>
</p>
</body>
</html>

I'm going to assume that you're storing your user information in a database. For the sake of argument, we'll say it's a mysql database. What you need to do is capture the userid and then read only that column from the database.
If your URL is website.com/user/view.php?id=17, your user variable will be in $_GET['id']
So something like this:
$id = mysqli_real_escape_string($_GET['id']);
$results = mysqli->query("select * from users where id = '$id'");
$results = $results->fetch_assoc();
... will bring up the information for the user; then you just build a page to display it.

Related

PHP, link when redirected doesn't work anymore

Currently I'm working with a group on a website where people can plan things and earn badges. For that we made a log in screen. After a user has logged in the user gets redirected to the index.php file. In this file is one link that has to send the user to the index.html file in which people can actualy put tasks or plan things.
The problem is that the link doesn't work. The link only opens when I open it in a new tab but not in the same one. This is the code we used for the login.php file.
<?php
require('db.php');
// session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
header("Location: index.php"); // Redirect user to index.php
exit();
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}
In the index.php file we used this code:
<?php
include("auth.php"); //include auth.php file on all secure pages ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome Home</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<p>This is secure area.</p>
<p>Ga nu naar de planner</p>
Logout
</div>
</body>
</html>
It's about this row in the index.php file:
<p>Ga nu naar de planner</p>
When clicked on I get an error loading the page. When opened in a new tab it works fine. Also the CSS doesn't work after logging in. In the URL the login.php is behind the URL. When I remove this (after logging in) the link does work and also the CSS works.
Hopefully you can help us out! Thanks a lot in advance! Hopefully you understand the problem a little :)
EDIT
As asked the file tree:
https://s27.postimg.org/mswa2dmlf/foto1.jpg
https://s24.postimg.org/ca3lbw3cl/foto2.jpg
First picture is the main map, second picture the planning map!
replace <a href="planning/index.html"> with the full path to the page where you want this to go ... Example ... if your site is www.exemple1.com ...<a href="http://www.exemple1.com/planning/index.html">

Script to update users value in data base not working – issue with sessions?

I’m pretty much a complete beginner when it comes to PHP and have been having some problems with my script to update the current users values in the database – when the script fires it doesn’t update the value in the database as intended at all.
Some background info:
Database name: “user”
Table “users” with columns User ID , Username , Password , Emailaddress , Offer.
Site that I’m working on allows users to complete a number of offers and then get rewarded upon completion. The offer column has the default value of “1”. Upon login the user is redirected according to the value in the offer column. (So on first login user is redirected to example.com/offer1 , after offer 1 is completed this value is updated so on next login user is redirected to offer 2 – in essence storing the users progress) This login process works fine , its just updating the value which is my problem.
This is the script which is played after an offer is completed (in this case after offer 3 is completed) – aim to connect to database and then update that users “offer” so when they next login they will be directed to the correct offer – thus storing their progress:
~Could this actually not be a problem with the Script its self but in regards to sessions not starting/continuing correctly upon login – or maybe an issue with the script not using the session data correctly?~
<?php
session_start();
$con = mysqli_connect("localhost","name","password","user");
$select = mysqli_fetch_assoc(mysqli_query($con,"SELECT offer FROM user WHERE Username = '".$_SESSION['username']."'"));
$plus = $select['offer']++;
mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" );
header("location: http://example.com/offer4".$plus);
?>
The mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" ); isn't working at all, could the issue be here?
In case it helps , this is a previous version I was using which did work in updating the values but does so for all users in the database rather than just the one user who is logged in. So lets say Jim has completed this offer , his Offer value will be updates to 3 but so will all the other users will have their offer value set to 3 when only Jim’s should be.
<?php
session_start();
$con = mysqli_connect("localhost","username","pass","user");
$select = mysqli_fetch_assoc(mysqli_query($con,"SELECT offer FROM users WHERE Username = '".$_SESSION['username']."'"));
$plus = $select['offer']++;
mysqli_query($con,"UPDATE users SET offer=3".$plus);
header("location: http://example.com/offer4".$plus);
?>
Just for reference here is my login script – this works correctly in redirecting user upon login to value in their Offer column (could my problem be to do with sessions not starting correctly?)
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="main">
<?php
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['EmailAddress'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo '<meta http-equiv="refresh" content="0;URL=\'http://example.com/offer'.$row['offer'].'\'" />';
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
else
{
?>
<h1>Member Login</h1>
<p>Thanks for visiting! Please either login below, or click here to register.</p>
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
<?php
}
?>
</div>
</body>
</html>
Lastly, heres base.php
<?php
session_start();
$dbhost = "localhost"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "user"; // the name of the database that you are going to use for this project
$dbuser = "name"; // the username that you created, or were given, to access your database
$dbpass = "password"; // the password that you created, or were given, to access your database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
Thank you very much for your time and have a good evening ; very much appreciate all the previous replies here that have been so helpful.
Try this:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
session_start();
if(!empty($_SESSION['Username'])) {
$con = mysqli_connect("localhost","username","pass","user");
$username = mysqli_real_escape_string($con, $_SESSION['Username']);
$result = mysqli_query($con, "UPDATE users SET Offer = Offer + 1 WHERE Username = '{$username}'");
while ($row = mysqli_fetch_assoc($result)) {
$offer = $row['Offer'];
}
header("Location: http://example.com/offer".$offer);
} else {
echo "You are not logged in.";
}
mysqli_real_escape_string will escape dangerous characters from the username. You can use an UPDATE to increment a cell's value by an amount (in this case 1).
Another thing to note: In the PHP on the page with the HTML, you are using mysql extension functions instead of mysqli. The mysql extension is deprecated. Either way, your code is inconsistent in the use of mysql and mysqli. For a list of equivalent mysqli functions, check the PHP manual.
You said your database was called user and your table users. In your first query statement, you selected offer from a table called user not users. You can use mysqli_error() to display errors, which you would have received.
Regarding your second mysqli_query statement:
mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" );
There is no $id anywhere else in your code. Also you need a space before your where, otherwise if $plus == 13, the statement reads SET offer=313where user_id....
According to your code ($select['offer']++), you retrieve the previous offer value, increment it by 1 and then set the offer value in the database to this incremented value with a 3 added on to the beginning.
If offer == 31, then after going through your code, the new offer == 332.
EDIT: Something else I just noticed. I think you are misunderstanding the ++ operator. When used after an operand, it is called the post-increment operator. When used before, it is called the pre-increment operator. The reason for this is because in the case of the post-increment operator, the value of the operand (in your case $select['offer']) is assigned to $plus before it is incremented. What this means, in the context of your code, is that you are never actually incrementing the offer value.
I think the problem is with this line:
mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" );
Where is $id coming from? In the line above, you used username.
Your SQL is "UPDATE users SET offer=3".$plus."where user_id = $id". In PHP with $plus variable equal, e.g. "54" this becomes "UPDATE users SET offer=354where user_id = $id". So, a space is missing before where.
If this is not the case, learn to use mysqli error logging: http://php.net//manual/ru/mysqli.error.php.

PHP Selecting a single result

I created a PHP form which allows users to Register and Log in. Now I created another page named View.php that will show all the registered users in my MySQL database. The code I used was
while($row=mysqli_fetch_assoc($sql))...
and it displayed all the users successfully.
Now I created another PHP page which I named profile.php. I want to add a link from every result on view.php which will redirect to profile.php?user=(their username). But I don't know how.
In this line:
echo "<small><a href = 'profile.php?user=$them'>[View Profile]</a></small><br/>";
instead of using your fixed $them, just use $row['id']. Then you can fetch the user with that id in your profile.php file:
$id = $_GET['user'];
$sql = "SELECT * FROM users where id = $id";
Note that this code is prone to sql injection. I only posted it to make the idea easier to understand. See here how to do it right.
I do not know the code you are using to achieve the result but having something like :
$query = "SELECT * FROM database WHERE id=$id";
$query = mysql_query($query);
This will filter out the profile page according to the user id
In your view.php considering that you have a column named 'username' , change the following :
please not, it's preferably to put the ID column If you want to put the id column, simply change the $row['username'] to $row['id'] and the same in the query in profile.php
<?php
...
while($row=mysqli_fetch_assoc($result)) {
echo "---------------------<br/>";
echo "<b>".$row['fullname']."</b><br/>";
echo "<small><i>".$row['course']."</i></small><br/>";
echo "<small><a href = 'friends.php?user=".$row['username']."'>[View Profile]</a></small><br/>";
echo "---------------------<br/><br/>";
}
?>
And in your
profile.php
<?php session_start();
if($_SESSION['logged_in']==false) {
header("Location:login.php");
}
include("header.php");
?>
<html>
<head>
<title>View School-Mates</title>
</head>
<body>
<center>
<h1>My School-Mates</h1>
<small>View or Add them in your Trust List</small>
<br/><br/>
<hr>
</center>
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test_basic', "root", "");
$stmt = $dbh->prepare("SELECT * FROM USERS WHERE username= ?");
if ($stmt->execute(array($_GET['user']))) {
while ($row = $stmt->fetch()) {
//here you will have your row with all your username data
}
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
</body>
</html>
Please read more about PDO from here and how to do connections this is required because you get data from your $_GET variable, and thus you need to avoid for sql injection
Hopefully this is what you wanted, if not, please let me know so i can adjust the code

Setting user privileges in PHP and MYSQL

I want to make some of my php pages accessible to certain users. I flag these users in my users table as 'super_user' in the 'user_privilege' attribute. So fat I have got the login and sessions working. But I'm not sure about 'super_user' only pages. Basically this is the page I want to make accessible only to super users:
<?php
require_once('../includes/su_permission.inc.php');
require_once('../includes/session_timeout_db.inc.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Secret page</title>
</head>
<body>
<h1>Restricted area</h1>
<p>Back to restricted menu </p>
<?php include('../includes/logout_db.inc.php'); ?>
</body>
</html>
The session_timeout_db.inc.php doc checks if the user's session has expired and it works fine. I have also added this: require_once('../includes/su_permission.inc.php'); in the code to check if the user is a super user. This my attempt at the code:
<?php
require_once 'login.php';
$conn = new mysqli ($host, $user, $password, $database) or die("Connection Failed");
$sql = 'SELECT user_role FROM users WHERE user_email = ?';
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param('s', $user_email);
$stmt->bind_result($user_role);
$stmt->execute();
$stmt->fetch();
if ($user_role='SU') {
$_SESSION['privilege_level'] = $user_role;
// some other code needed here
exit;
} else {
echo 'No permission to visit this page';
}
I know it is a poor attempt, but I'm not sure what else to do from here. Can someone please advice the best way I can do this ?
Thanks
Here is your problem:
if ($user_role='SU') {
You need a proper comparison operator (== or ===) here. What you are doing right now is assigning a value of SU to $user_role in all cases.
A slight programming suggestion to avoid such problems is to flip to comparison order like this:
if ('SU' == $user_role) {
That way if you accidentally type = instead of == or ===, you will get an error output, rather than having your code quietly run while doing something you don't want it to do.
I did a similar thing on the site I'm working on. I setup up three different areas, for the different user 'types'.
I then setup 3 different session check files for the groups of pages. I'm sure this could be done using only one file, and some elseifs but whatever. Anyway here is the code snippet that I use on my pages to check if a user is logged in, and if they are the right "type" of user to view the page:
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] !== 'admin') {
//if (!isset($_SESSION['authenticated'])) {
header("Location: $redirect");
exit;
If they aren't right it redirects them. I hope that helps.

Getting access to a database variable

I'd like to pull a value from my database and use it as the current page title. My connection works, the page loads fine, but I need access to a variable and I can't figure this one out.
How my page is structured:
Blog.php
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/header.php');
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$blogid = $_GET['id'];
$stmt = $dbh->prepare("SELECT id, title, slug, body, image, author, date, category from blog WHERE id= :id ORDER BY date DESC");
$stmt->execute(array('id' => $_GET['id']));
$row = $stmt->fetch();
}
if(isset($row['title'])) {
$pageTitle = $row['title'];
} else {
$pageTitle = "Something Here";
}
$pageTitle is a variable in $header.php. It controls the <title> tage for each page.
Problem
My database connection $dbh is set in header.php. this means I don't have access to $row['title'] until it's too late.
Question:
How can I restructure this to gain access to $row['title'] BEFORE require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/header.php');. I really don't want to pull the database connection out of the header if I don't have to.
Thanks!
You can't do that, because your <title></tile> is already printed in the ouput.
An hardcore fix would be to use rendering in buffer (with ob_start ob_get_content) then parse the rendered content to change the content of your <title> tag.
However the clever way is to get your database out of your header.
Regards

Categories