PHP code is showing in the webpage while executing - php

i am new to php I am trying to write a registration page.But something goes wrong.Every time i try to execute the code i get something like this in my page
Database details
Db name: cibil,
table name: table {id,username,password,email
}
query($sql)===true) { $_SESSION['message']='You are successfully added';
$_SESSION['username']=$user; $_SESSION['email']=$email;
header(location:page.php); } else{ $_SESSION['message']='Something went wrong'; } } ?>
My code is
<? php
session_start()
$_SESSION['message']='';
if($_SERVER['REQUEST_METHOD']=='POST')
{
$conn=new mysqli('localhost','root','','cibil') or die("error");
$user=$_POST['user'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$sql="INSERT INFO table (username, password,email)VALUES('$user','$pass','$email')";
if($conn->query($sql)===true)
{
$_SESSION['message']='You are successfully added';
$_SESSION['username']=$user;
$_SESSION['email']=$email;
header(location:page.php);
}
else{
$_SESSION['message']='Something went wrong';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register form</title>
<link rel="stylesheet" type="text/css" href="reg_style.css">
</head>
<body>
<div id="h1">
<h1>Registration Page</h1>
</div>
<div id="err"><? php echo $_SESSION['message'] ?></div>
<div id='form'>
<form method="post" name='form' onsubmit="return rvalidate()" action="">
<p class="error">*Required</p>
<label for="user">Enter Your Name* : </label>
<input id="user" type="text" name="user" class="field">
<span class='error'></span><br><br>
<label for="email">Enter Your Email : </label>
<input id="email" type="text" name="email" class="field">
<br><br>
<label for="pass">Enter Your Password* : </label>
<input type="password" id="pass" name="pass" class="field"><span class='error'></span><br><br>
<label for="rpass">Re-Enter Your Password* : </label>
<input type="password" id="rpass" name="rpass" class="field"><span class='error'></span><br><br>
<input type="submit" id='submit' class="field" value="SUBMIT" onclick="validate();" >
</form>
</div>
<br><br>
<div id="login_text">
<b>If you are already register </b><br>Click here
</div>
<script type="text/javascript">
var error=document.getElementsByTagName('span');
var user=document.form.user;
var pass=document.form.pass;
var rpass=document.form.rpass;
function validate()
{
if(user.value==="")
{
error[0].innerHTML="*Enter Your name";
user.setAttribute("style","border-color:green");
}else{
error[0].innerHTML="";
user.setAttribute("style","border-color:initial");
}
if(pass.value=="")
{
error[1].innerHTML="*Password is Required";
pass.setAttribute("style","border-color:green");
}else{
error[1].innerHTML="";
pass.setAttribute("style","border-color:initial");
}
if(pass.value!==rpass.value)
{
error[2].innerHTML="*Password Missmatch";
rpass.setAttribute("style","border-color:green");
}else{
error[2].innerHTML="";
rpass.setAttribute("style","border-color:initial");
}
}
function rvalidate()
{
if (error[0].innerHTML=="" && error[1].innerHTML=="" && error[2].innerHTML=="") {
return true;
}
else{
return false;
}
}
</script>
</body>
</html>
Thank you for your help.........

Your code is not executed and shown as text because you have a space between ? and php at the start of the code. Try to start with <?php
session_start();. Then you will be able to debug all the rest :)

<div id="err"><? php echo $_SESSION['message']
If you notice there is a space between the ? And PHP, that may affect what is bring output. There is a few areas where your quotes don't match so if you check if the quotes aren't closing each other in places they shouldn't be closed then you should be okay
Is your filename correct? If it is a .htm or .html file it may not parse the PHP which could also be another issue you're having

You have a space at the opening of your php code :
<? php
should be :
<?php

Your code:
$sql="INSERT INFO table (username, password,email)VALUES('$user','$pass','$email')";
Must be without `...`:
$sql="INSERT INFO table (username, password,email)VALUES($user, $pass, $email)";

Related

Redirect page and edit something in another file

i have a little problem
I have a form in login.php:
`
<form action="loginscript.php" method="post">
<h2>Login form</h2>
<label for="nick">Podaj imie: </label>
<input type="text" name="nick" id="nick">
<br>
<label for="pass">Podaj haslo: </label>
<input type="password" name="pass" id="pass">
<br>
<p>LOG IN</p>
<input type="submit" name="submit" id="submit">
</form>
`
and i have a loginscript.php file:
`
<?php
session_start();
if (isset($_POST["nick"]) && isset($_POST["pass"])) {
$nick=$_POST["nick"];
$pass=sha1(sha1($_POST["pass"]));
$conn = mysqli_connect("localhost", "root", "", "baza2");
if ($conn) {
$query = mysqli_query($conn, "SELECT * FROM login_table WHERE nick='$nick' AND pass='$pass'");
if (mysqli_num_rows($query)) {
$_SESSION["logged"]=true;
header("Location: main.php");
} else {
header('Location: login.php');
}
mysqli_close($conn);
}
}
?>
`
In the loginscript.php in else i have redirect to login.php page. How can i change maybe p tag from 'LOG IN' to 'USERNAME OR PASSWORD IS WRONG'?
I tried using jquery but that doesn't work, maybe I don't know how. Please help :(
You can't change anything on the target page from there, but what you can do is provide some information to the target page which that page can use. For example, consider this redirect:
header('Location: login.php?failed=true');
Then in the login.php code you can check for the "failed" query string value and conditionally change the output based on that. For example:
<?php
$message = isset($_GET['failed']) ? "USERNAME OR PASSWORD IS WRONG" : "LOG IN";
?>
<form action="loginscript.php" method="post">
<h2>Login form</h2>
<label for="nick">Podaj imie: </label>
<input type="text" name="nick" id="nick">
<br>
<label for="pass">Podaj haslo: </label>
<input type="password" name="pass" id="pass">
<br>
<p><?= $message ?></p>
<input type="submit" name="submit" id="submit">
</form>
you could try the code below.
if (mysqli_num_rows($query)) {
$_SESSION["logged"]=true;
echo "<script type='text/javascript'> document.location = 'main.php';</script>";
} else {
echo "<script>alert('Your Password or username is wrong!');</script>";
}

Unable to call PHP function in HTML file, tried using the same code in different code its working fine but not here

When I press the Login button it refreshes the page and doesn't do anything. I tried entering wrong Server IP just to check the error, but I guess it's not responding to the login button and directly refreshing the page.
Unable to call a PHP function in the HTML file, tried using the same code in a different code and it's working fine there but not here:
<title> Database Login </title>
<body>
</head>
<body>
<span>
<div class="heading">
<h3><img src="http://zicom.com/img/ilayashop-1482233381.jpg" alt="Zicom Logo" >
<h1><b>MAaaS Login<b></h1><br>
</span>
</div>
<div class='admin'>
<form method='post' action=''>
<p class='main'> Enter your Details </p>
<p> Enter User Name <input type="text" name="name" id="userInput"></p>
<p> Enter password <input type="password" name="pass" id="userInput"> </p>
<br>
<input id="login" type="submit" name="submit" value="Login">
</form>
</div>
<?php
if($_POST){
$UN = $_POST['name'];
$PS = $_POST['pass'];
$scon=odbc_connect("Driver={SQL Server};Server=XXXXXXX; Database=Sampledata;","XX","XXXXX");
$query="SELECT [password] FROM [Simcarddata].[dbo].[MasterUser] Where username='$UN'";
$rs=odbc_exec($scon,$query);
if (!$rs)
{
$msg="SQL statement failed with error:\n";
$msg.=odbc_error($scon).": ".odbc_errormsg($scon)."\n";
} else {
$number_of_rows = odbc_num_rows($rs);
$msg="$number_of_rows records found.\n";
}
while(odbc_fetch_row($rs))
{
$field1 = odbc_result($rs,1);
// print ("$PS and $field1");
if ($PS == $field1){
print ("TRUE");
header("Location: /test.php");
}
else {
print ("Incorrect Username or password");
}
}
odbc_close($scon);
header("Refresh:2");
}
?>
</body>
</html>
I just tidied up the HTML tags a little and used a better method of checking for POST data - but I think the issue was the badly formed HTML was confusing the form
<html>
</head>
<title> Database Login </title>
</head>
<body>
<span>
<div class="heading">
<h3><img src="http://zicom.com/img/ilayashop-1482233381.jpg" alt="Zicom Logo" ></h3>
<h1><b>MAaaS Login<b></h1>
<br>
</div>
</span>
<div class='admin'>
<form method='post'>
<p class='main'> Enter your Details </p>
<p>Enter User Name <input type="text" name="name" id="userInput"></p>
<p>Enter password <input type="password" name="pass" id="userInput"></p>
<br>
<input id="login" type="submit" name="submit" value="Login">
</form>
</div>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['name'], $_POST['pass'] ) ){
$UN = $_POST['name'];
$PS = $_POST['pass'];
$scon=odbc_connect("Driver={SQL Server};Server=XXXXXXX;Database=Sampledata;","XX","XXXXX");
$query="SELECT [password] FROM [Simcarddata].[dbo].[MasterUser] Where username='$UN'";
$rs=odbc_exec( $scon, $query );
if (!$rs) {
$msg="SQL statement failed with error:\n";
$msg.=odbc_error($scon).": ".odbc_errormsg($scon)."\n";
} else {
$number_of_rows = odbc_num_rows($rs);
$msg="$number_of_rows records found.\n";
}
while( odbc_fetch_row( $rs ) ) {
$field1 = odbc_result($rs,1);
if ($PS == $field1){
print ("TRUE");
header("Location: /test.php");
} else {
print ("Incorrect Username or password");
}
}
odbc_close($scon);
header("Refresh:2");
}
?>
</body>
</html>
if ($_SERVER['REQUEST_METHOD'] === 'POST') use this please instead of if($_POST) or use if(isset($_POST))

PHP to MYSQL form validation and database insertion with PHP_SELF and php process

I'm trying to use a php form saved on the artistRegister.php below and process it with the file at the bottom named processArtist.php .
I can't find the proper way to populate the fields in case there's an error and when I submit it to the database, I get an empty record on the database.
I'm populating a dropdown list on the navigation bar at header.php and using the same code to connect to the database, so it's not a database communication problem, since I'm able to create new empty records on the submit button press.
Tried several ways to make it work but would appreciate any help debugging the problem at hand.
Thank you advance.
***artistRegister.php***
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
//define page title
$title = 'Members Page';
//include header template
require('layout/header.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php if(isset($title)){ echo $title; }?></title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div class="container-fluid">
<div class="col-xs-3">
</div>
<div class="col-xs-6">
<?php
// define variables and initialize with empty values
$artistName = $artistLabel = $websiteAddress = $facebookAddress = $youtubeAddress ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["artistName"])) {
$nameErr = "Enter Artist name";
}
else {
$artistName = $_POST["artistName"];
}
if (empty($_POST["artistLabel"])) {
$labelErr = "Enter Label name";
}
else {
$artistLabel = $_POST["artistLabel"];
}
}
?>
<form class="form" method="POST" action="processArtist.php">
<div class="form-group">
<label for="artistName">Artist Name:</label>
<input type="text" class="form-control" id="artistName" value="<?php echo htmlspecialchars($artistName);?>">
<span class="error" style="color: red"><?php echo $nameErr;?></span><br>
<label for="artistLabel">Artist Label:</label>
<input type="text" class="form-control" id="artistLabel" value="<?php echo htmlspecialchars($artistLabel);?>">
<span class="error"><?php echo $LabelErr;?></span><br>
<label for="websiteAddress">Artist Website:</label>
<input type="text" class="form-control" id="websiteAddress" value="<?php echo htmlspecialchars($websiteAddress);?>">
<label for="facebookAddress">Artist Facebook:</label>
<input type="text" class="form-control" id="facebookAddress" value="<?php echo htmlspecialchars($facebookAddress);?>">
<label for="youtubeAddress">Artist Youtube:</label>
<input type="text" class="form-control" id="youtubeAddress" value="<?php echo htmlspecialchars($youtubeAddress);?>">
<br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
<div class="col-xs-3">
</div>
</div>
</body>
***processArtist.php***
<?php
$host="localhost";
$username="some_user_with_access";
$password="the_user_password";
$db_name="artist_management";
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump($_POST);
$artistName=$_POST['artistName'];
$artistLabel=$_POST['artistLabel'];
$websiteAddress=$_POST['websiteAddress'];
$facebookAddress=$_POST['facebookAddress'];
$youtubeAddress=$_POST['youtubeAddress'];
$sql="INSERT INTO artists (artistName, artistLabel, websiteAddress, facebookAddress, youtubeAddress)
VALUES
('$artistName', '$artistLabel', '$websiteAddress', '$facebookAddress', '$youtubeAddress')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);

