Echo not displaying inside a div but worked outside of it - php

I'm currently making a webpage and I have run in to some problems with echo being inside a div container.
My website is currently setup like this:
index.php has the header and a navigation pane on the left side. and there is a bodycontent div that will load in different pages depending on what is clicked.
I previously had the following code in my index.php right before my bodycontent div:
<?php
//set the variables
$username = isset($_POST['username']) ? $_POST['username'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$step = isset($_POST['step']) ? $_POST['step'] : '1';
//validation
if($step=='2'){
if($username == '' || strlen($username)==0){
echo 'username can not be blank<br/>';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) == false){
$errors[] = 'invalid email address<br/>';
}
if($password == '' || strlen($password)<=4){
$errors[] = 'password can not be blank or less than 4 characters<br/>';
}
$username=mysql_real_escape_string(trim($username));
$email=mysql_real_escape_string(trim($email));
$password=md5(mysql_real_escape_string(trim($password)));
//mysql queries
if(empty($errors)){
//do something
$query = "
INSERT INTO user
(email, username, password, user_level)
VALUES
('$email', '$username', '$password', '1')";
$result = mysql_query($query) or die ('error: '. mysql_error());
echo 'new user registered!';
$step='2';
}
else{
//error output
foreach($errors as $errors)
echo $errors;
$step='1';
}
}
if($step=='1'){
?>
I decided to move this piece of code in my registration.php page so the index.php looks cleaner for me.
However, ever since I moved the code from index.php to registration.php the echos are not displaying. If you need more code I will gladly post some more.. I don't want to overwhelm right now.

I noticed in your final foreach loop:
foreach($errors as $errors) is missing an opening bracket;
foreach($errors as $error) {
// instructions
}

Related

How to check for duplicate username and/or email in php

Hello guys i have a simple pdo login and register page, and when i test it in localhost, I could register same usernames and emails. How do i check for duplication in registration page, and shows an error if same user/email already exist? This is my register.php
<?php
require 'config.php';
if(isset($_SESSION['username'])){
header('location:dashboard.php');
}
if(isset($_POST['register'])) {
$errMsg = '';
// Get data from FROM
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$address = $_POST['address'];
$password = $_POST['password'];
$secretpin = $_POST['secretpin'];
if($fullname == '')
$errMsg = 'Enter your fullname!';
if($username == '')
$errMsg = 'Enter username!';
if($address == '')
$errMsg = 'Enter a valid email!';
if($password == '')
$errMsg = 'Enter password!';
if($secretpin == '')
$errMsg = 'Enter a sercret pin number!';
if($errMsg == ''){
try {
$stmt = $connect->prepare('INSERT INTO pdo (fullname, username, address, password, secretpin) VALUES (:fullname, :username, :address, :password, :secretpin)');
$stmt->execute(array(
':fullname' => $fullname,
':username' => $username,
':address' => $address,
':password' => $password,
':secretpin' => $secretpin,
));
header('Location: register.php?action=joined');
exit;
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
if(isset($_GET['action']) && $_GET['action'] == 'joined') {
$errMsg = 'Registration successfull. Now you can login';
}
?>
And my other problem is, how to get the registration date of every person who register and save in the database and echo the date in the profile page. Im just a newbie in php and i get some ideas in other open source php codes. Thanks guys.
P.S dont mind about the security, Im still learning about that :)
Your security is already slightly enhanced by the fact you are using PDO rather than the deprecated mysql or mysqli.
Checking for duplication is simply a case of an SQL "LIKE" statement query - like so -
SELECT * FROM websiteUsers WHERE userEmail or userLogin LIKE ?
an example of this can actually be found on this link - https://www.w3schools.com/sql/sql_like.asp
I would not want to undermine your approach, however bear in mind that at the moment your code here:
if($fullname == '')
$errMsg = 'Enter your fullname!';
if($username == '')
$errMsg = 'Enter username!';
if($address == '')
$errMsg = 'Enter a valid email!';
if($password == '')
$errMsg = 'Enter password!';
if($secretpin == '')
$errMsg = 'Enter a sercret pin number!';
will overwrite the $errMsg everytime, so you won't get the full set of errors either, which might or might not be important.
I know you didn't want security pointers as such, but using
if(isset($_GET['action']) && $_GET['action'] == 'joined') {
as a way of knowing if someone is registered is not a good idea either, please either use a framework or change your approach, as this one suggests I can access that url without actually filling out your form.

PHP skipping if blocks

When I run this page, everything shows up correctly, but then when I try to test my various error messages, my button keeps redirecting me back to my login page as if everything was inputted correctly. It fails to register the if blocks I've included. Below is the php (the html runs fine, not included).
*Side note, a few lines are commented out because I initially had PDO and am changing them over to mysql, but those shouldn't affect everything else running. I have them commented out too so if things did work, I wasn't adding unnecessary info to my database.
Of course, PHP is not skipping anything. It is diligently running your conditions, but in your code the only condition that affects the insert is the last one.
To make it work as desired you have to change all your ifs to elseif save for the first one
The problem: Your error may be set, but your INSERT will execute only if $password == $password2 which will be true if they're both empty.
You need to indicate alternative paths by doing else if
<?php
error_reporting (E_ALL);
$error = "";
if (isset($_POST['createAccount'])){
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$address = $_POST['address'];
$city = $_POST['city'];
$province = $_POST['province'];
$postalCode = $_POST['postalCode'];
if (!$username){
$error = "<br><div><em>No username entered.</em></div>";
}
elseif (!$password || !$password2){
$error = "<br><div><em>Missing password.</em></div>";
}
elseif (!$firstName || !$lastName){
$error = "<br><div><em>Please enter first and last name.</em></div>";
}
elseif (!$address || !$city || !$province || !$postalCode){
$error = "<br><div><em>Insufficient address provided. Please fill in all fields.</em></div>";
}
elseif ($password != $password2){
$error = "<br><div><em>Passwords do not match.</em></div>";
}
else{
$conn = mysql_connect(<blocked out for privacy reasons>);
$db = mysql_select_db("grocery", $conn);
$account = mysql_query("SELECT *
FROM accounts
WHERE username = '$username'",
$conn);
$rowExist = mysql_num_rows($account);
if ($rowExist == 1){
$error = "<br><div><em>Username already exists.</em></div>";
}
else {
//$newAccount = ("INSERT INTO accounts (username, password, first_name, last_name, street, city, province, postal_code)
// VALUES ('$username','$password','$firstName','$lastName','$address','$city','$province','$postal_code')");
//$conn->exec($newAccount);
header("location: GroceryLogin.php");
}
mysql_close($conn);
}
}
// I'm guessing here you do an echo $error;

PHP sign up code

I am creating my first sign in/register function to my web site by following a online tutorial. Every thing seems to be working good , My problem is in the tutorial the php if ($_SERVER['REQUEST_METHOD'] == 'POST') is set in the index page which checks if all the fields and then inserts them into the DB . But for me this not seem to work. But if I put the code onto the page where the form action redirects after it works fine. Is this the right way to do it. I wouldn't like to think so because I would like to check all the variable before we move on.
So if someone would like to educate me on this would be great.
Here is my php code still not fully finished but i wanted to clear this up first.
This is used by include method
<?php
//setup some variables/arrays
$action = array();
$action['result'] = null;
//check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$message = "wrong answer";
echo "<script type='text/javascript'>alert('$message');</script>";
$firstName = mysqli_real_escape_string($link,$_POST['firstName']);
$lastName = mysqli_real_escape_string($link,$_POST['lastName']);
$password = mysqli_real_escape_string($link,$_POST['sign-up-password']);
$confirmPassword = mysqli_real_escape_string($link,$_POST['password-confirm']);
$email = mysqli_real_escape_string($link,$_POST['email2']);
//quick/simple validation
if(empty($firstName)){ $action['result'] = 'error';}
if(empty($lastName)){ $action['result'] = 'error';}
if(empty($password)){ $action['result'] = 'error';}
if(empty($email)){ $action['result'] = 'error';}
if($password != $confirmPassword){ $action['result'] = 'error';}
if($action['result'] != 'error'){
$add = mysqli_query($link,"INSERT INTO `users` VALUES(NULL,'$firstName','$lastName','$password','$email',0)");
if($add){
//the user was added to the database
//get the new user id
$userid = mysqli_insert_id($link);
//create a random key
$key = $firstName . $email . date('mY');
$key = md5($key);
//add confirm row
$confirm = mysqli_query($link,"INSERT INTO `confirm` VALUES(NULL,'$userid','$key','$email')");
if($confirm){
//let's send the email
}
}else{
$action['result'] = 'error';
array_push($text,'User could not be added to the database. Reason: ' . mysql_error());
}
}else{
}
}
?>

Echo is not showing up in api

I'm trying to make an api for my iOS application by sending POST http requests to my api.php. I'm testing it right now, but my echo is not showing up? The only moment my echo works is when I delete everything and just write echo 'Test';.
Here is my code:
<?php
$user = '';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=iOS', $user, $pass);
if(isset($_POST['status']) && $_POST['status'] == "login")){
// Login stuff
}else if(isset($_POST['status']) && $_POST['status'] == "registreren")){
//Register stuff
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email']))){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "INSERT INTO `user` (username, password, email) VALUES ('$username', '$password', '$email')";
if($dbh->execute($sql)){
echo 'Did it';
}else{
echo 'Nop';
}
}
}else{
echo 'Something is wrong';
}
$dbh = null; // PDO sluiten
?>
I'm not so good at php, but in my case there should always return 'Something is wrong' when accessing the api.php by URL because I don't send any POST requests with it.
There are several syntax errors which might prevent your code from executing correctly. In every if-statement, there is an additional bracket.
Eg: if(isset($_POST['status']) && $_POST['status'] == "registreren")) should be replaced by if(isset($_POST['status']) && $_POST['status'] == "registreren") (note that the last bracket is missing).
Remove the additional brackets at the end of every if-statement in your code and it might be fine.

