PHP POST via JSON is empty - php

I have a basic form that post to PHP file.
<form action="index.php" method="POST">
<input name="operation" id="operation" placeholder="operation" />
<br>
<input id="name" name="name" placeholder="Name" />
<br>
<input id="email" name="email" placeholder="Email"/>
<br>
<input id="password" name="password" placeholder="Password"/>
<br>
<button type="submit" >POST</button>
</form>
problem is the operation is posting NULL or empty via the index file below.
I am using the basic php://input to get encoded via json.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents('php://input'));
if(isset($data -> operation)){
$operation = $data -> operation;
echo $operation;
if(!empty($operation)){
}else{
//$operation is empty ...
}
}else{
//$operation is not set ...
}
}
However echoing the file_get_contents('php://input') displays the correct values from the posted form.
Any reason why the $operation return is always empty?

Your data should be prepared before convert to Json format Try this code :)
I test this Code, it work.
Good Luck
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = file_get_contents('php://input');
$data = str_replace('=','":"',$data);
$data = str_replace('&','","',$data);
$data = '{"'.$data.'"}';
$data = json_decode($data);
if(isset($data->operation)){
$operation = $data -> operation;
echo $operation;
if(!empty($operation)){
echo "NOT EMPTY";
}else{
echo "IS EMPTY";
//$operation is empty ...
}
}else{
echo "NO OPERATION";
//$operation is not set ...
}
}

Related

Can't access upload file input with php

I created a simple form, to create a post, that has three inputs:
One for the title
Description
Image
So, when I submit my form (using post) I call a php file, that "echoes" the value from each input.
It works just fine, but when I try to call the php function $_FILES['my_input_name']['tmp_name'], on my file input, I get an error saying:
Undefined index: my_input_name
My form looks like this (shorter version):
<form action="processForm.php" method="post">
<input type="text" name="title" class="input" required>
<textarea id="description" name="description"required></textarea>
<input type="file" name="fileMedia">
</form>
My php file looks like this
$method = $_SERVER[ 'REQUEST_METHOD' ];
if ( $method=='POST') {
$_args = $_POST;
$_INPUT_METHOD = INPUT_POST;
}
elseif ( $method=='GET' ) {
$_args = $_GET;
$_INPUT_METHOD = INPUT_GET;
}
else {
exit(-1);
}
$title = $_args['title'];
$description = $_args['description'];
$mediaName = $_args['fileMedia'];
$mediatmpPath = $_FILES["fileMedia"]["tmp_name"];
echo $title."<br>";
echo $description."<br>";
echo $mediaName."<br>";
echo $mediatmpPath ."<br>";
I have no idea of what I'm doing wrong, so any helped would be really apreciated!
P.s: My form's is really reduced. In the original one I have row, cols, divs, etc, and some other inputs, which I did not find relevant for this question
You just need to add multipart = "form/data" in form tag
You need to add this below line in <form> tag
<form action="processForm.php" method="post" enctype='multipart/form-data'>
<input type="text" name="title" class="input" required>
<textarea id="description" name="description"required></textarea>
<input type="file" name="fileMedia">
<input type="submit" name="save" value="save">
</form>
And below post data code:
<?php $method = $_SERVER[ 'REQUEST_METHOD' ];
if ( $method=='POST') {
$_args = $_POST;
$_INPUT_METHOD = INPUT_POST;
}
elseif ( $method=='GET' ) {
$_args = $_GET;
$_INPUT_METHOD = INPUT_GET;
}
else {
exit(-1);
}
$title = $_args['title'];
$description = $_args['description'];
$mediaName = $_FILES["fileMedia"]["name"];
$mediatmpPath = $_FILES["fileMedia"]["tmp_name"];
echo $title."<br>";
echo $description."<br>";
echo $mediaName."<br>";
echo $mediatmpPath ."<br>";
?>
I think this help you.

