Im new on php, so i need some sugests for following code:
<?php
// Start the session (pretty important!)
session_start();
// Establish a link to the database
$dbLink = mysql_connect('', '', '');
if (!$dbLink) die('Can\'t establish a connection to the database: ' . mysql_error());
$dbSelected = mysql_select_db('', $dbLink);
if (!$dbSelected) die ('We\'re connected, but can\'t use the table: ' . mysql_error());
$isUserLoggedIn = false;
$query = 'SELECT * FROM users WHERE session_id = "' . session_id() . '" LIMIT 1';
$userResult = mysql_query($query);
if(mysql_num_rows($userResult) == 1) {
$_SESSION['user'] = mysql_fetch_assoc($userResult);
$isUserLoggedIn = true;
} else {
if(basename($_SERVER['PHP_SELF']) != 'conectare.php') {
header('Location: conectare.php');
exit;
}
}
?>
Upper code verify if user it's logged in or not..
I need to create a profil link, like following:
http://site.com/profile.php?name=NAME-OF-USER
Can someone give me a ideea?
Im newbie on php, so pls understand me..
PS: Please dont tell me to use mysql, pdo and another, i allready know the beneficts, i need only answers for my code..
Thank you !
you simply need to use the get variable
create the link that will be clicked like this
the link that will be clicked on home page or any other page
<?php
$username='test';//the variable containing the username
echo'<a href="mysite.com/profile.php?user='.$username.'">
The link redirecting to profile page
</a>';
?>
the address bar will turn something like this www.mysite.com/profile.php?user=test
then on the profile page
<?php
$username_selector=$_GET['user']//in this case the value got from the link clicked is test
//then just select the necessary data using the variable storing the value got from th link clicked
?>
All you need to do is echo some html:
$username = "foo";
echo "profile link";
Note: I use \" to escape the "
More information about strings in php: http://php.net/manual/en/language.types.string.php
Related
I have only access to a source code (connect.php) from previous developer as
<?php $_F=__FILE__;$_X='Pz48P3BocA0KNG40X3M1dCgnZDRzcGwxeV81cnIycnMnLCdPZmYnKTsNCiRjMm4gPSBteXNxbF9jMm5uNWN0KCJsMmMxbGgyc3QiLCJyMjJ0IiwibW0xYWFhOSIpOw0KbXlzcWxfczVsNWN0X2RiKCJtNHRyMSIsICRjMm4pOw0KNGYgKCEkYzJuKQ0KICB7DQogIGQ0NSgnSzJuNWtzNCBnMWcxbCAhOiAnIC4gbXlzcWxfNXJyMnIoKSk7DQogIH0NCj8+';eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));?>
Then I googled there's tool to decode the above encrypted text which gives me
?><?php
ini_set('display_errors','Off');
$con = mysql_connect("localhost","root","mma2229");
mysql_select_db("mitra", $con);
if (!$con)
{
die('Koneksi gagal !: ' . mysql_error());
}
?>
All I need is just to change the password (example to "123") but I do not know where to start.
How can I set the my connect.php with my new password ?
Just replace the previous delevopers code:
<?php $_F=__FILE__;$_X='Pz48P3BocA0KNG40X3M1dCgnZDRzcGwxeV81cnIycnMnLCdPZmYnKTsNCiRjMm4gPSBteXNxbF9jMm5uNWN0KCJsMmMxbGgyc3QiLCJyMjJ0IiwibW0xYWFhOSIpOw0KbXlzcWxfczVsNWN0X2RiKCJtNHRyMSIsICRjMm4pOw0KNGYgKCEkYzJuKQ0KICB7DQogIGQ0NSgnSzJuNWtzNCBnMWcxbCAhOiAnIC4gbXlzcWxfNXJyMnIoKSk7DQogIH0NCj8+';eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));?>
With:
<?php
ini_set('display_errors','Off');
$con = mysql_connect("localhost","root","123"); // put your new password instead of 123
mysql_select_db("mitra", $con);
if (!$con)
{
die('Koneksi gagal !: ' . mysql_error());
}
?>
In your phpMyAdmin panel write query like this:
SET PASSWORD FOR 'root'#'localhost' = password('mynewpass')
Setting new user / change password in view
If you want to do it with clicking, go to phpMyAdmin, click on the top Users -> Edit Privileges and there you can change a password. In this view you can also add new user which can be used in your PHP code.
I am new to PHP
i am making a simple login functionality for user with php & mysql
Here i want to make a simple thing where when a user after "loggingin" if presses back button he shouldn't get the login page back on screen.
I have tried using JS history.forward but its little wierd...
It shows glimps of login page for a second and takes back user to same page from where he presses back button...
How to make a facebook like functionality where login page never appears after loging in even on pressing back button..
Please HELP...:)
<?php
include_once 'conn.php';
if (isset($_SESSION['username'])) {
header('location:home.php');
}
if (isset($_REQUEST['btnsignin'])) {
if ($_REQUEST['txtemail'] <> "" && $_REQUEST['txtpass'] <> "") {
$email = $_REQUEST['txtemail'];
$pass = $_REQUEST['txtpass'];
$q = mysql_query("SELECT * FROM register WHERE emailid = '" . $email . "' && password = '" . $pass . "'");
while ($row = mysql_fetch_assoc($q)) {
$_SESSION['username'] = $email;
$_SESSION['userid'] = $row['uid'];
header('location:home.php');
}
}
}
?>
You always want to add exit; after the header() function to prevent the code block below from execution.
try to use 'AND' in place of '&&' in your sql query.
you have to start session in php before set it.
you can session start with.
include_once 'conn.php';
session_start(); //add this line in your code.
if (isset($_SESSION['username']))
{
header('location:home.php');
}
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 few session variables that I am trying to use in my application, however, I am unable to get them to show up on the pages I need them to.
This is the code that sets them (I have manually assigned them values as well, so it isn't the database pull that is the problem):
if ($name != ""){
$_SESSION['name'] = $name;
$_SESSION['id'] = $user_id;
}
I start that page with a session_start();, as I do on all the pages that will be using the session variables.
When I try to call the session variables on another page, they no longer exist, even if that is the page the one that assigns the values redirects to.
This is how I am trying to call the session variables:
$name = $_SESSION['name'];
$user_id = $_SESSION['id'];
why would it be doing this?
EDIT: To help I'm including the rest of my code for that page. The database connection portions work fine, they are identical to what I use eveyrwhere else.
<?php
session_start();
define('DB_SERVER', '<server>');
define('DB_USER','<db>');
define('DB_PASSWORD' , '<password>');
define('DB_NAME' , '<db-name>');
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database');
$stmt = "Select User.user_id, User.name from User where User.username = '" .
$_POST["username"] . "' AND User.password = '" . $_POST["pwd"] . "';";
if(!$result = $conn->query($stmt)){
die('there was an error retrieving the information');
}
$row = $result->fetch_assoc();
$name = $row['name'];
$user_id = $row['user_id'];
$_SESSION["name"] = $name;
$_SESSION["id"] = $user_id;
if ($name != ""){
$conn->close();
?>
<script type="text/javascript">
<!--
window.location = "store.php"
//-->
</script>
<?php
}
else{
?>
<script type="text/javascript">
<!--
window.location = "register.php"
//-->
</script>
<?php
}
?>
There is only two probabilities:
You did not started session before any output.
The $name is already empty or null.
You have to do the following to debug:
echo $name before the if conditional.
error_reporting(E_ALL); or checkout this question: How to get useful error messages in PHP?
As a debugging technique, try setting the session values ON the page that you're trying to call them. For example, set them on the top of the page and then try outputting them somewhere else below on the page and see if that works. If it does, then it's obvious that the variables aren't being set on the previous page(s).
In PHP you must need to start session using session_start() then only you can user session variables.
And also try to debug, Does your if condition satisfied or not. In your case if your if condition does not satisfied then it is not possible your below code will execute.
$_SESSION['name'] = $name;
$_SESSION['id'] = $user_id;
Hello, I'm kind of new to php, so don't bash on me, but I just can't figure out what the problem is with this code. So basically I have several forms of output, but as soon as I do anything with mysql ( even just connect and disconnect! ), it won't allow me to do any kind of output. It also won't allow me to redirect.
I tried taking all the code out between the mysql connect and disconnect code and it didn't help to resolve anything, However, as soon as I comment out the mysql connection code, all my outputs and redirects work! I'm trying to build a simple login script that gets the email and password from a form elsewhere. I would love to get this resolved so I could figure out if the rest of it works. And I know that 'header' will not work after echo; the echo and the file writes will not be there as soon as I can make sure this is working. Any help would be appreciated! Thanks!
<?php
/*
Login.php searches for the email address given by loginPage.php in the data base.
If the email is found and the password given by loginPage.php matches that stored
in the data base, a session will begin and the client will be redirected to the
main page.
*** INCOMPLETE ***
*/
echo "HELLO!";
$email = $_POST["email"];
$password = $_POST["password"];
$errorLog = fopen("login.txt", "w");
fwrite($errorLog, "***Sesion started***");
$mysql_id = mysql_connect("localhost", "root", "12131");
if (!$mysql_id)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('informationStation', $mysql_id);
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "';", $mysql_id);
if($results != null && $password == mysql_fetch_array($result))
{
$redirect = 'Location: http://127.0.1.1/main.php';
}
else
{
$redirect = 'Location: http://127.0.1.1/loginPage.php';
{
mysql_close($mysql_id);
fwrite($errorLog, "result: " . $results);
fwrite($errorLog, "redirect: " . $redirect);
fclose($errorLog);
header($redirect);
?>
Try this to get you started..
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "'", $mysql_id) or die(mysql_error());
But you also need to read about sql injection.
And you should not store passwords in your database without salting and hashing them.
And you also need to use array syntax to access the data from your result...
$mysql = mysql_connect("localhost", "root", "12131") or die('Could not connect: ' . mysql_error());
mysql_select_db('informationStation', $mysql);
function loged($email, $password) {
$result = mysql_query("SELECT id FROM Personals WHERE email = '" . $email . "' AND password='" . $password . "'");
if(mysql_num_rows($result) != 1)
return false;
return true;
}
if(loged(mysql_real_escape_string($email), md5($password))) {
header('Location: http://127.0.1.1/mainPage.php');
exit;
}
header('Location: http://127.0.1.1/loginPage.php');
In this example you need to store users password using md5 encryption method (search for other more securely encryption methods).
Also we've escaped the email address against sql injection.
I've created a function which can be called every time you want to see if the user is loged in or not.
Note that this is not a complete login script. You will also need to make a login function where you'll have to start a new session for each user.