error with fill in a mysql table via php

I tried to make a code which will add an entry to my MySQL table (called "rechnungen") via php. So I made some inputs in html and finaly I tried to insert the informations into my table (using the INSERT INTO... command). So this is what i made:
<?php
Session_Start();
$username=$_SESSION['username'];
$password=$_SESSION['password'];
$dbname=$_SESSION['dbname'];
$servername=$_SESSION['hostname'];
/*conn dev*/
$conn = mysql_connect($servername, $username, $password);
if($conn === false){
header("Location: LogIn.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title></title>
</head>
<body>
<main>
<form method="POST" action="">
<div class="form_neueRechnung">
<!-- part 1 -->
<input type="text" name="suche_Vname_Patienten" placeholder="Vorname" required="">
<input type="text" name="suche_Nname_Patienten" placeholder="Nachname" required="">
<input type="number" id="id_Patient" name="id_patient" placeholder="Pat. Nr." Value="
<?php echo $KID_output; ?>" required="">
</td>
<input type="radio" name="Behandlung" value="Osteopathie" onclick="andere()" required="">
<input type="radio" name="Behandlung" value="Krankengymnastik" onclick="andere()" required="">
<input type="radio" name="Behandlung" id="andere_Behandlung" value="andere" onclick="andere()" required="">
<input type="text" name="andereBehandlung_text" id="andereBehandlung_text" placeholder="andere" style="visibility:hidden">
<!-- part 2 -->
<input type="radio" name="rezept_rechnung" id="mit_rezept" value="mit_Rezept" onclick="rezept()" required="">
<input type="radio" name="rezept_rechnung" id="ohne_rezept" value="ohne_Rezept" onclick="rezept()" required="">
<input type="text" id="ohne_rezept_text" name="ohne_rezept_text" placeholder="freier Text">
<!-- part 3 -->
<input type="time" name="termin1_von" required="">
<input type="time" name="termin1_bis" required="">
<input type="date" name="termin1_date" required="">
<!-- submit -->
<input type="submit" class="submit" value="Rechnug erstellen" name="submit" id="submit">
</div>
<div class="form_fieldset" id="rezept_einstellungen" style="visibility:hidden">
<input type="date" id="rezept_datum" name="rezept_datum">
<input type="text" id="rezept_verordnung" name="rezept_verordnung">
<input type="text" id="rezept_diagnose" name="rezept_diagnose">
</div>
</form>
<script type="text/javascript">
function andere() {
if (document.getElementById('andere_Behandlung').checked) {
document.getElementById('andere_BehandlungArt').style.visibility = 'visible';
} else {
document.getElementById('andere_BehandlungArt').style.visibility = 'hidden';
}
}
function rezept() {
if (document.getElementById('mit_rezept').checked) {
document.getElementById('rezept_einstellungen').style.visibility = 'visible';
} else {
document.getElementById('rezept_einstellungen').style.visibility = 'hidden';
}
if (document.getElementById('ohne_rezept').checked) {
document.getElementById('ohne_rezept_text').style.visibility = 'visible';
} else {
document.getElementById('ohne_rezept_text').style.visibility = 'hidden';
}
}
</script>
<?php
mysql_connect("$servername","$username","$password") or die("connection failed!");
mysql_select_db($dbname) or die ("no database found");
$query = mysql_query("SELECT * FROM `rechnungen`");
while($row = mysql_fetch_array($query)){
$RID = $row['RechnungsID'];
}
$RechnungsID = max($RID ,$RID)+1;
echo $RechnungsID;
$mit_ohne_Rezept = "";
if(isset($_POST['submit'])) {
if($_POST['rezept_rechnung'] == "mit_Rezept") {
$mit_ohne_Rezept = "1";
}
else {
$mit_ohne_Rezept = "0";
}
}
if(isset($_POST['submit'])){
$KundenID=$_POST['id_patient'];
$Behandlung=$_POST['Behandlung'];
$Rezept_datum=$_POST['rezept_datum'];
$Rezept_Verordnung=$_POST['rezept_verordnung'];
$Rezept_Diagnose=$_POST['rezept_diagnose'];
$ohneRezept_text=$_POST['ohne_rezept_text'];
mysql_select_db($dbname,$conn);
$result = "INSERT INTO rechnungen (`RechnungsID`, `KundenID`, `Behandlung`, `mit_ohne_Rezept`, `Rezept_datum`, `Rezept_Verordnung`, `Rezept_Diagnose`, `ohneRezept_text`)
VALUES ('$RechnungsID','$KundenID','$Behandlung','$mit_ohne_Rezept','$Rezept_datum','$Rezept_Verordnung','$Rezept_Diagnose','$ohneRezept_text)";
if (mysql_query($result)) {
echo ("finished!");
} else {
echo "error". mysql_error();
}
}
mysql_close($conn);
?>
</main>
</body>
</html>
I know it's a pretty long code, but i don't know where the problem could be. I'm getting this error:
errorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''sdfas)' at line 2
please help me. I'm despairing.
','$ohneRezept_text)";
looks like the issue is here.
missing a quotation mark?
that's what the error is saying
also you don't need to wrap variables in quotations, well you can but its still a pain. if your input contains quotation marks it skips right out. Use addslashes()

PHP url Redirect

I've written a PHP script for user login and I validate it using 2 users namely "test" and "admin". When the username and password is matched I redirect the page to UploadFile.php and DownloadFile.php. Though my script validates test and admin users by displaying the echo stmt present in the block, redirect is not working. What mistake have i done or should i follow any other method?
<!DOCTYPE html>
<html lang="en" class="no-js"> <!--<![endif]-->
<head>
<meta charset="UTF-8" />
<title>Login Page</title>
</head>
<body>
<h1>PHP & MySQL File Upload & Download </h1>
<br><br><br>
<form autocomplete="on" method="post">
<h1>Log in</h1>
<p>
<label for="userName" class="uname" data-icon="u" > Your email or username </label>
<input id="userName" name="userName" required="required" type="text" placeholder="myusername or mymail#mail.com"/>
</p>
<p>
<label for="userPass" class="youpasswd" data-icon="p"> Your password </label>
<input id="userPass" name="userPass" required="required" type="password" placeholder="eg. X8df!90EO" />
</p>
<p class="keeplogin">
<input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" />
<label for="loginkeeping">Keep me logged in</label>
</p>
<p class="login button">
<input type="submit" value="Login" id="sign" name="sign"/>
</p>
<p class="change_link">
Not a member yet ?
Join us
</p>
</form>
</body>
</html>
<?php
if (isset($_POST['sign'])) {
$uname = test_input($_POST["userName"]);
$upass = test_input($_POST["userPass"]);
if ((strcmp($uname, "test") == 0) && (strcmp($upass, "test") == 0)) {
header("Location: UploadFile.php");
echo "test user";
} else if ((strcmp($uname, "admin") == 0) && (strcmp($upass, "admin") == 0)) {
header('Location: DownloadFile.php');
echo "admin user";
} else {
echo "<script>
alert('Login Failed');
</script>";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Put the PHP code in front of the HTML code.
Calls to header() have to be placed before outputting anything! You are outputting lots of html before.
See any of these results for further information: https://www.google.de/search?q=headers+already+sent
You can't output headers after starting the body of the response. Try moving your PHP block to before the HTML begins.
On a side note, the fact that PHP isn't telling you this suggests your error reporting isn't verbose enough - you should see a warning similar to the one in this question. Try putting error_reporting(-1); at the top of your code, or changing the setting in php.ini.
Generally speaking, I agree with the usage of header() as a proper redirection mechanism (and, with the exception of the javascript you're injecting, you could move the entire PHP code block above the HTML to get the desired effect)
However, if you'd like to display some content for a short period of time (let's say 2 seconds) before performing the redirect, consider using the "meta-refresh" method, described here:
http://www.w3.org/TR/WCAG20-TECHS/H76
For example, in your current code, try changing:
header("Location: UploadFile.php");
to:
echo "<meta http-equiv=\"refresh\" content=\"2;URL='UploadFile.php'\" />";
Although the W3C page says you should place this element inside the "head" element, practical experience shows that the vast majority of browsers will respect your intentions of showing content then redirecting after the specified time interval.
If you decide to use this "meta" element and move your PHP code to the top of the file, I suggest plugging values in accordingly instead of echoing them immediately:
<?php
$meta_element = '';
$login_message = '';
if (isset($_POST['sign'])) {
$uname = test_input($_POST["userName"]);
$upass = test_input($_POST["userPass"]);
if ((strcmp($uname, "test") == 0) && (strcmp($upass, "test") == 0)) {
$meta_element = "<meta http-equiv=\"refresh\" content=\"2;URL='UploadFile.php'\" />";
$login_message = "test user";
} else if ((strcmp($uname, "admin") == 0) && (strcmp($upass, "admin") == 0)) {
$meta_elementt = "<meta http-equiv=\"refresh\" content=\"2;URL='DownloadFile.php'\" />";
$login_message = "admin user";
} else {
$login_message = "<script>
alert('Login Failed');
</script>";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE html>
<html lang="en" class="no-js"> <!--<![endif]-->
<head>
<meta charset="UTF-8" />
<title>Login Page</title>
<?php echo $meta_element; ?>
</head>
<body>
<h1>PHP & MySQL File Upload & Download </h1>
<br><br><br>
<form autocomplete="on" method="post">
<h1>Log in</h1>
<?php echo $login_message; ?>
<p>
<label for="userName" class="uname" data-icon="u" > Your email or username </label>
<input id="userName" name="userName" required="required" type="text" placeholder="myusername or mymail#mail.com"/>
</p>
<p>
<label for="userPass" class="youpasswd" data-icon="p"> Your password </label>
<input id="userPass" name="userPass" required="required" type="password" placeholder="eg. X8df!90EO" />
</p>
<p class="keeplogin">
<input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" />
<label for="loginkeeping">Keep me logged in</label>
</p>
<p class="login button">
<input type="submit" value="Login" id="sign" name="sign"/>
</p>
<p class="change_link">
Not a member yet ?
Join us
</p>
</form>
</body>
</html>

Categories