I'm not quite sure why is this happening. After a bit of research and a few shots ate solving it I'm finally giving up and asking for help. My problem is that I start a session on a page (controle.php) and create an array at $_SESSION["agenda"], but I only what to create it at the first time. After that I want to add elements to it with array_push($_SESSION["agenda"], $Contato), where $Contato is an object and I create a new instance of that object for every iteration. However, the data on $_SESSION["agenda"] is not persisting, every time the code runs it creates a new array. I've tried adding session_start() to the very top of the page, checked that my browser allows sites to save cookies. As for PHP configuration I'll post a picture because I'm ignorant in this area.
Here is phpinfo();
controle.php code:
<?php
session_start();
require_once '../Model/Contato.php';
$op = $_GET["op"];
if (isset($op) && $op != "") {
switch ($op) {
case 'add':
include '../View/novo.php';
break;
case 'cad':
if(isset($_POST["enviar"])){
$nome = $_POST["nome"];
$email = $_POST["email"];
$Contato = new Contato($nome, $email);
if(!isset($_SESSION["agenda"])){
$_SESSION["agenda"] = array();
}
array_push($_SESSION["agenda"], $Contato);
include '../View/sucesso.php';
}
else{
include '../View/erro.php';
}
unset($nome);
unset($email);
break;
case 'lst':
include '../View/lista.php';
break;
}
}
else{
include '../View/index.php';
}
?>
novo.php code:
<!DOCTYPE html>
<html>
<head>
<title>Novo Contato</title>
</head>
<body>
<h1>Criar novo contato</h1>
<form action="../Controller/controle.php?op=cad" method="post">
<label>Nome:</label>
<input type="text" name="nome" required="required">
<label>Email:</label>
<input type="email" name="email" required="required">
<input type="submit" name="enviar" value="Enviar">
</form>
</body>
</html>
Related
I'm very new to PHP and I'm trying to build a webpage with a login page. I think I understand it but my login page isn't working even though its very basic.
This is my file structure at the moment:
http://imgur.com/a/zVcPK
This is the idx (index):
<?php
error_reporting( E_ALL );
ini_set( "display_errors", 1 );
include 'templates/header.php';
if(!isset($_SESSION['logged'])){
include 'controller/login.php';
}else{
if($_SESSION['logged'] == true){
include "controller/navigation.php";
}else{
include "idx.php";
}
}
include 'templates/footer.php'
?>
This is the login.php template:
<?php
$out = "<form method='POST' action='idx.php'>
<p>Login:</p>
<label>Username:</label><input type='text' name ='username' required />
<label>Password:</label><input type='password' name'password' required />
<input type='submit' value='submit' name=submit'/>
</form>";
echo $out;
This is the login.php controller:
<?php
include "view/login.php";
if(isset($_POST['submit'])){
$urn=$_POST['username'];
$pwd=$_POST['password'];
$user = new user($urn);
$worked = $user->authenticate($urn, $pwd);
if($worked == true){
$_SESSION['logged']=true;
$_SESSION['username']=$urn;
header('Location: controller/navigation.php');
}
else
{
echo('Error');
}
}
?>
This is the user model:
<?php
class user
{
private $username;
function __construct($username)
{
$this->username=$username;
}
function authenticate($username, $password)
{
if ($username == 'tim' && $password == 'ttt') {
return true;
} else {
return false;
}
}
}
?>
I'm just trying to get the form to take in the users details, check that they are "tim" and "ttt" and if so return a true value which will prompt the controller to change the header URL to navigation.php controller which in turn shows the navigation.php view which will just be a list of links. For some reason though whenever I hit submit nothing happens, it just stays on the login page.
I know this is a pretty basic thing to do but I've been stuck on it for a couple of days now and I've watched hours and hours of videos on it and read dozens of pages explaining how MVC works but can't get this simple thing done. Please can somebody tell me whats going wrong.
Make sure you start the session on every page you want to get or set session variables.
session_start()
It should be as simple as that, and it threw me for a loop for quite a while.
Have you considered using an MVC framework? They are very helpful for keeping everything tidy and organized, as well as providing a library of helpful functions and classes. CodeIgniter is a great and easy to use framework that is super lightweight. Laravel is a lot more invovled and is better suited for large scale projects.
Change this:
<input type='password' name'password' required />
This:(You missed = name='password')
<input type='password' name='password' required />
And dont forget to add session_start() at the very top of your page.
I will share you my sample PHP login page setup.
it has 3 pages, index, admin, logout
index.php: Creates a form asking username and password, once correct username pssword given (here admin, password) it will create a new session "login". Once logged in it will redirect to the admin.php $validuser ensures previous login is true or not.
<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if (isset($_POST["sub"]))
{
$validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
if (!$validUser) $errorMsg = "Invalid username or password.";
else $_SESSION["login"] = true;
}
if ($validUser)
{
header("Location: /admin.php");
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Login</title>
</head>
<body>
<center>
<h1>Login</h1>
<table>
<form name="input" action="" method="post">
<tr>
<th>
<label for="username">Username</label>
</th>
<th>
<input type="text" value="" id="username" name="username" />
</th>
</tr>
<tr>
<th>
<label for="password">Password</label>
</th>
<th>
<input type="password" value="" id="password" name="password" />
</th>
</tr>
<tr>
<th></th>
<th>
<input type="submit" value="Login" name="sub" />
</th>
</tr>
</form>
</table>
</center>
</body>
</html>
admin.php: Checks for session "login", if session was set then it will proceed further otherwise it will go to login.php
<?php
session_start();
if (!isset($_SESSION['login']))
{
header('LOCATION:login.php');
die();
}
?>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
<center>
<h1>Succesfully logged in</h1>
<input type="button" value="Logout" onclick='window.open("/logout.php","_self")'/>
</center>
</body>
</html>
logout.php: Clears the session, cookies and close them and returns to login.php
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name() , '', 0, '/');
session_regenerate_id(true);
header("Location: /index.php");
die();
?>
put them in same folder it will work.
I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php
My problem: even if form fields are empty, the variables are still being inserted into the database.
I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.
I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.
I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist
Login.php:
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<?php
session_start();
$passworderr='';
if(isset($_SESSION["passworderr"])) {
$passworderr=$_SESSION["passworderr"];
}
?>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Form.php:
<?php
session_start();
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if(!isset($_POST["username"])) {
$_SESSION["usernameerr"]="UserName is required";
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if(!isset($_POST["password"])) {
$_SESSION["passworderr"]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if(!isset($_POST["phone"])) {
$_SESSION["phoneerr"]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if(!isset($_POST["mailid"])) {
$_SESSION["mailiderr"]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if(!isset($_POST["city"])) {
$_SESSION["cityerr"]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty.
One way to do that is to use the strlen function.
So an example for you is:
if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {
NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.
You may want to consider using a helper function to do the determination. Basically something like this:
function DoesPostFormFieldHaveValue($formFieldName) {
return(
isset($_POST[$formFieldName])
&& strlen($_POST[$formFieldName]) > 0
);
}
First of all, session_start should always be the first line of the php page you need to use sessions on.
Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.
Here's your updated form :-
<?php
session_start();
if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
{
echo "Please fix the following errors";
foreach($_SESSION['errors'] as $error) //loop through the array
{
echo $error;
}
}
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Backend processing file :-
<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if((!isset($_POST["username"])) || (empty($_POST['username']))) {
$_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if((!isset($_POST["password"])) || (empty($_POST['password']))) {
$_SESSION["errors"][]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
$_SESSION["errors"][]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
$_SESSION["errors"][]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if((!isset($_POST["city"])) || (empty($_POST['city']))) {
$_SESSION["errors"][]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.
Now the solution is to change all your isset() to empty() and that should solve your problem!
[Note] There is no need to use both isset() and empty() like this:
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
because empty() is doing everything that isset() does.
check like this:
if(!isset($_POST["username"]) && $_POST["username"]!="")
Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank.
To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).
Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.
Instead of doing that:
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
Do something like this:
if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))
Should work.
Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.
Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of:
$_SESSION['cityerr']
to:
$_SESSION['errors']['cityerr']
So afterwards, you can clean the specific form error session in one command, like that:
unset($_SESSION['errors']);
Hope it helped ;)
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']
}else
{
unset($_POST['field_name'])
}
OK, so here's my code. (I'll sanitize it later. Don't worry about it.)
gallery_upload_new.php
// Check if user wants to upload to existing or new album
if (isset($_POST['album'])) {
if ($_POST['album'] == '') {
$_POST['album'] = $_POST['new_album'];
}
}
// Populate album dropdown menu
$albums = $database->query("SELECT DISTINCT(album) FROM images")->fetchAll(PDO::FETCH_COLUMN);
// Load the 'upload new photo' interface if user's not uploading it already
if (!isset($_FILES['image_link']) || !isset($_POST['caption']) || $_POST['caption'] == '') {
//var_dump($_FILES);
//var_dump($_POST);
include('views/gallery_upload_new.php');
// Otherwise store the image file, register it into database, and put the user back in the list of photos
} else {
$new_image = new Image($_POST['caption'], $_POST['album']);
$new_image->register($_FILES['image_link']['tmp_name'], $_FILES['image_link']['name']);
header('location: gallery_management.php');
}
?>
views/gallery_upload_new.php
<!DOCTYPE html>
<html>
<head>
<title><?php echo $site_title; ?></title>
<?php include('views/header.php'); //Just the global CSS and JavaScript ?>
</head>
<body>
<?php include('views/nav_menu.php'); //Site navigation panel ?>
<div id="content">
<h1>Upload new photo</h1>
<form enctype="multipart/form-data" action="gallery_upload_new.php" method="post">
<p>
<strong>Upload to album: </strong>
<select name="album">
<?php
foreach($albums as $album_name) {
echo "<option value='$album_name'>$album_name</option>";
}
?>
<option id="selectNewAlbum" value="" selected>New album</option> <input type="text" placeholder="New album name" name="new_album" id="newAlbumName">
</select>
</p>
<p><strong>Photo caption</strong> <input type="text" name="caption"></p>
<p><strong>Photo file: </strong><input type="file" required name="image_link"></p>
<input type="submit" value="Unggah">
</form>
</div>
</body>
</html>
Here's the weird part: without those two var_dump's up there, the else block won't execute. I've made sure the indexes in the $_POST and $_FILES are correct. Yet without those dummy dumps, this thing won't work. It'd just load the views/gallery_upload_new.php no matter what.
It doesn't even matter if they're commented out or not. They just need to be there.
What did I do wrong? Did I made a syntax error somewhere?
<?php
ob_start();
// First we execute our common code to connection to the database and start the session
define('MyConst', TRUE);
include('../database.class.php');
include('../table.class.php');
include('../user.class.php');
include('../loginattempts.class.php');
include('../timer.class.php');
include('../characters.class.php');
include('../weapontype.class.php');
include('../objects/weapons/weaponobject.class.php');
include('../objects/weapons/bowieknife.class.php');
include('../npc/enemy.class.php');
include('../npc/skinhead.class.php');
include('../npc.class.php');
include('../npctype.class.php');
include('../functions.php');
include('../loginf.php');
include('locationf.php');
$dbo = database::getInstance();
$dbo -> connect("***************", "********", "********", "***************", array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
secSessionStart();
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
$_SESSION['currentlocation'] = "combat.php";
?>
<?php
if($_POST['formSubmit'] == "Submit")
{
$varMovie = $_POST['formMovie'];
echo $varMovie;
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="index.php" method="post">
Which is your favorite movie?
<input type="text" name="formMovie" maxlength="50">
<input type="submit" name="formSubmit" value="Submit">
</form>
</body>
</html>
Ok...so its supposed to echo out some text. Instead it just reloads the form! I'm not sure what else to write and it won't allow me to post so i'm just going to repeat what i've wrote until i reach the limit.
Add an ELSE part in the HTML, that will either show the form OR the answer, but keeps the header etc intact.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if($_POST['formSubmit'] == "Submit")
{
$varMovie = $_POST['formMovie'];
echo $varMovie;
}
else {
?>
<form action="index.php" method="post">
Which is your favorite movie?
<input type="text" name="formMovie" maxlength="50">
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php } ?>
</body>
</html>
I would tend to use:
<?php
if (array_key_exists("formSubmit",$_POST) && !strcmp($_POST["formSubmit"],'Submit'))
{
$varMovie = $_POST['formMovie'];
echo "Movie=(${varMovie})<br>\n";
}
:
:
Also comment out all the includes etc. above this, check it's giving you the contents of formMovie then add the other stuff back in gradually until it fails (or not).
Cheers.
I am a beginner to PHP and i want to make a static method that if its argument is empty it'll show the message. If not, it'll set the given message to a static variable for later use. But when i call the method to set the message, and then call it in another page to show the message. Nothing appear.
Here's my portion of code for this "session.php" :
class Session {
public static $message;
public static function notify($message = ""){
if(!empty($message)){
self::$message = $message;
} else {
return self::$message;
}
}
}
$session = new Session();
"add_user.php" :
<?php
require_once '../helper/session.php';
?>
<?php
if (isset($_POST["submit"])) {
$user->username = $_POST["username"];
$user->password = $_POST["password"];
$user->first_name = $_POST["first_name"];
$user->last_name = $_POST["last_name"];
if($result = $user->add_user()){
Session::notify("New user added");
redirect_to("../view/login.php");
} else { Session::notify("Cannot add new user"); }
}
?>
"login.php" :
<?php
require_once "../control/add_user.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="../stylesheet/login.css" />
<title>Welcome to Harmony</title>
</head>
<body>
<header>
<h2>Harmony</h2>
</header>
<section>
<div id="formStyle">
<h3>Login or Signup:</h3>
<form action="login.php" method="post">
<p><label for="username">Username: </label>
<input type="text" name="username" value="" placeholder="Username"/></p>
<p><label for="password">Password: </label>
<input type="text" name="password" value="" placeholder="Password"/></p>
<input type="submit" name="submit" value="Submit" />
<input type="button" name="sign_up" value="Sign up" onClick="parent.location='add_user.php'">
</form>
<?php echo Session::notify(); ?>
</div>
</section>
</body>
</html>
You aren't really writing to the session, now are you?
You should create two more methods for getting and setting the variables in the actual session. After the redirect, your message dissapears, because it is only saved on script execution.
function set_notification($message) {
$_SESSION['notification'] = $message; }
function get_notification() {
if(!empty($_SESSION['notification'])) {
return $_SESSION['notification']; }
Something like that :)
Of course, for sessions to work, you should do a session_start() call in the beginning of the script. read more about them here
HTTP by nature is shared-nothing, so anything you do in one request is not available to any other request. You will need to use a shared datastore to persist these messages.
A database, memcache, even a text file on the server (assuming you are operating on a single server and are not load balancing multiple) are all choices.
You can use cookies on the client side to persist a small amount of data. But keep in mind its not a secure solution (without using encryption) and you are limited in the amount of data you can store in cookies.
HTTP - and PHP - is stateless. You need to use session variables to track data across sessions
http://www.php.net/manual/en/book.session.php