Restrict a content using session control in php

Hello reading websites and forums i have learned that, content can be prevented using sessions.I have a index.php page which checks sessions and give results as per the condition:
<?php
session_start();
if( $_SESSION['user'] != $name ) { echo "Sorry,no session found or is expired";
require( 'login.php' );
}
else {
echo "hello,you have session existing";
}
?>
I have table created details
FNAME
LNAME
BDAY
PASS
EMAIL
CODES
login.php is as follows:
<?php
$name = $_POST['name'];
$pass = $_POST['pass'];
mysql_connect('mysqlhost','user','pass','userdatabase');
$query=mysql_query(sprintf("SELECT FNAME FROM `details` WHERE FNAME=$name AND PASS=$pass";
mysql_real_escape_string($PASS)));
if($query) { while($row = mysql_fetch_assoc($query)) { $rows[1] = $row; } }
if( isset($name) || isset($pass) )
{
if( empty($name) ) {
die ("ERROR: Please enter username!");
}
if( empty($pass) ) {
die ("ERROR: Please enter
password!");
}
if( $name == $rows[1][FNAME] &&
$pass == $rows[1][PASS] )
{
session_start();
$_SESSION['user'] = $_POST['name'];
header('Location: index.php');
}
else {
echo "ERROR: Incorrect username
or password!";
}
}
else {
?>
<html>
<head>
<body>
//Load login form here & save $SESSION value in "name"
</html>
<?php } ?>
So,my code is going wrong somewhere and cannot see "hello,you have session existing".Any help again would be gratefull.(Code can be half viewed, sorry for that)
Try this -
if( !isset( $_SESSION[ "user" ] ) )
instead of
if( $_SESSION['user'] != $name )
In login.php you must somehow pass the value of $_POST['name'] as $name to index.php, and also it's really a bad idea to put session as password, few tips:
1) use a user id, say 1,2,3... and add a primary key to it, and use that id to do stuff like granting access.
2)md5 your pass while registering, and check it like
if (md5($_POST['pass']) == $pass) {
//some code
};

Categories