I am trying to echo an HTML form within PHP but I just can't get it done.
It just echo pre-formatted HTML. I ain't getting the form.
Here is my PHP script
do-reset.php
<?php
require_once 'connect.php';
session_start();
if($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['hash']) && !empty($_GET['hash'])) {
$email = htmlentities(mysqli_real_escape_string($connection, trim($_GET['email'])));
$hash = htmlentities(mysqli_real_escape_string($connection, trim($_GET['hash'])));
$search_query = "SELECT email, hash, status FROM users WHERE email = '{$email}' AND forgot_password_hash = '{$hash}' AND
status = '1'";
$do_search_query = mysqli_query($connection, $search_query);
if($do_search_query) {
$count_rows = mysqli_num_rows($do_search_query);
if($count_rows > 0) {
$_SESSION['email'] = $email;
$_SESSION['hash'] = $hash;
echo "<form method='post' action='do-reset.php'><input type='password' name='password'><br><input type='submit' value='Reset My Password'></form>";
}
else {
$data = array("result" => -3, "message" => "Invalid URL");
}
}
else {
$data = array("result" => -2, "message" => "Something Went Wrong! Try Again Later.");
}
}
else
{
$data = array("result" => -1, "message" => "Certain Request Parameters Are Missing!");
}
}
else {
$data = array("result" => 0, "message" => "Incorrect Request Method!");
}
mysqli_close($connection);
/* JSON Response */
header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
?>
1.: Remove the header('Content-type: application/json');
This will basically tell the browser to display the output as text.
2.:
to preserve formatting, you can use <pre>-tags:
echo "<pre>";
echo json_encode($data, JSON_PRETTY_PRINT);`
echo "</pre>";
Different approach:
only set content type to application/json when the $data-array is filled
if(!empty($data)){
header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
}
I found a way out! $type_json did the trick for me.
<?php
require_once 'connect.php';
session_start();
$type_json = true;
if($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['hash']) && !empty($_GET['hash'])) {
$email = htmlentities(mysqli_real_escape_string($connection, trim($_GET['email'])));
$hash = htmlentities(mysqli_real_escape_string($connection, trim($_GET['hash'])));
$search_query = "SELECT email, hash, status FROM users WHERE email = '{$email}' AND forgot_password_hash = '{$hash}' AND
status = '1'";
$do_search_query = mysqli_query($connection, $search_query);
if($do_search_query) {
$count_rows = mysqli_num_rows($do_search_query);
if($count_rows > 0) {
$_SESSION['email'] = $email;
$_SESSION['hash'] = $hash;
$type_json = false;
echo "<form method='post' action='do-reset.php'><input type='password' name='password'><br><input type='submit' value='Reset My Password'></form>";
}
else {
$data = array("result" => -3, "message" => "Invalid URL");
}
}
else {
$data = array("result" => -2, "message" => "Something Went Wrong! Try Again Later.");
}
}
else
{
$data = array("result" => -1, "message" => "Certain Request Parameters Are Missing!");
}
}
else {
$data = array("result" => 0, "message" => "Incorrect Request Method!");
}
mysqli_close($connection);
/* JSON Response */
if($type_json) {
header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
}
?>
PHP is executed on the server side and is treated as a script instead of a markup language, meaning the HTML on the requested page doesnt matter to the server at all it only cares about the PHP. so if you did
<?php
if(true) {
?>
<form>Hello</form>
<?php
}
?>
the html form will only be displayed with the text hello if the statement is true, which true always is true ofcourse. you could replace this with any statement, for example to check if someone hes entered something in a field from the form they submitted.
hope this helps!
Related
i wrote this script to sign in the user in PHP in order to save the data to the server, if the user has been created the scrip should return a simple json with true or false.
<?php
require "../private/autoload.php";
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
print_r($_POST);
$Error = "";
$staff = $_POST['staff_ID'];
$email = $_POST['email'];
$pass = $_POST['password'];
$name = $_POST['Name'];
$cpt = $_POST['isCPT'];
$date = date("Y-m-d H:i:s",time()); // date of creation
// check if user alrady exixt
$sqlexixst = "SELECT * FROM `users` WHERE staff_ID = ?";
$st = $pdo->prepare($sqlexixst);
$st->execute(array($staff));
$result = $st->fetchAll();
if (count($result) > 0){
$array = array(
"user_created"=>false
);
$js = json_encode($array);
echo $js;
} else {
// user not exixt creo utente
$regex = '/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex,$email)){
// ok email
if (is_numeric($staff)){
// ok id
$sql = "INSERT INTO users (staff_ID,password,email,isCPT,Name, date) VALUES (?,?,?,?,?,?)";
$statement = $pdo->prepare($sql);
$statement ->execute([$staff,$pass,$email,$cpt,$name,$date]);
$array = array(
"user_created"=>true,
"staff_ID"=>$staff
);
$js = json_encode($array);
echo $js;
}
}else{
$Error = "pls enter valid email";
echo $Error;
}
}
}else {
echo 'no post';
}
?>
i'm sending the request using Alamofire... if i post the request using respondeString i can see the corret print out of the json, if i use respondJSON i cant get the json print out.. i get error say 'JSON could not be serialized. thata could not be read because it isn't in the correct format'
Alamofire and swiftyjson code:
func nxTest (){
let parm : [String : Any] = ["staff_ID": "3879","password":"12345678","email":"damiano.miai#gmail.com", "isCPT":false,"Name":"Marco Frizzi"]
AF.request("http://192.168.50.10/nx/public/register.php", method: .post, parameters: parm,headers: nil, interceptor: nil, requestModifier: nil).validate()
.responseJSON { js in
switch js.result {
case .success(let value) :
let json = JSON(value)
debugPrint(json)
case .failure(let err) :
debugPrint(err.localizedDescription)
}
}
.responseString { st in
print(st)
}
}
I have a form which when submitted made request to the server through ajax using php curl. Everything worked perfectly in my local environment(wamp) but when I moved it to live server, it doesn't return any json response.
I can't figure out why it worked in wampserver but not on live server?
php code
<?php
if(isset($_POST['logins']))
{
require_once 'functions.php';
require_once("cons.php");
$licence = $_POST['licence'];
$url = "http://tapi.com/apis/User/api.php?licence=".$licence;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$data = json_decode($response, true);
$msg = $data['message'];
$lic = $data['licence'];
$p = $data['period'];
$u = $data['user'];
$sta = $data['status'];
if($msg == 'Successfully Validated!')
{
//$_SESSION['data'] = array($data, true);
$url = "http://tapi.com/apis/User/api.php?lic=".$lic;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$data = json_decode($response, true);
$msg = $data['message'];
if($msg == 'inserted')
{
$host = $_SERVER['HTTP_HOST'];
$hostaddrs = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$sys_info = php_uname();
$exp_date = encryptIt2($p);
$date = date('Y-m-d');
$ts = encryptIt2($date);
$queryu = "insert into tray(host, license, validity, et)values('$host', '$lic', '$exp_date', '$ts')";
$get = mysqli_query($mysqli,$queryu);
if($get){
echo "yes";
}else{
echo $mysqli -> error;
}
}else{
echo $msg;
}
}
else
{
echo $data['message'];
}
}
?>
jQuery code
function licenceForm()
{
var data = $("#licence-form").serialize();
$.ajax({
type : 'POST',
url : 'ext/b0a012.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-login").html('<img src="assets/img/find.png"
width="26" height="25"> Please wait...');
},
success : function(response)
{
if(response=="yes"){
$(".hideit").hide();
$(".shows").show();
setTimeout('window.location.href = "index.php"; ',2000);
}else{
$("#error").fadeIn(1000,function(){
$("#error").html('<div class="alert alert-danger text center">
<img src="assets/img/attention.png" width="45" height="40" />
<br/> '+response+'</div>');
$("#btn-login").html('Error occured. Try again.');
});
}
}
});
return false;
}
API
if (isset($_GET['licence']) && $_GET['licence']!="") {
$licence = $con->real_escape_string($_GET['licence']);
//$licence = "M7RS-8C46-APSE";
$selec = mysqli_query($con, "SELECT licence, period, users FROM licence_used WHERE licence='$licence'");
$mrow = mysqli_fetch_array($selec);
$count = mysqli_num_rows($selec);
if($count > 0){
$q2 = mysqli_query($con,"select count(licence) use_count FROM licence_used WHERE licence='$licence'");
$get = mysqli_fetch_array($q2);
//query 2
$selec = mysqli_query($con, "SELECT licence,
period, users FROM licence_used WHERE licence='$licence'");
$users = $mrow['users'];
$num = $get['use_count'];
if($num == $users){
$user_arr=array(
"status" => false,
"message" => "Licence key entered has been used up by ".$num." users. Please purchase another licence.",
);
}else{
while($row = mysqli_fetch_array($selec)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"licence" => $mrow['licence'],
"period" => $mrow['period'],
"user" => $mrow['users'],
"mstatus" => $mrow['status']
);
}
}
}else{
$select = mysqli_query($con, "SELECT licence, period, users FROM licence WHERE licence='$licence'");
if(mysqli_num_rows($select) == 0){
$user_arr=array(
"status" => false,
"message" => "Invalid Licence Key Entered. Please contact the software company.",
);
}else{
while($row = mysqli_fetch_array($select)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"licence" => $row['licence'],
"period" => $row['period'],
"user" => $row['users'],
"mstatus" => $row['status']
);
}
}
}
}
header("Content-Type:application/json");
print_r(json_encode($user_arr));
I used postman to test it and it worked. Do anyone know what the issue might be? Thanks.
I have a code in PHP where a field value entered should match with the values in a table in a database. If match found it must do some work, or else it must say "match was not found".
But whenever I check with values which are not in the table (database), it says "match has been found".
Here is the code:
<?php
include"conn.php";
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
// Vehicle Number
$vehicle_number = isset($_POST['VehicleNumber']) ?mysql_real_escape_string($_POST['VehicleNumber']) : "";
//ID card Nos.
$idcardno1= isset($_POST['idno1']) ? mysql_real_escape_string($_POST['idno1']) : "";
$idcardno2= isset($_POST['idno2']) ? mysql_real_escape_string($_POST['idno2']) : "";
//Text Messages
$Textmsg = isset($_POST['yourtext']) ? mysql_real_escape_string($_POST['yourtext']) : "";
if($idcardno1 == NULL )
{
//echo "Blank Fields";
$json = array("status" => "Failure", "msg" => "User has entered one or more than one null values so couldn't go for database operations");
}
else
{
$q=mysql_query("SELECT * FROM profile WHERE IDcardno1 ='$idcardno1' OR IDcardno2 = '$idcardno2' OR VehicleNumber ='$vehicle_number'" )or die(mysql_error());
if($q)
{
$num=mysql_num_rows($q);
if($num==0)
{
$json = array("status" => "Failure", "msg" => "Information not found");
print $num;
}
else{
$json = array("status" => "success", "msg" => "Information is stored and match has been found");
}
}
}
}
else{
$json = array("status" => "Failure", "msg" => "POST_Request method not accepted");
}
mysql_close($con);
/* Output header */
//header('Content-Type: application/json');
echo json_encode($json);
?>
Because you are using OR in your SQL query, it will return any database rows where there is an empty database value and empty form value. This may return rows where you were not expecting them (depending on your intention)
If that's the case, you may want to ONLY match on field values that are actually populated by changing the query to something like this:
$q = mysql_query("SELECT * FROM profile WHERE (IDcardno1 ='$idcardno1' AND '$idcardno1' <> '') OR (IDcardno2 = '$idcardno2' AND '$idcardno2' <> '') OR (VehicleNumber ='$vehicle_number' AND '$vehicle_number' <> '')" )or die(mysql_error());
(This is just one way to approach it)
Okay so I'm looping through the results that contains two question IDs and two answers and I'm trying to match the two answers with the two answers from the form submission.
I'm not sure what I'm doing wrong.
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if (($answer == $answer1Post) && ($answer == $answer2Post)) {
} else {
$errors = true;
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => $errors, 'message' => $message);
}
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Since your question is not clear in the first place, so I'm assuming that the question you are asking is "why you're not getting any matching results, when you've the correct answers in the database?". Please correct me, if this is wrong.
The logic can be like this:-
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
// Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc, $_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc, $_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc, $_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc, $_POST['question1']);
$question2 = mysqli_real_escape_string($dbc, $_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc, $query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answer1Post) {
// The first answer is correct
$errors = false;
$message = "Your first answer is correct!";
} else if ($answer == $answer2Post) {
// The second answer is correct
$errors = false;
$message = "Your second answer is correct!";
} else {
$errors = true;
$message = "Your answers did not match the answers inside the
}
$output = array('errorsExist' => $errors, 'message' => $message);
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
// Output the result
$output = json_encode($output);
echo $output;
?>
It's better to have more segregation of logical conditions. In this case, it's your two answers to check for.
Hope it helps.
What I'm trying to figure out here is how to access the different array values that I need. I have the following query and it returns this for an array when the print_r() is applied. For some reason it only does the first row from the db table. It should return a whole another row.
<?php
session_start();
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = "no";
if((empty($_POST['answer1'])) || (trim($_POST['answer1'])=="") || ($_POST['answer1'] == NULL) || (!isset($_POST['answer1']))){$errors = "yes";}
if((empty($_POST['answer2'])) || (trim($_POST['answer2'])=="") || ($_POST['answer2'] == NULL) || (!isset($_POST['answer2']))){$errors = "yes";}
// Error checking, make sure all form fields have input
if ($errors == "yes") {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answerPost) {
} else {
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
} else {
$errors = "yes";
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Because you just fetch the first one, where you should loop on the result set instead:
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '$userID'";
$result = mysqli_query($dbc,$query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
print_r($row);
}
}
By the way, you should be using prepared statements to avoid SQL injection.
You need to wrap your fetch in a loop. e.g.
if (mysqli_num_rows($result) > 0)
{
while (($row = mysqli_fetch_array($result)) !== false)
{
if ($row['answer'] == $answerPost)
{
// $row matches what we're looking for
}
else
{
$errors = "yes";
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => true, 'message' => $message);
}
print_r($row);
}
}