Submit returning a blank page - php

A blank page is returned when I try to add a new note. My code is in php and the DB is mysql
This is the php code:
if (isset($_POST['Submit'])) {
$candidate_id = $_POST['candidate_id'];
$Notes = $_POST['notes'];
if ($Notes != "") {
$sql3 = "INSERT INTO notes (notes_id, candidate_id, notes) VALUES(DEFAULT,'$candidate_id','$Notes')";
$result3=mysql_query($sql3);
if (!$result3) {
die('Error: ' . mysql_error());
}
echo "</br>1 note added"
}
}
mysql_close();
The code for the form
<div id="tab3">
<h2> Notes </h2>
<dl>
<dt>Notes</dt>
<dd>
<textarea id="notes" style="width: 80%; height: 150px;" name="notes"></textarea>
</dd>
</dl>
<?php
echo "";
?>
</div>

try
if($_SERVER['REQUEST_METHOD']=="POST"){
or
if(isset($_POST['update'])){
instead of
if (isset($_POST['Submit'])) {
the name of the submit button is update not Submit on your form
also stop using mysql_* functions. If you have to use them for now, at least escape the inputs properly before inserting them to database.

To sum this up:
use error reporting in the beginning of your script
error_reporting(E_ALL);
Echo out the SQL query (after you created it) to see what weird, unescaped stuff you want to send to the server:
echo $sql3;
exit; // to prevent execution
Try the echoed SQL with phpmyadmin to see if the problem is your query or the missing database connection.
There are a lot more bad things in your script, but for first error-tracing those tips might be okay... In general, i recommend you to completely rewrite this after you read into SQL injection, modern database query methods, proper php coding etc. ! To finish your project, you should consider using a micro framework to get quick and secure results.

in your submit button you have no form
try this
<div id ="tab3">
<h2> Notes </h2>
<dl><dt>Notes</dt><dd><form action="" method="post" name="myform"><textarea id="notes" style="width: 80%; height: 150px;" name="notes"></textarea></dd></dl>
<?php echo "</form>";
?> </div>
and please avoid using inner css , please use classes in other css file.

Try This
<?php
if(isset($_POST['submit'])){
// Code
<?php
}
else
{
echo "form not submited properly";
}
?>
<?php
include 'header.php';
include 'nav.php';
include 'config.php';
?>
Except
<?php
include 'header.php';
include 'nav.php';
include 'config.php';
?>
<?php
if(isset($_POST['submit'])){
// Code
<?php
}
else
{
echo "form not submited properly";
}
?>

Related

PHP Myqsli Form automatically returning to previous page in Chrome but not in Edge?

I have a form that submits fields to a database using mysqli that was working perfectly; however, I pulled up the form page in Chrome and tried to submit a new row to the db, only for the page to go back to the previous page when I tried to click on the form's text-areas. I tried clearing all of my browser history (cache, cookies, etc.) and asked a friend to try it on their Chrome browser, with the same result.
The kicker? It works in Edge. Makes no sense.
I've gone through the code and can't find any missing <'s or quotes, etc. Everything was working fine and I can't imagine why it would suddenly start doing this in Chrome.
(Note: I know this code is clunky and vulnerable to SQL injection, but I don't have any users/sensitive data to protect, for the moment. Also, I made no changes to head.php or any code (that I can recall), just confused as to why it would suddenly start redirecting me back to notebook.php as soon as I click on a text area in Chrome but not in Edge.)
Notebook_add.php
$con = #mysqli_connect('localhost', 'root', 'pass', 'db');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
?>
<body>
<div class="wrapper">
<h1>Post Comments</h1>
<?php
include ('navbar.php');
?>
<br>
<form name="noteworthy" METHOD=POST action=<?php echo $_SERVER['PHP_SELF']; ?>>
<br>
Title: <input type="text" name="title" id="$title" size="50"> <br>
Link: <input type="text" name="link" id="$link" size="50"><br>
Description: <TEXTAREA NAME="description" id="$description" ROWS="5" COLS="30"></TEXTAREA><br>
<Input type="submit" name="enter" id="$enter" value="enter">
</form>
<?
echo $submitted = date("Y-m-d");
?>
<?
$title = $_REQUEST['title'];
$link = $_REQUEST['link'];
$description = $_REQUEST['description'];
$enter = $_REQUEST['enter'];
if(isset($_REQUEST['enter'])){
$submitted = date("Y-m-d");
$sql = "INSERT INTO notes (title, link, description, submitted) VALUES ('$title','$link','$description','$submitted')";
}
if(mysqli_query($con, $sql)){
echo "Records inserted successfully.";
print "<meta http-equiv='refresh' content='0; url=http:notebook.php' />";
}
// Close connection
mysqli_close($con);
?>
<div class="push"> </div>
</div>
<?php
include 'footer.php';
?>
</body>
So what happened was that I had added a new menu item in my navbar.php and forgot to close the link tag (e.g., " New menu item "). This made the entire php form into a link, so whenever I anywhere on it under my navbar I was returned to the previous page.
It is interesting that this didn't happen in Edge; perhaps there is some feature in Edge that automatically closes rogue tags.
Anyway, thanks for responding. #Smith, thanks for the tip, I'm using the php head featured/location function instead of meta-refresh now.

Remove HTML tags in textaera (Basic CMS)

I am very new to PHP and started making a light weight CMS. I have stored all the body content in the database and the CMS calls it from the database and displays it in a text area to be edited. However I was wondering is there a way to make it display the text without HTML tags. I have tried the strip_tag function however when I hit save on my cms it saves without the html tags! how will I go about making it display the data from the database without HTML tags but when I save it, it will save with the HTML tags! Sorry if this question is not clear but it is quite difficult to explain. Here is my code so far working fine:
<?php include_once "includes/scripts.php"; ?>
<?php include_once "includes/connect.php";?>
<?php include_once "includes/cms_page_security.php";?>
<?php
$sql = "SELECT * FROM content WHERE id = '5'";
$result = mysql_query($sql, $connect);
$num= mysql_numrows($result);mysql_close();
$row = mysql_fetch_row($result);
$pg_content = $row['1'];
if (isset($_POST['saveChanges'])){
$pgcontent = $_POST['edit'];
$sql_query = ("UPDATE content SET cage_content= '$pgcontent' WHERE cage_content= '$pg_content'");
mysql_query($sql_query,$connect);
header('location: admin_cms_staff.php');
$feedback = "Updated successfully";
}
?>
<div id="cms_container"><br>
<h1>Staff Page<img src="images/three_column_grid_line.png" alt="line"></h1>
<form id="form1" name="form1" method="post">
<textarea id="content" name="edit"><?php echo $pg_content; ?></textarea>
<input type="submit" class="submit_edit" value="Save" name="saveChanges" onClick="alertFunction()">
</form>
<p class="logout_btn">Back</p>
<?php if(isset($_POST['saveChanges'])){
echo $feedback;}?>
</div><!--cms_container-->
<script>
function alertFunction()
{
var r=confirm("Do you want to save the changes you made to the page?");
if (r==true)
{
}
else
{
return;
}
}
</script>
</body>
</html>
Change this:
$pgcontent = $_POST['edit'];
to:
$pgcontent = strip_tags($_POST['edit']);
And also change this:
<textarea id="content" name="edit"><?php echo $pg_content; ?></textarea>
to:
<textarea id="content" name="edit"><?php echo strip_tags($pg_content); ?></textarea>

Can't get variables from SESSION

I'm having a problem with my school project. I've asked both my teacher and classmates for help but none of them doesn't know what to do.
I've made a browser based game, and obviously it needs to have users. And this is where the problem is.
When i log in and proceed to the authenticate page, it extracts info from POST just fine, but when i insert the info into SESSION in authenticate and then go to the homepage index, it refuses to get the SESSION information and i just get an error.
NOTE, design2.php doesnt have anything to do with the log in process.
Here's the code:
Login.php
<?php
include_once'design2.php';
?>
<div id="center">
<form method="POST" action="authenticate.php">
User Name <input id="input" type="text" name="player" size="21">
Password <input id="input" type="password" name="password" size="21">
<br>
<input type="submit" value="Login" name="submit">
<br><br>Not Registered? <a id='underlinelink' href='register.php'>Register</a>
Authenticate.php
<?php
include_once 'connect.php';
?>
<div id="center">
<?php
if (isset($_POST['submit']))
{
$player=$_POST['player'];
$password=$_POST['password'];
$player=strip_tags($player);
$password=strip_tags($password);
$password=md5($password);
$query = "select name, password from players where name='$player' and password='$password'";
$result = mysql_query($query) or die("Could not query players");
$result2 = mysql_fetch_array($result);
if ($result2)
{
$_SESSION['player'] = $player;
echo "<big>Logged in successfully<br>";
echo "<A id='underlinelink' href='index.php'>Continue</a></big>";
}
else
{
echo "<big>Wrong username or password.<A id='underlinelink' href='login.php'>Try Again</a></big>";
}
}
?>
</div>
Design.php (This is on every single webpage on my site)
<?php
include_once 'connect.php';
?>
<link href="stilark.css" rel="stylesheet" type="css" />
<?php
session_start();
if(isset($_SESSION['player']))
$player = $_SESSION['player'];
else
echo "could not logg in, <a href='login.php'>Go back</a>";
exit;
$playerinfo="SELECT * from players where name='$player'";
$playerinfo2=mysql_query($playerinfo) or die("could not get player stats!");
$playerinfo3=mysql_fetch_array($playerinfo2);
?>
Please help, i really need to get this done before its due.
You need to create or resume the session before you write into it. So in your Authenticate.php where you do $_SESSION['player'] = $player;, create a session first exactly as you do it in your other files. Something like that
Authenticate.php
<?php
session_start();
include_once 'connect.php';
?>
<div id="center">
<?php
// Rest of your code
// ...
if ($result2)
{
$_SESSION['player'] = $player;
// and so on...
Also, as #DamienLegros noted in his answer, you should always have the session_start() statement as early as possible in your code, i.e. as one of the first statements, so you make sure no output has been made before it's started. Otherwise you'll start getting errors stating that headers has already been sent.
Your session_start() must be BEFORE any output
<?php
session_start();
include_once 'connect.php';
?>
<link href="stilark.css" rel="stylesheet" type="css" />
<?php
session_start();
include_once 'connect.php';
?>
<div id="center">
<?php
if (isset($_POST['submit']))
...
...
...
note: add session_start(); at the top of your Authenticate.php page

Nothing happens after I submit the form

So I am building a simple question form that allows a user to submit a question and once the question is submitted it is sent to the database. I can't figure out why it isn't working. Here is my code, first one is the ask.html and the second is the ask.php.
<form action="ask.php" method="POST">
Name: (not your real name)<br/>
<input type="text" name="name" id="name"/>
<br/>
<br/>
Question: <br/>
<textarea name="question" cols="60" rows="10" id="question">
</textarea>
<br/>
<input type="submit" />
</form>
<?php
include('config.php');
include('open_connection.php');
if ((!$_POST[name]) || (!$_POST[question]))
{
header ("Location: ask.html");
exit;
}
//Select database and table
$db_name = "questionme";
$table_name = "questions";
//Insert data into database
$sql = "INSERT INTO $table_name
(name, question) VALUES
('$_POST[name]', '$_POST[question]')";
$result = #mysql_query($sql, $connection) or die(mysql_error());
?>
<html>
<head>
<title>Ask</title>
<head>
<body>
<h1>Question Submitted</h1>
<p><strong>Name:</strong>
<?php echo "$_POST[name]"; ?></p>
<p><strong>Question:</strong>
<?php echo "$_POST[question]"; ?></p>
</body>
</html>
The following is certainly generating warnings:
if ((!$_POST[name]) || (!$_POST[question]))
replace with
if (!isset($_POST[name]) || !isset($_POST[question]))
then absolutely take into consideration what the other dudes answered. On your INSERT:
('$_POST[name]', '$_POST[question]')";
would be better off as (they're also triggering warnings):
('{$_POST['name']}', '{$_POST['question']}')";
And on these
<?php echo "$_POST[name]"; ?></p>
...
<?php echo "$_POST[question]"; ?></p>
have them as
<?php echo $_POST['name']; ?></p>
...
<?php echo $_POST['question']; ?></p>
Check your post variables with isset() and use quotes for the hashes you're checking:
if (!isset($_POST['name']) || !isset($_POST['question']))
Also, never insert the values of your $_POST variables directly - do something like this instead:
$name = mysql_real_escape_string($_POST['name']);
$question = mysql_real_escape_string($_POST['question']);
Have you show_errors PHP configuration enabled?
Try placing some lines like
echo "[1]";
echo "[2]";
etc to discover where your script terminates (debug a bit);
AND NEVER, NEVER USE _POST and _GET variables in SQL queries directly (use mysql_real_escape_string to escape their values)... or your script will be vulnerable to SQL injection attacks!!!
if you are using tables like $_POST['name'] in a string you have to wrap them with a {}
$sql = "INSERT INTO $table_name
(name, question) VALUES
('{$_POST[name]}', '{$_POST[question]}')";
<?php echo "{$_POST[name]}"; ?>
also

How to redirect to another page using PHP [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 months ago.
I'm building a website which includes a login page. I need to redirect the user to their profile page once they've logged in successfully, but I don't know how to do that in PHP (It's my first site).
I've searched the internet and have been told that the header() function should do the trick, but it will only work if I haven't outputted any information before using it.
That's the problem. I've outputted a bunch of information (Including the HTML to build the login page itself).
So how do I redirect the user from one page to the next?
What options do I have? Also, what is the best practice in these instances?
EDIT: Here's my entire login.php page:
<?php
session_start();
echo "<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Sprout</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'>
</head>
<body>
<div class='box'>
<form action='login.php' method='post'>
Name<br /> <input type='text' name='username' class='form'/><br />
Password<br /> <input type='password' name='password' class='form'/>
<input type='submit' value='Login' class='button' />
</form>
</div>
</body>
</html>";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = $_POST["username"];
$password = $_POST["password"];
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to database");
$dbname = "database";
mysql_select_db($dbname);
$query = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($query) or die ("Failed Query of " . $query);
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
}
?>
You could use a function similar to:
function redirect($url) {
header('Location: '.$url);
die();
}
Worth noting, you should them with a die() or exit() function to prevent further code execution.
Note that it just makes no sense to output large chunks of HTML if you are going to redirect. Therefore you have to move the form handling code above all HTML. As a side effect it will mitigate the notorious "Headers already sent" error.
Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/
This guide includes reasons for using die() / exit() functions in your redirects, as well as when to use ob_flush() vs ob_start(), and some potential errors that the others answers have left out at this point.
You can conditionally redirect to some page within a php file....
if (ConditionToRedirect){
//You need to redirect
header("Location: http://www.yourwebsite.com/user.php");
exit();
}
else{
// do something
}
That's the problem. I've outputted a bunch of information (including the HTML to build the login page itself). So how do I redirect the user from one page to the next?
This means your application design is pretty broken. You shouldn't be doing output while your business logic is running. Go an use a template engine (like Smarty) or quickfix it by using output buffering).
Another option (not a good one though!) would be outputting JavaScript to redirect:
<script type="text/javascript">location.href = 'newurl';</script>
header won't work for all
Use below simple code
<?php
echo "<script> location.href='new_url'; </script>";
exit;
?>
Assuming you're using cookies for login, just call it after your setcookie call -- after all, you must be calling that one before any output too.
Anyway in general you could check for the presence of your form's submit button name at the beginning of the script, do your logic, and then output stuff:
if(isset($_POST['mySubmit'])) {
// the form was submitted
// ...
// perform your logic
// redirect if login was successful
header('Location: /somewhere');
}
// output your stuff here
You could use ob_start(); before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.
Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML.
The simplest approach is that your script validates the form-posted login data "on top" of the script before any output.
If the login is valid you'll redirect using the "header" function.
Even if you use "ob_start()" it sometimes happens that you miss a single whitespace which results in output. But you will see a statement in your error logs then.
<?php
ob_start();
if (FORMPOST) {
if (POSTED_DATA_VALID) {
header("Location: https://www.yoursite.com/profile/");
ob_end_flush();
exit;
}
}
/** YOUR LOGINBOX OUTPUT, ERROR MESSAGES ... **/
ob_end_flush();
?>
firstly create index.php page and just copy paste below code :-
<form name="frmUser" class="well login-form" id="form" method="post" action="login_check.php" onSubmit="return FormValidation()">
<legend>
<icon class="icon-circles"></icon>Restricted Area<icon class="icon-circles-reverse"></icon>
</legend>
<div class="control-group">
<label class="control-label" for="inputPassword">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-user icon-cream"></icon> </span>
<input class="input" type="text" name="username" id="username" placeholder="Username" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-password icon-cream"></icon>
</span> <input class="input" type="password" name="password" id="password" value="" placeholder="Password" />
</div>
</div>
</div>
<div class="control-group signin">
<div class="controls ">
<input type="submit" class="btn btn-block" value="Submit" />
<div class="clearfix">
<span class="icon-forgot"></span>forgot password
</div>
</div>
</div>
</form>
/*------------------after that ----------------------*/
create a login_check.php and just copy paste this below code :-
<?php
session_start();
include('conn.php');
<?php
/* Redirect browser */
header("location:index.php");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
<?php
if(count($_POST)>0)
{
$result = mysql_query("SELECT * FROM admin WHERE username='".$_POST["username"]."' and password = '".$_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["user_id"] = $row[user_id];
$_SESSION["username"] = $row[username];
$session_register["user_id"] = $row[user_id];
$session_register["username"] = $row[username];
}
else
{
$_SESSION['msg']="Invalid Username or Password";
header("location:index.php");
}
}
if(isset($_SESSION["user_id"]))
{
header("Location:dashboard.php");
}
?>
/*-----------------------after that ----------------------*/
create a dashboard.php and copy paste this code in starting of dashboard.php
<?php
session_start();
include('conn.php');
include('check_session.php');
?>
/*-----------------------after that-----------------*/
create a check_session.php which check your session and copy paste this code :-
<?php
if($_SESSION["user_name"])
{
?>
Welcome <?php echo $_SESSION["user_name"]; ?>. Click here to Logout.
<?php
}
else
{
header("location:index.php");
}
?>
if you have any query so let me know on my mail id farjicompany#gmail.com
Although not secure, (no offense or anything), just stick the header function after you set the session variable
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
header('Location: /profile.php');
On click BUTTON action
if(isset($_POST['save_btn']))
{
//write some of your code here, if necessary
echo'<script> window.location="B.php"; </script> ';
}
----------
<?php
echo '<div style="text-align:center;padding-top:200px;">Go New Page</div>';
$gourl='http://stackoverflow.com';
echo '<META HTTP-EQUIV="Refresh" Content="2; URL='.$gourl.'">';
exit;
?>
----------
Just like you used echo to print a webpage. You could use also do the same with redirecting.
print("<script type=\"text/javascript\">location.href=\"urlHere\"</script>")
<?php
include("config.php");
$id=$_GET['id'];
include("config.php");
if($insert = mysqli_query($con,"update consumer_closeconnection set close_status='Pending' where id="$id" "))
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
else
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
?>

Categories