I have a file "test.php" like this:
<?php
session_start();
unset($_SESSION['ph']);
require 'connection.php';
if(!session_id())
session_start();
else
{
echo session_id();
echo "<br>";
echo var_dump($_SESSION);
}
$ph = 0;
if(isset($_POST['ph']))
if(isset($_POST['submit']))
{
$ph = $_POST['ph'];
$q1 = "select PHONE_CUST_ID from PHONE where PHONE_NO = :ph_bv";
$prepare = oci_parse($conn, $q1);
oci_bind_by_name($prepare, ':ph_bv', $ph);
oci_execute($prepare);
$res = oci_fetch_array($prepare, OCI_ASSOC);
if(!$res)
header('Location:newcustomer.php');
else
header('Location:oldcustomer.php');
}
?>
<!doctype html>
<html lang="en">
<body>
<form method="POST" action="" id="custphoneform">
<label for="PhoneNumber">Enter Phone Number:</label>
<input type="number" name="ph" required>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
The "oldcustomer.php" and "newcustomer.php" have similar code as below:
<?php
require 'connection.php';
session_start();
if(isset($_SESSION['ph']))
{
echo $_SESSION['ph'];
}
else
echo "Not found";
?>
The session variable is not working, gives me the following error:
Notice: Undefined index: ph in D:\xampp\htdocs\myfiles\newcustomer.php on line 4
The session works properly if I set the "form action" to some value but I don't want that. I want redirection based on user input. How to achieve it?
Example:
"test.php"
Enter Phone Number: 100
Based on the above value i.e. 100 I want to direct the user to different pages. If the number exists in the DB then oldcustomer.php otherwise newcustomer.php.
How can I do this?
You didn't give any value for action attribute here, So it will always post the data on current page only which is test.php. So you are getting error at oldcustomer.php when you are trying to access the variable.
<form method="POST" action="" id="custphoneform">
either you can directly post your data to oldcustomer.php by specifying it in action attribute as
<form method="POST" action="oldcustomer.php" id="custphoneform">
or you should store your data in $_SESSION global variable so you can access it anywhere in your project as
$_SESSION['ph'] = $_POST['ph'];
use this variable in oldcustomer.php as
<?php
session_start();
if(isset($_SESSION['ph'])){
echo $_SESSION['ph'];
}else{
echo "Phone number not found";
}
?>
You are redirecting after form post. At that time new request will be initialize which doesn't contain post data. Whsat you can do is in test.php assign session which will then use in any page
test.php
<?php
session_start();
require 'connection.php';
$ph = 0;
if(isset($_POST['ph']))
if(isset($_POST['submit']))
{
$ph = $_POST['ph'];
$q1 = "select PHONE_CUST_ID from PHONE where PHONE_NO = :ph_bv";
$prepare = oci_parse($conn, $q1);
oci_bind_by_name($prepare, ':ph_bv', $ph);
oci_execute($prepare);
$res = oci_fetch_array($prepare, OCI_ASSOC);
if(!empty($_POST['ph']))
$_SESSION['ph'] = $_POST['ph']; //assign value to session
if(!$res)
header('Location:newcustomer.php');
else
header('Location:oldcustomer.php');
}
?>
oldcustomer.php and newcustomer.php
<?php
session_start();
echo $_SESSION['ph'];
?>
you redirect to xxxcustomer.php (by the line header('Location: ...);. That will be a GET request.
So $_POST is empty.
So the if() will not be executed. { } are missing so the echo line will be executed next.
But no $_SESSION['ph'] is set >>> warning missing index ph
edit
I suppose you better do an include() on those xxxcustomer.php files?
EDIT 2
As you changed your code in the question, this answer makes no sense anymore.
Bottom line remains: after a redirect you loose the values in $_POST as it no longer is a POST-request
Related
Down, in the second page i am not getting the session variable values. Actually sessions variables are not recieving in second file(index.php).
Error is Notice: Undefined index: userid in /storage/ssd5/520/5088520/public_html/index.php on line 150
1 - login.php //file 1
session_start();
if (isset($_POST['login'] ))
{
$_SESSION["userid"] = $_POST["userid"];
$_SESSION["user"] = $_POST["user"];
$userid=$_SESSION["userid"];
$user=$_SESSION["user"];
if ($userid=='' || $user=='')
{
//generate error
echo 'ERROR: Please fill in all required fields!';
renderForm();
}
else
{
//query
$result = mysql_query("SELECT user_id FROM users WHERE user_id='$userid'
AND user='$user'") or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row['user_id'] == 1 || $row['user_id'] == 2)
{
$_SESSION['login_status'] = true;
echo "<script> window.open ('index.php','_self') </script>";
}
else
{
echo "Sorry, No account exist";
}
}
}
//if submit button not pressed yet. show form:
else
{
//now show form
renderForm();
}
//redenring form
<?php
//function starts
function renderForm()
{
?>
<form role="form" method="post">
<input placeholder="User ID" name="userid" type="text">
<input placeholder="User" name="user" type="text">
<button type="submit" name="login">Login</a>
</form>
<?php
} //function ends
?>
Second file where error comes
2-index.php //file 2
<?php
session_start();
if ($_SESSION['login_status']==false) {
header("Location:login.php"); } else { ?> <body> //somewhere inside here i am accessing the session variables <?php
if ($_SESSION['userid']==1) //line 150
{
echo "<a class='navbar-brand' href='index.php'>Admin</a>";
}
if ($_SESSION['userid']==2 )
{
echo "<a class='navbar-brand' href='index.php'>Clerk</a>";
} ?> </body>
on local host. this code runs . But i am now hosting it. but i am not understanding, what can be the issue?
Declare session_start(); on second page.
You need to add session_start(); at the top of the second file in order to access session variables in it.
Add session_start(); in every page you are accessing session variables from otherwise it doesn't work. It is a requirement to start the session in order to access the super global variable $_SESSION.
Edit:
You need to use if( !isset($_SESSION['userid']) ) instead of
if ($_SESSION['userid']==1) on the index.php page.
Otherwise, it will throw you undefined index error if you are
visiting the index.php before attempting to log in.
You may have noticed that your code doesn't throw error if you visit index.php after logging in.
Okey guys , i try to secure page with access code ,but page is not secrued if some people write in url pagename.php page is loading without checked my code is. Code is work after put correct access code redirect to my page but , page is not secured client visit page without code after write in url my page .....
<?php
include ('modules/conf.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$secretcode = mysqli_real_escape_string($db,$_POST['secretcode']);
$sql = "SELECT * FROM password WHERE password = '$secretcode'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $secretcode;
session_start();
header("location: question.php");
}else {
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("", "Съжеляваме вашият код е невалиден");';
echo '}, 1000);</script>';
}
}
?>
<div class="section">
<div class="container-fluid gamebox">
<div class="row">
<div class="col-md-6">
<div class="secretcode">
<h1 class="text-center">въведете код от брошурата</h1>
<form action="" method="post" class="formsecretcode text-center">
<input type="secretcode" id="codeverify" name="secretcode" placeholder="въведете вашият код">
<input type="submit" class="buttonsubmit" name="submit" value="провери код">
</form>
</div>
</div>
As I stated in comments and seeing that nobody posted an answer so far, am submitting the following.
Check to see if the session is set (with an optional "if { equal to something }"), and if not, else { kick them out }.
The logic is, and to be part of every page using sessions that you wish to protect and assuming $secretcode equals 12345 as an example:
<?php
session_start();
if (isset($_SESSION['login_user']) && $_SESSION['login_user'] == '12345'){
// Do something
}
else {
// Do something else
}
It's also best to add exit; after header, otherwise your code may want to continue executing.
Reference:
http://php.net/manual/en/function.header.php
Footnotes:
You don't need to use session_start(); twice as that may trigger that the session was already started.
Use it once and at the "top" of every page, while making sure you're not outputting before header.
References:
http://php.net/manual/en/features.sessions.php
How to fix "Headers already sent" error in PHP
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional notes:
You could optionally check for both a username and secret word in the query which makes it a bit more unique.
$username = "Johnny B. Good";
$sql = "SELECT * FROM password
WHERE username = '$username'
AND password = '$secretcode'";
Unless you're only checking for a secret code only, then leave your query the way it is now.
I apologise for the trivial question, but I have been having problems using the header() php function to redirect to pages. More specifically I am struggling to redirect a user when he/she tries to view a non existent profile page. My problem is that I am always including a header file which contains session start and some html to display a basic header. Does this mean I cannot use the header() function to redirect to pages in my scripts that include this header file?
I thought one way to get around the problem might be to split the html part of the header into a separate file, and include the header scripts first, then write my profile scripts, and finally include the html part of the header. Is that bad practice? the profile.php script follows:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
if(isset($_GET['u'])) {
//check user exists
$username = mysql_real_escape_string($_GET['u']);
if (ctype_alnum($username)) {
$check = mysql_query("SELECT username, email FROM users WHERE username = '$username'");
if (mysql_num_rows($check)===1) {
$get = mysql_fetch_assoc($check); //execute query and store in array
$username = $get['username'];
$email = $get['email'];
}
else {
header("Location: index.php");
die();
}
}
else {
echo "username has to be alphanumeric";
}
}
else {
echo "error";
}
?>
<h2> Profile page of <?php echo "$username";?>
<h3> Email: <?php echo "$email";?>
header.inc.php file:
<?php
include ("inc/scripts/mysql_connect.inc.php");
//start the session
session_start();
//Checks whether the user is logged in
$user = $_SESSION["user_login"];
if (!isset($SESSION["user_login"])) {
//header("Location: index.php");
//exit();
}
else
{
header("location: home.php");
}
?>
<?php
//Login Scripts has to be at the top to make sure header() redirecting works
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i','', $_POST["user_login"]); //filter user login text
$password_login = preg_replace('#[^A-Za-z0-9]#i','', $_POST["password_login"]); //filter user password text
$md5password_login = md5($password_login);
$sql = mysql_query("SELECT id FROM users WHERE username='$user_login' AND
password='$md5password_login' LIMIT 1"); //query the user
//Check for user's existence
$userCount = mysql_num_rows($sql); //count number of rows
if ($userCount == 1) {
while ($row = mysql_fetch_array($sql)) {
$id = $row["id"];
}
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $md5password_login;
header("Location: home.php");
exit();
}
else {
echo "That information is incorrect, try again";
}
}
?>
<html>
<head>
<link href = "css/main.css" rel = "stylesheet" type = "text/css">
<title> title </title>
</head>
<body>
<div class = "wrapper">
<div id = "header">
<div class = "logo">
<img src = "img/Logo.png">
</div>
<div id = "login-header">
<form action = "index.php" method ="post" name = "form1" id = "form1">
<div class = "input-wrapper"><input type = "text" size = "25" name = "user_login" id = "user_login" placeholder = ">Username" ></div>
<div class = "input-wrapper"><input type = "password" size = "25" name = "password_login" id = "password_login" placeholder = "Password" ></div>
<div class = "input-wrapper"><input type = "submit" name = "login" value = "Sign in"></div>
</form>
</div>
<div id = "menu">
</div>
</div>
</div>
You can include files wherever you want. The problem is OUTPUT. If you're going to be doing header() calls, you cannot have performed ANY output prior to the call. If your includes are simply spitting out output, and are not just defining functions/vars for later use, then you'll have to have to modify the includes to NOT do that output, or at least buffer/defer the output until later. e.g.
<?php
include('some_file_that_causes_output_when_loaded.php');
header('This header will not work');
will fail no matter what, because your include did output, and kills the header call. But if you mod the include, so you have something more like:
<?php
include('file_that_just_defines_functions.php');
header('This header will work');
function_from_include_that_causes_output();
will work just fine. If you can't mod the code, then
<?php
ob_start();
include('some_file_that_causes_output_when_loaded.php');
header('This header will still work, because we're buffering output');
ob_end_clean();
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
I am trying to simply set a variable and have it passed back to the same PHP script as called, however it doesn't work.
The first time the script is run I see what I expect to see on screen which is
Your store is USA and your language is
en
If I then choose UK and press submit I see the following line
Your store is and your language is en
My sample code is
<?php
if(isset($_POST['submit'])){
$store = $_GET['store'];
$lang=en;
}
else
{
$store=143441;
$lang=en;
}
switch ($store)
{
case "143441":
$storename="USA";
break;
case "143444":
$storename="UK";
break;
}
?>
<head>
</head>
<body>
<form name="store" method="post" action="test.php">
<select name="Store">
<option value="143441">USA</option>
<option value="143444">UK</option>
</select>
<INPUT TYPE="submit" name="submit" value="submit">
</form>
<?php echo "Your store is " . $storename . " and your language is " . $lang; ?>
</body>
</html>
In the first if clause use
$store = $_POST['Store']; //be aware of the upper case!!!!!
instead of
$store = $_GET['store'];
and everything will be fine.
Your sample code:
if(isset($_POST['submit'])){
$store = $_GET['store'];
Your problem is that you're mixing $_POST and $_GET.
Since your form is doing a POST action, you should be using $_POST for both of those lines.
You could also use $_REQUEST if you're not sure whether it'll be a post or a get request, but generally it'd be better to use $_POST in your case, since you know it'll always be a post.
You should use $_POST['store'] instead of $_GET['store'] since it's a POST request parameter.
<?php
if(isset($_POST['submit'])){
$store = $_POST['store'];
$lang='en';
}
else{
$store=143441;
$lang='en';
}
switch ($store){
case "143441":
$storename="USA";
break;
case "143444":
$storename="UK";
break;
}
?>