Using $_POST in 2 if statements - php

I'm trying to use one post in 2 different if statements.
What I'm trying to achieve is that I want to insert 3 values in mysql with post.
$action = $_POST['action'];
if($action == "checkCharacterName"){
$username = $_POST['name'];
}
it gets the character name here ^
and then in different action it gets the password:
if($action == "registerUser"){
$password = $_POST['password'];
$qry = $db->prepare ( 'INSERT INTO user_data (id, username, password, gold)
VALUES (null, "'. $username .'","'. $password .'", 500)');
$qry->execute();
but it shows this error:
Undefined variable: username
The posts are sending through swf, so I'm not able to change it cause its not mine swf

You work in PHP. This is a STATELESS langage. It means each time you post data, the whole script is executed but NO VARIABLES are saved. There is two ways to bypass this.
Adding state : Save the $username in the $_SESSION object or in the $_COOKIE object.
Working stateless : Do your request in only ONE POST. (Sending the username and the password at same time.
More informations to maintain a state here

Related

How to make php to redirect each user to their own respective pages?

ok, so i have a little issue here with php. I know there are alot of similar questions, but ones i found did not help.
I dont want to use anything more like javascript or something. I got mysql set up, there are 3 columns ID username and password.
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost","root","");
mysql_select_db("login");
$result = mysql_query("select * from users where username='$username' and password= '$password'")
or die("failed to query DB".mysql_error());
$row = mysql_fetch_array($result);
if ($row['username'] == $username && $row['password'] == $password) {header(suc.html);
die();}else{header("Location: fail.html");die();}
?>
This code, it works but when i dont fill in any details and press submit too, it gets me to the suc.html which shows successful login. Now i want to make the following:
I'll make ID's similar to each individual html's names, then the php will go match the ID number with the file name in the directory, and show the page for the respective user.
like lets say user1.
Login userlol password 123 ID user1 file user1.html
then what code to use that it goes and matches the ID user1 with the .html name, then redirects the user to their own custom page. Is there a way? Kinda getting started with php ,so cut some slack please :)
p.s i know these codes are older php codes, but anything works for me personally.
You are getting that sort of behaviour because when a username and password is not submitted, their respective values evaluates to null and your SQL query is successful but returns 0 rows thereby making your $row['username'] and $row['password'] to be null. In general, your $row['username'],$row['password'],$username,$password would all be equal to null which fulfills all the requirements to redirect to "suc.html"
To solve this problem, simply check if mysql_num_rows($result)==1 because usually, a successful login would return just one row due to unique usernames.
But
I would not advice you to continue with deprecated mysql and SQL Injection susceptible logic. Please allow me to rewrite your logic as follows:
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
// You don't have to escape or sanitize user inputs if you use Prepared Statement plus sanitizing user password is highly discouraged.
// $username = stripcslashes($username);
// $password = stripcslashes($password);
// $username = mysql_real_escape_string($username);
// $password = mysql_real_escape_string($password);
// Initiate a PDO connection and set your error mode to exception.
$conn=new pdo("mysql:host=localhost;dbname=login;","root","",array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
try{
// Prepare your query and replace all values with ? which would be provided as an array in execute(); I added limit 1 to make sure we are getting a maximum of one row from our query.
$result_stmt = $conn->prepare("select * from `users` where (`username`=? and `password`=?) limit 1");
$result_stmt->execute([$username,$password]);
// fatch() would return a single row just like mysql_fetch_array or mysql_fetch_assoc while fetchAll() would return all rows.
$result=$result_stmt->fetch();
if(count($result)==1){
// There is no need to check this again because your query to the database already did.
// if ($row['username'] == $username && $row['password'] == $password)
// Redirect users to the same page but identify each user through session (recommended)
header("location:suc.html");
}else{
header("location:fail.html");
}
}catch(Exception $e){
echo $e->getMessage();
}
?>

my php registration file creates too many entries in the database

I have a file named reg.php that extends my registration.php for a login system.
The registration is connected with a mysqli database and I have a manual
increase in user id in php instead of autoincrement in mysqli because I could
not make this work.
When I hit the register button, my code is creating two entries in the db and
I dont know why.
<?php
if(isset($_POST["register_user"])){
header('location: login.php');
}
if(isset($_POST["username"])){
$username = mysqli_real_escape_string($db, $_POST['username']);
}
if(isset($_POST["email"])){
$email = mysqli_real_escape_string($db, $_POST['email']);
}
if(isset($_POST["password"])){
$password = mysqli_real_escape_string($db, $_POST['password']);
}
if(isset($_POST["passwordconfirm"])){
$passwordconfirm = mysqli_real_escape_string($db, $_POST['passwordconfirm']);
}
$idcount = mysqli_num_rows(mysqli_query($db, "SELECT id FROM user"));
$regquery = "INSERT INTO user (id, name, email, password) VALUES ('$idcount', '$username', '$email', '$password')";
mysqli_query($db, $regquery);
?>
all I want is one single entry.
There's nothing in the code, in your question, that could insert two rows in your database. My guess it that you call this script twice, probably because your form has two ways of submitting the same data:
The normal way, with the form action attribute.
Through an event, like onSubmit
You've got to stop the former, if the latter is used. Look at the example in the link for 2. It tells you how to stop the form from submitting as well:
// For this example, don't actually submit the form
event.preventDefault();
So if the onSubmit works, it stops the normal form submission, but if it doesn't work, the form is submitted the normal way.

apache2 and php - please advise

OK, I originally posted this a question about php, but have since realized it could be a server configuration problem, which I know little about. I left the php script in case, and am hoping someone might have some pointers on this - I already checked permissions (755).
"NetworkError: 500 Internal Server Error - http://localhost/register.php?name=uname&password=upassword"
I was hoping someone here would be able to catch my error - sorry if this is obvious I've been learning as I go.
<?php
define('USER', 'root');
define('PASS', 'password');
$dbh = new PDO('mysql:host=localhost;dbname=users', USER, PASS);
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
$query = 'INSERT INTO `users` (`name`, `password`) VALUES (?,?)';
$query->bind_param($uname, $upassword);
$queryResults = $dbh->prepare($query);
$queryResults->execute();
$queryResults = null;
$dbh = null; // close the connection
?>
This keeps giving me a 500 internal server error indicating the php script, (in firebug for firefox), and I can't really figure out where I'm going wrong. I can also post ajax if needed.
You are using a Query String http://localhost/register.php?name=uname&password=upassword". Its purely a GET Method.
Your have to check whether the GET Method is exist then you need to access the GET Method Data.
$uname = "";
if(isset($_GET['uname'])) {
$uname = $_GET['uname'];
}
$upassword = "";
if(isset($_GET['password'])) {
$upassword = $_GET['password'];
}
if(($uname != "") && ($upassword != "")) {
$upassword = password_hash($upassword, PASSWORD_DEFAULT)
$query = sprintf("INSERT INTO `users` (`name`, `password`) VALUES (%s, %s)", $uname, $upassword);
----- Statements ------
}
I don't know why it's throwing 500 error, but you clearly have error in code.
Your $query variable is string and it does not have $query->bind_param() method. I assume you are trying to do this (bind_param is MySqli while bindParam is PDO):
$dbh->prepare($query);
$sth->bindParam($uname, $upassword);
Also since you are passing variables via URL, than you must use $_GET instead of $_POST. Just make sure you first check if these parameters exists in $_GET and only than use them:
if (!empty($_GET['name'])) {
$uname = $_GET['name'];
}
NOTE ?name=uname&password=upassword means variable names are name and password. It's values are $_GET['name'] = 'uname' / $_GET['password'] = 'upassword'.
Never pass username and password using $_GET as it's insecure. Better use some secure file to save them.

Data not inserting in MySQL

I am making a script for a guy and he uses Advanced Outgoing API (not familiar). He gives me this URL where the POST variable will be stored in http://example.com/your_script.php?email_address={u_email}&firstname={u_firstname}. So here is my php code. The problem is it cannot read the post values. When I echo it, it's empty.
NOTE: This is the instruction from the API Manual.
Advanced Outgoing API
You can have up to 5 URLs for each Product/Podcast/RSS Feed/Membership be notified whenever a subscriber event happens. You can enter these URLs by clicking on "Edit Notifications/Custom Fields" for a particular item. The system will then POST the following variables to the URLs you've entered. You can also include any of the variables below as a "tags" in your URL and the system will replace the tag with the actual value. This way you can post the values to an existing script that expects a variable name to be different than the ones listed below. For example, your notification URL could be: http://example.com/your_script.php?email_address={u_email}&firstname={u_firstname} . The system would then post all the variables below to: http://example.com/your_script.php?email_address=joe#example.com&firstname=Joe
$con = mysql_connect("localhost","xyz","xyz","xyz"); // Establish connection to insert in the first table.
$username = $_POST['paypal_email']; // username of the user.
$rawpass = $_POST['access_code']; // Raw password.
$pass = md5($rawpass); // Password of the user encrypted with md5.
$email = $_POST['email_address']; // E-mail of the user.
$time = date("Y-m-d H:i:s");
echo $username;
echo $pass;
echo $email;
echo $time;
mysql_query("INSERT INTO wpinrootusers ('user_login', 'user_pass', 'user_email', user_registered, 'user_status') VALUES ('$username', '$pass', '$email', '$time', 0), $con"); // Insertion into wpinrootusers table.
mysql_close($con); // Close connection.
$con = mysql_connect("localhost","xyz","xyz","xyz"); // Establish connection to insert in the second table.
mysql_query("INSERT INTO customers ('receipt', 'prod_num', 'email') VALUES ('$rawpass', '6', '$email')", $con); // Insertion into customers table.
mysql_close($con); // Close second connection.
With mysql you have to do:
$con = mysql_connect("localhost","xyz","xyz");
and then select the database:
$db = mysql_select_db("xyz");
The code you used to connect to database works with mysqli (i stands for improved) and you should consider switching from mysql to mysqli
When you send the variable as GET parameters you have to use $_GET of course.

What is wrong with this MySQL insert statement?

The form is ok and it captures all of the information correctly, however, the errors started when I used a function to generate a random string that is used for user activation.
function generateActivationString() {
$randomSalt = '*&(*(JHjhkjnkjn9898';
$uniqId = uniqid(mt_rand(), true);
return md5($randomSalt.$uniqId);
}
if (!get_magic_quotes_gpc()) {
// $_POST['pass'] = addslashes($_POST['pass']);
$username = addslashes($_POST['username']);
$firstname = addslashes($_POST['firstname']);
$surname = addslashes($_POST['surname']);
// $_POST['email'] = addslashes($_POST['email']);
$email = mysql_real_escape_string(addslashes($_POST['email']));
$pass = mysql_real_escape_string(sha1($_POST['pass']));
$activationString = generateActivationString();
}
$insert = "INSERT INTO users (username, password, firstname, surname, email, activation_string)
VALUES ('".strtolower($username)."', '".$pass."', '".strtolower($firstname)."', '".strtolower($surname)."', '".strtolower($email)."', '".$activationString."')";
Here is the echoed insert statement:
INSERT INTO users (username, password, firstname, surname, email, activation_string) VALUES ('', '', '', '', '', '')
I know it has created a new entry as the auto_increment id row is populated however al of the other fields remain empty.
Here is the code from the generateActivationString() so I know that's working too! - 264361eeb6e75d3934ce249a0d05f2c1
Any suggestions are more than welcome and greatly appreciated!
Going strictly by the code above, your variables like $username,$password etc are in the scope of your if block, move them outside of the if.
I don't see you send that query anywhere, maybe that's your problem...
Oh dear. The biggest problem with your statement is that you are not using prepared statement and taking info directly from the POST parameters. This is a recipe for disaster and how most sites get hacked.

Categories