variable and string apparently not matching

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input onclick="this.value=''" type="text" name="first_name" value="First Name">
<input onclick="this.value=''" type="text" name="last_name" value="Last Name">
<input onclick="this.value=''" type="text" name="pwd" value="The Passcode">
<input name="submit" type="submit" value="Submit" class="submit_">
<textarea name="comments" id="comments" rows="4" cols="50"></textarea>
</form>
PHP :
if(isset($_POST['submit']))
{
$name = mysql_real_escape_string($_POST['first_name']);
$pwd = mysql_real_escape_string($_POST['pwd']);
$text = mysql_real_escape_string($_POST['comments']);
// print_r($_POST);
if(is_null($text)) {
debug_to_console('some fields empty');
echo "<p class=\"warning\">* Your Message Did Not Contain Any Characters.</p>";
}
else if($name === 'First Name'){
debug_to_console('name isnt set');
echo "<p class=\"warning\">* You Have Not Entered Your First Name Correctly.</p>";
}
else if($pwd !== 'XyZ'){
debug_to_console('password not set');
echo "<p class=\"warning\">* Passcodes Do Not Match.</p>";
} else {
Keeps returning 'password not set' even though the form input matches the variable. Used print_r and $pwd states XyZ.
tried removing onClick from the form input. I'm assuming this is a caps thing?
Please help, thank you.
Check $pwd with
var_dump($pwd);
I do believe $pwd is a string (because you use !== instead of !=) AND doesn't contain: XyZ
(if you didn't change the value in input field pwd, its value is still: The Passcode)

mysql post missing data from SERVER REQUEST_METHOD

I have the following code, whenever I try to insert the data, the $content is not being inserted, where might the problem be? I am using the function test input for security related issues.
<?php
// define variables and set to empty values
$title = $content = $path = $file_type ="";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$title = test_input($_POST["title"]);
$content = test_input($_POST["content"]);
$path = test_input($_POST["path"]);
$file_type = test_input($_POST["file_type"]);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con=mysqli_connect("localhost","---","---","---");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO articles (ArtID,Title,Content,Image_VideoLink_Path,file_type)
VALUES
('','$title','$content','$path',' $file_type')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "<h2 >Article Published</h2>";
echo"<a href='../mag/index.php'> View it Now </a>";
mysqli_close($con);
?>
here is the code for the form:
<form method="POST" action="artPro.php">
<fieldset>
<legend>Create New Article</legend>
<br/>
Article Title:
<input type="text" placeholder="enter title here" class="span3" name="title" required>
Image/Video Path :
<input type="text" placeholder="enter image name e.g k.jpg or k.mp4 for video" name="path" class="span3" required/>
File Type :
<input type="text" name="file_type" class="span3" required placeholder="e.g: image or video"/>
<br/>
<label>Article Content:</label>
<textarea name="content" rows="20" class="jqte-test span12" required id="txtmsg"></textarea>
<br><button type="submit" class="btn btn-primary btn-large pull-right">Publish</button>
</fieldset>
</form>
Try this query:
$sql="INSERT INTO articles
(Title,Content,Image_VideoLink_Path,file_type) VALUES
('$title','$content','$path',' $file_type')";
$content was not being inserted because you are giving Article ID. And I am sure that Article ID will your primary key and this will auto incremented. So, you did not need to mention Article id in sql query (statement).

PHP - Redisplay forms with valid values in fields and error messages where validation fails

I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

Jquery,AJAX & PHP, form submition not working

Basically i am trying to create a validation for the form. I want it to check if it can connect to the DB and if true to proceed to another page and if false to return an error.
I am inputting the wrong details to make it just display the error but somehow it always returns "TRUE" on page load... and everytime i click the submit it doesnt do anything regardless of my entry...
thx
<script>
$(document).ready(function(){
var u = $('#username');
var s = $('#server');
var p = $('#password');
$('#iValForm').submit(
$.post("connect.php", {u: u.val(),p: p.val(),s: s.val()}, function(fd){
if (fd == "true"){
alert("Is: " + fd);
return false;
} // if1
if (fd == "false"){
alert("Is2: " + fd);
return false;
} // if2
} //post function
) //Post
) //submit
}) //document
</script>
<form class="iValForm" id="iValForm" method="post">
<fieldset>
<legend id="error"> </legend>
<p>
<label for="username">Username </label>
<input id="username" name="username" class="required" /> </input>
</p>
<p>
<label for="password">Password</label>
<input id="password" name="password" class="required"/> </input>
</p>
<p>
<label for="server">Server</label>
<input id="server" name="server" class="required"/> </input>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
Connect.php
<?php
$user = $_POST['u'];
$password = $_POST['p'];
$server = $_POST['s'];
#$con = mysql_connect ($server, $user, $password);
if (!$con) {
$response = "false";
echo $response;
} else {
$response = "true";
echo $response;
}
?>
change your php script
if (!$con) {
$response = 'false';
echo $response;
} else {
$response = 'true';
echo $response;
}
and in javascript
if (data == 'false')

Categories