I've made a web page where you can register and log in, and once you log in you can edit your profile and also upload an avatar. I'm working on the avatar part right now and I can't figure out why it doesn't work. I will show you some parts of my code so hopefully you can help me.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$avatar_path = $mysqli->escape_string('images/'.$_FILES['avatar']['name']);
if (preg_match("!image!",$_FILES['avatar']['type'])) {
if (copy($_FILES['avatar']['tmp_name'], $avatar_path)) {
//It copies the image to the specified path so i know it works till here.
$_SESSION['avatar'] = $avatar_path;
And here is the problem, because it basically does nothing, it doesn't even return an error message so I don't know what's wrong with my SQL.
($_SESSION[msg1] is equal to your username (I know it because I printed it here), so basically what I'm trying to do is insert the avatar path into the users table where username is equal to your username, but it does nothing.
$sql = "UPDATE users SET avatar = $avatar_path WHERE username = $_SESSION[msg1]";
if ($mysqli->query($sql) === true){
header("Location: index.php");
}
}
}
}
Formate your query like so:
$sql = "UPDATE users SET avatar = '" . $avatar_path . "' WHERE username = '" . $_SESSION['msg1'] . "'";
if ($mysqli->query($sql) === true){
header("Location: index.php");
}
else
{
die("Database Query Failed: " . mysqli_error());
}
Related
I'm new to programming and I'm trying to build a simple login-form with HTML, PHP and Bootstrap. I have a login page and a registration page. I wanted to display a success message once a user was created. But it keeps showing when I come back from a different page and also when I refresh the page.
With header("Location:registration.php"); I redirect to the same page. This prevents inserting into the database when I refresh the page. See my code below from "registration.php".
session_start();
if(isset($_POST['add_user'])) {
//When submitted store entered data in a variable
$add_username = $_POST['add_username'];
$add_password = $_POST['add_password'];
//Database query
$query = "INSERT INTO users(username, user_password) VALUES('{$add_username}', '{$add_password}')";
$result = mysqli_query($connection, $query);
if(!$result) {
die("QUERY FAILED" . mysqli_error($connection));
} else {
$_SESSION['success_message'] = " ";
header('Location: ' . $_SERVER['PHP_SELF']);
$_SESSION['success_message'] = "<div class='alert alert-success' role='alert'><strong>User Created</strong><br><a href='index.php'>Log In</a></div>";
exit();
}
}
You can try this code to avoid issue.
if (isset($_POST['submit'])) {
// ... your code here
header('Location: ' . $_SERVER['PHP_SELF']);
}
Try this
if (empty($_SESSION['success_message'])) {
// set and display message
}
This way you will display the message only the first time.
My issue is that for some reason on the login.php page of my website, I initialize some $_Session Variables from my users table in the corresponding database, but while these variables seem to function properly on other pages I can't do anything with them immediately after initializing them, because they don't seem to exist. This is an issue because I would like to reference the variables I have defined to create other session variables for efficiency, and because I would like to use it for a welcome message like the simple example shown in my code. Here is the code in question:
if(isset($_POST['user_email']) && !empty($_POST['user_email']) AND isset($_POST['user_pass']) && !empty($_POST['user_pass']))
{
$email = mysqli_real_escape_string($link, $_POST['user_email']); // Set variable for the username
$password = mysqli_real_escape_string($link, sha1($_POST['user_pass'])); // Set variable for the password and convert it to an sha1 hash.
$result = mysqli_query($link, "SELECT user_email, user_pass, user_active FROM users WHERE user_email='".$email."' AND user_pass='".$password."' AND user_active='1'") or die(mysqli_error($link));
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_uuid'] = $row['user_uuid'];
$_SESSION['user_level'] = $row['user_level'];
$_SESSION['user_rank'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_uuid'] . '. <br />Proceed to the forum overview.';
}
}
}
I have session_start(); at the top of my connect.php which is included at the top of the signin.php doc.
The result of this code on this page is something like:
Welcome, .
Proceed to the forum overview.
However if I run it on a different page on the site it properly prints, i.e.:
Welcome, username.
Proceed to the forum overview
Thanks.
I have created a script for users to invite a friend using a email address, the email address and a randomly generated 10 character string 'inviteCode' is sent to a table called 'referrals'.
The invited person then receives an email with a URL link that contains their email and their unique inviteCode; http://website.com/register.php?email=email&inviteCode=1234567890
When the user clicks on the link the page register.php should then check the URL and if they data is valid in the 'referrals' table. If so then I have an include line to add the register form, if not then they are redirected. The point is nobody can access register.php unless they have been invited and sent a link.
At the moment the page keeps redirecting to index.php;
Register.php script:
<?php
include 'config.php';
if (isset($_GET['email'],$_GET['inviteCode'])) {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
echo 'lol';
}
else
{
echo 'no';
exit;
}
}
else
{
echo 'problem'; //Page not accessible if neither email nor referral entered
}
?>
I replaced the first if statement with:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else
And I receive a blank page with no errors. I believe there may be something wrong with the email and invite code not being set.
Any help on this would be much appreciated (Y) thanks.
You should really be looking at handling the errors first. Try something like this:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='$email' AND inviteCode='$inviteCode'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
include'register-form.php';
} else {
die(header('Location: index.php'));
}
}
Breakdown
The if block checks to see if GET[email] or GET[inviteCode] are not set. if that is the case, kill the app with die() and redirect the user to index.php.
The second change is this line:
if ($query->num_rows > 0) {
That will check to ensure the rows returned are more than 0 (meaning there are actually rows returned.) Because you were just testing the presence of the $query->num_rows before.
Another Note:
Turn on error reporting, it will help you emensly during debugging:
ini_set('display_errors', 1);
error_reporting(E_ALL);
You could alternatively change your sql query to select the COUNT(id) and check if that is greater than 0, but that seems like overkill for what you're trying to do.
Do this to find out if anything is being returned by your query:
Start by making sure that the connection to your database is succeeding:
$mysqli = new Mysqli(/* your connection */);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$email = $mysqli->real_escape_string($_GET['email']);
Add that then let us know the results afterward, also provide specific error messages.
To debug your num_rows, replace this:
$query = $mysqli->query($sql);
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
With this:
$query = $mysqli->query($sql);
$count = $query->num_rows;
print $count;
exit;
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
If it shows 0, I have a suspicion it is because your sql statement needs to be concatenated.
"SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";
I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();
I have a comics site which I'd like to easy my uploading of image paths to the database.
I have a login screen which checks as such for correct credentials:
<?php
$username = isset($_POST['username']) ? $_POST['username'] : "";
$password = isset($_POST['pw']) ? $_POST['pw'] : "";
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(verify($username, $password) == 1) {
header("Location: ?action=admin");
}
else {
echo "<center>Incorrect credentials</center>";
}
}
function verify($user, $pw) {
include './scripts/dbconnect.php';
$result = $mysqli->query("SELECT username, password FROM users WHERE username='" . $user . "' AND password='" . $pw . "'");
return $result->num_rows;
}
include 'include/footer.php';
?>
Which will then log them in to the upload screen.
Unfortunately, all the user has to do is guess what my url might be for the upload page and they can skip my login screen...
/HTwS/?action=login (just replace 'login' with 'admin' and you're there...) So, my first line of defense will be to not make my upload page name so obvious... but what happens if a user still guesses it... can I verify in another way which won't let them just change the url up?
Thanks!
Well this is pretty insecure. What you're going to want to do is set some session variables when you login ($_SESSION[user_id], $_SESSION[permission_type], etc...). You can then have a function such as verifyAdmin() at the top of each admin page that would check if the logged in user is in fact an admin by checking the $_SESSION variables you just set. If they're not, they get redirected to the login page.
When the admin logs in, set some session variables as such:
$_SESSION[user_id] = id_of_admin;
$_SESSION[permission_type] = 'admin';
verifyAdmin would look something like this:
function verifyAdmin() {
if(!isset($_SESSION[username]) || !isset($_SESSION[permission_type]) || $_SESSION[permission_type] != 'admin'){
header("Location: login.php");
}
}
Then on the top of each admin page you can simply do this:
verifyAdmin();
Your verify function should look like this:
function verify($user, $pw) {
include './scripts/dbconnect.php';
$result = $mysqli -> query("SELECT username, password FROM users WHERE username='" . $user . "' AND password='" . $pw . "'");
if ($result -> num_rows == 1) {
$_SESSION[username] = $user;
$_SESSION[permission_type] = 'admin';
}
return $result -> num_rows;
}
This chunk of code is also vulnerable to SQL injection. You need to sanitize those $_POST variables.