I'm a beginner to PHP and trying to write a code, that does form validation.
It's nothing fancy just testing it out. I just wrote a function that test the Age input text whether it's a number or not. If it isn't it stores an error in an array and then display that error in another page. I saw this method in a video tutorial , but couldn't do it myself. When i try to invoke that error (not numeric value in Age) it always shows me this error in my add.php page :
Notice: Undefined variable: errors in /home/rafael/www/RofaCorp/add/add.php on line 37
How do i declare a variable that can be accessed through my whole project ?
Here's my code :
form_validation.php
<?php
function validate_number($number) {
global $errors;
if (is_numeric($number)) {
return $number;
}else {
$errors[] = "Value must be number";
}
if (!empty ($errors))
{
header("Location: ../add.php");
exit;
}
}
?>
create_ind.php
<?php require_once '../../include/connection.php'; ?>
<?php require_once '../../include/form_validation.php'; ?>
<?php require_once '../../include/functions_database_infoget.php'; ?>
<?php
$family_id = get_family_info_fam("id");
$ind_name = mysql_real_escape_string($_POST["ind_name"]);
$age = validate_number(mysql_real_escape_string($_POST["age"]));
$gender = $_POST["gender"];
$notes = mysql_real_escape_string($_POST["notes"]);
$add_query = "INSERT INTO individual
( g_id , ind_name , age , gender , notes)
Values ( {$family_id} , '{$ind_name}' , {$age} , '{$gender}' , '{$notes}')";
if(mysql_query($add_query , $connection)){
header("Location: ../../main.php");
exit;
} else {echo "ERROR " . mysql_error() ; }
?>
<?php mysql_close($connection); ?>
add.php (a portion of my code)
<!--Main Content-->
<section id="mainContent">
<header>
<h3>Select where to add new Family/Individual.</h3>
</header>
<article>
<?php
if (count($errors) > 0) {
for($i=0 ; $i < count($errors) ; $i++){
echo "{$errors[$i]}" . "<br/>";
}
}
?>
</article>
</section>
A global variable is only defined while your scripts are processing, as soon as you do header("Location: ../add.php"); you are loading a new page and all variables are lost. That´s what the error message is telling you, there is no variable $errors in add.php.
If you want your error message to persist between different page loads, a session variable is a good option (there are of course others like databases, etc.). Just start the session again in add.php and you have access to the variables stored in the session.
If it is shown in another page, use sessions.
Will allow you to retrieve variables from other pages.
You can use this simple tut http://www.tizag.com/phpT/phpsessions.php
Related
When users comming this link www.sitename.com/index.php?userid=1
But user dont need to login.
I want to do change some value for the ID =1 user at the database. How can I change value. When the user just come this url address ?
This is my index.php code: (that include some other codes about qr code)
<?php
require "header.php";
require_once 'phpqrcode/qrlib.php';
$path='img/';
$file = $path.uniqid().".png";
?>
<?php
echo 'Current PHP version: ' . phpversion();
?>
<main>
<div class="wrapper-main">
<section class="section-default">
<?php
if (!isset($_SESSION['userID'])) {
echo '<p class="login-status">You are logged out!</p>';
}
else if (isset($_SESSION['userID'])) {
$text="http://sitename.com/project/userid{$_SESSION["userID"]}";
echo '<p class="login-status">You are logged in!</p>';
QRcode::png($text,$file,'L',10,2);
echo "<center><img src='".$file."'></center> " ;
}
?>
</section>
</div>
</main>
<?php
require "footer.php";
?>
EDIT 1
When I try this I failed where is my fault ?
<?php
if(!empty($_GET['user_idx'])){
$user_idx=$_GET['user_idx'];
require_once 'dbh.inc.php';
$sql = "UPDATE users SET balance=balance-5 WHERE user_idx='$user_idx';";
mysqli_query($conn,$sql);
}
In the dbh.inc.php
$servername ="127.0.0.1";
$dBUsername="xx";
$dBPassword="xx";
$dBName="xx";
$conn= mysqli_connect($servername,$dBUsername,$dBPassword,$dBName);
if(!$conn){
die("Connection failed:".mysqli_connect_error());
}
Data being fetched from the URL directly may be accessed or retrieved via the GET method
For your URL www.sitename.com/index.php?userid=1, you may access the userid=1 part by using the code $_GET['userid'] // which will result into "1"
Now, if you want to change it, you may create a link then pass a variable or new value to it:
In your case:
$text="http://sitename.com/project?userid{$_SESSION["userID"]}";
//we will treat the "userid" as a variable now
//so for you to fetch it, use:
//$_GET['userid']
Hi i'm developing a multi steps form with php using session and i've been wondering if there is a way for the user to alter session variables for example on the first page i have something like this :
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['name'] = $_POST['name'];//and so on
}
?>
and the other page has something like :
<?php
session_start();
$name = $_SESSION['name'];
?>
my question is can the user modify the value of the session variable on the second page
Since you're populating the session variable with the value of a POST variable, they can continue to resubmit the first form as much as they want with arbitrary values.
You can use application logic to defeat this:
<?php // form1
session_start();
if (empty($_SESSION['step'])) {
$_SESSION['step'] = 1;
}
if ($_SESSION['step'] > 1) {
header("Location: form2.php");
exit; // This exit is very important, don't neglect it
}
if (isset($_POST['submit'])){
$_SESSION['name'] = $_POST['name'];//and so on
$_SESSION['step'] = 2;
}
And then
<?php // form2
session_start();
if (empty($_SESSION['step'])) {
header("Location: form1.php");
exit;
}
if ($_SESSION['step'] > 2) {
header("Location: form3.php");
exit;
}
if ($_SESSION['step'] < 2) {
header("Location: form1.php");
exit;
}
$name = $_POST['name'];
By using application logic, you can control the flow of your visitors within your application.
If you're asking if users can change $_SESSION variables outside of any code you've written, the answer is usually no. See also: this answer.
I am trying to display an error message when there is a username-password mismatch. I set a php session variable if username and password dont match. Then i header back to the same page, with an if conditioned php statement to display an error if the variable is set. But when i unset the variable after error display, there is no error displayed on the page.
I have seen similar problems mentioned in this forum. But i seem to be doing everything right as suggested in questions.. Please help me out...
This is part of my code flow...
<?php
ob_start();
session_start();
.
.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
header('Location: index.php');
}
.
.
//in html body
<?php
if (isset($_SESSION['user_found'])){
if($_SESSION['user_found'] == 0){
?>
<div>
<p class = "bg-danger text-danger">Username Password Mismatch</p>
</div>
<?php
unset($_SESSION['user_found']);
}
}
?>
Now, if unset is removed..it works fine. If it is there, there is no display of error message.
Try not reloading the same page.. remove the header redirect.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
//header('Location: index.php');
}
When I tried the your code, things seem to work fine. Something should be wrong with the code you've not mentioned here..
To troubleshoot the problem instead of
unset($_SESSION['user_found']);
try changing the value of the variable.. say
$_SESSION['user_found'] = -1;
I'm trying to integrate a php login script that I have working, but I can't seem to get simple php calls going on a page. On this user profile page, I want to simply have the user name displayed (mysql field is "name"). The user is logged in and the session carries through, but on this page, all I see is the text "Here is your profile info..." What might be wrong in the code to prevent the user name from displaying?
<?php
include_once('classes/check.class.php');
include_once('header.php');
if( protectThis("*") ):
if(!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['jigowatt']['name'])) {
echo "You're name is: " . $_SESSION['jigowatt']['name'];
}
?>
<br />
Here are is your profile info...
<?php
else :
?>
<div class="alert alert-warning">
<?php _e('Only signed in users can view what\'s hidden here!'); ?></div>
<?php
endif;
include_once('footer.php');
?>
For check session is set already use session_id() Also check you have set $_SESSION['jigowatt']['name'] already with empty()
if(session_id() == '') {
session_start();
}
if(!empty($_SESSION['jigowatt']['name'])) {
echo "You're name is: " . $_SESSION['jigowatt']['name'];
}
else {
echo 'username is empty';
}
You need to put session_start(); at the very top of the page. No white space can be put before that. Try if that works.
First you need to write the sessions at the very top of the page if it works than okay else you can try this.
Just append this 2 function before and after the session_start();
Like this
ob_start();
session_start();
ob_end_clean();
I'm working on a log in session, and I want to display errors on the same page, for example - "Invalid Password" or "User does not exist".
Heres my code:
<?php
session_start();
mysql_connect('mysql.database.com','user','database')or die ('Connection Failed: '.mysql_error());
mysql_select_db('database')or die ('Error when selecting Database: '.mysql_error());
function remove($mensaje)
{
$nopermitidos = array("'",'\\','<','>',"\"");
$mensaje = str_replace($nopermitidos, "", $mensaje);
return $mensaje;
}
if(trim($_POST["usuario"]) != "" && trim($_POST["password"]) != "")
{
$usuario = strtolower(htmlentities($_POST["usuario"], ENT_QUOTES));
$password = $_POST["password"];
$result = mysql_query('SELECT password, usuario FROM usuarios WHERE usuario=\''.$usuario.'\'');
if($row = mysql_fetch_array($result)){
if($row["password"] == $password){
$_SESSION["k_username"] = $row['usuario'];
header( 'Location: diseno.php' ) ;
}else{
echo '<p class="message2">Invalid password</p>';
}
}else{
echo '<p class="message2"User does not exist</p>';
}
mysql_free_result($result);
}else{
echo '<p class="message2">Must enter a user and password</p>';
}
mysql_close();
?>
<SCRIPT LANGUAGE="javascript">
location.href = "index.php";
</SCRIPT>
As you can see that's my validation and action for the log in form. Instead of echoing errors in a new page I want to display it in the same page. I tried with javascript and it didn't work I used.
var page = document.URL = "http://www.mysite.com/login.php"
page.getElementById( 'wrongpassword' ).style.display = 'block';
All divs I want to display are set as none in the login.php file.
Anyone could help me?
The easiest way to accomplish this is to process the login and then include the PHP code which displays the normal page. I'm not sure how you've designed your site, but including index.php at the end might do the trick. Right now, you are using a JS redirect, which won't give you the result that you want.
Instead of echoing the message, I like to set a $message variable which includes the message. When you render the main page, simply echo this variable in the appropriate place if it is set.
For doing it simply you can make use of JQuery. I have done it on my website so I can say it really works.
Start your session, checking the values and either assign the value in global variables of javascript or print it there only
eg.
<?php
session_start();
//checking ur values
echo "<script src=\"js/jquery-1.8.3.min.js\"></script>
<script type=\"text/javascript\">
$(document).ready(function(){
//you can assign values here or print error messages to any div
('.div_class').html("unuthorised user");
});
</script>";
?>
Here I have used a downloaded JQuery file from
http://jquery.com/download/
You can choose other wise to use the online version of this JQuery file. The syntax for that is
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
Feel free to get back in case of any further query/issues regarding the above code.