I'm having some trouble with a Form. It contains an input type File for uploading an image, and a select tag to choose where to put this image.
Code goes like this:
<?php
require_once("functions.php");
if(isset($_COOKIE['user']))
{
$username= checkcookie($_COOKIE['user']);
}
if (isset($_SESSION['user'])) {
if ($_POST) {
$errors = array();
$errors = SomeValidation();
if (empty($errors )) {
UpdateImages();
exit;
}else {
Header ("location: somefile.php?error=There was an error");
exit;
}
}else{
var_dump("error");
} ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<?php if(isset($_GET['error'])) {?>
<div class="alert alert-danger" role="alert">
<ul>
<li><?php echo $_GET['error'] ?></li>
</ul>
</div>
<?php } ?>
<div class="cbp-mc-column">
<label>Choose new Image</label>
<select id="code" name="code">
<option value="1" >First</option>
<option value="2" >Second</option>
<option value="3" >Third</option>
</select>
<br/>
<input type="file" name="newimage" value="" />
<br>
<input type="submit" name="update" value="Update">
<br>
</div>
</form>
<!-- Bootstrap Core JavaScript -->
<script src="../js/bootstrap.min.js"></script>
</body>
</html>
<?php }else
{
header('location: panel.php');
}
?>
I'm always getting False for if($_POST), and also when I submit the form.
Any idea why?
EDIT: I forgot to mention, I'm sending the select value via post, so I can choose which file upload, and It is always empty.
to upload image or any other file you need to check the $_FILES array not post,
this question could be helpfull
How do you loop through $_FILES array?
It is better to check inputs instead of request method.. so use
if (!empty($_POST["update"])) {
....
}
First, you need to check if the submit button was clicked :isset($_POST['update'])
Next, check if a file has been selected: isset($_FILES['newimage']['tmp_name'])
if (isset($_POST['update'])) {
if (isset($_FILES['newimage']['tmp_name'])) {
$errors = array();
$errors = SomeValidation();
if (empty($errors )) {
UpdateImages();
exit;
} else {
Header ("location: somefile.php?error=There was an error");
exit;
}
} else {
echo "No file selected.";
}
} else {
echo "Not a POST request.";
}
Related
I'm very new to PHP and I've cobbled this together from some other answers on here. Can anyone show me how to get the $errMsg to display? At present, a blank or incorrect name leads to a blank page. Is this because the form isn't being displayed again? If so, how should I go about 'reloading' the form with the error message?
<?php
$name = "Fred";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["name"])) {
if ($_POST["name"] == $name) {
include("welcomeFred.php");
}
else {
$errMsg = "Incorrect name";
}
}
else {
$errMsg = "Name required";
}
}
else { ?>
<html>
...
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" required>
<span><?php echo $errMsg;?></span>
<input type="submit" value="Submit">
</form>
...
</html>
<?php } ?>
You shouldn't put the rendering of the form in the else of your if structure. This is the reason your form isn't loaded when you submit the form.
Remove the else { ?> and <?php } ?> at the end of your file and it should work fine.
I'm creating a function for PHP form validation. The idea is that if a user has not filled out a required field (for example, if a $_POST variable called "name" is empty), then the user will be warned.
This function doesn't seem to work, however:
function addError($x) {
if (!$_POST["$x"]) {
$error.="Please enter your $x";
}
}
echo $error;
I've isolated the problem down to the passing of the argument $x into $_POST, i.e. this line:
if (!$_POST["$x"]) {
Specifically, $_POST["$x"]. Is this the right way/syntax to pass an argument?
Thank you!
Your code should be like -
$error = '';
function addError($x, $error) {
if (!$x) { // Check for the data
$error.="Please enter your $x"; // Concatenate the errors
}
return $error; // return the error
}
echo addError($_POST[$x], $error); // Pass the data to check & the error variable
Try this.....
<form method="post">
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
<?php
$x=$_POST["name"];
function addError($x)
{
if ($x==null)
{
$error="Please enter your name";
}
else
{
$error='';
}
return $error;
}
echo addError($x);
?>
Try this :-
$error = "";
function addError($x)
{
global $error;
if ("" == $_POST['"'.$x.'"'])
{
$error.="Please enter your".$x;
}
}
addError("name");
echo $error;
I referenced above two answers and write some code for this question. It works when I tested. You might get some idea for your coding.
Here is my tested code.
PHP section
<?php
function check_error($x){
$error = "";
if(isset($_POST[$x]) && $_POST[$x] == ""){
$error = "Please Enter Data";
}
return $error;
}
echo check_error('txt_name');
?>
HTML section
<!DOCTYPE html>
<html>
<head>
<title> Testing </title>
</head>
<body>
<h1> Testing </h1>
<hr/>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input type="text" name="txt_name" value="" placeholder="Your name" />
<input type="Submit" name="btn_submit" value="Submit" />
</form>
</body>
</html>
Make $error a global variable.
I have a simple php calculator which code is:
<html>
<head>
<title>PHP calculator</title>
</head>
<body bgcolor="orange">
<h1 align="center">This is PHP Calculator</h1>
<center>
<form method="post" action="phptest.php">
Type Value 1:<br><input type="text" name="value1"><br>
Type value 2:<br><input type="text" name="value2"><br>
Operator:<br><input type="text" name="sign"><br>
Result:<br><input type"text" name="result">
<div align="center">
<input type="submit" name="submit" value="Submit">
</div>
</form>
</center>
<?php
if(isset($_POST['submit'])){
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
if($value1=='') {
echo "<script>alert('Please Enter Value 1')</script>";
exit();
}
if($value2=='') {
echo "<script>alert('Please Enter Value 2')</script>";
exit();
}
if($sign=='+') {
echo "Your answer is: " , $value1+$value2;
exit();
}
if($sign=='-') {
echo "Your answer is: " , $value1-$value2;
exit();
}
if($sign=='*') {
echo "Your answer is: " , $value1*$value2;
exit();
}
if($sign=='/') {
echo "Your answer is: " , $value1/$value2;
exit();
}
}
?>
All I want to do is that answer should be displayed in the result input field instead of echoing them separately. Please help? I Know it's simple but I am new in PHP.
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input> tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
Try this
<input class="qtytext-box" type="number" value= <?php echo $colll2; ?> >
In the below code: i have a select option dropdown(Employed,UmEmployed) If i select Option Employed it shows some input field(Current Designation, Current CTC) if i submit data without inserting anything it show validation: current designation is required.
If i select another option from dropdown that is unemployed it should redirect to another page directly but its not going to success.php (unemployed) that one is also validating.
<html>
<head>
<style>
#employer
{
display:none;
}
.error
{
color:#F00;
}
</style>
<?php
$currentdes="";
$currentdesErr="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
if(empty($_POST["desig"]))
{
$currentdesErr="* Current Designation is Required";
$valid=false;
echo "<style>#employer{display:block;}</style>";
}
else
{
$currentdes=test_input($_POST["desig"]);
}
//if valid then redirect
if($valid){
include 'database.php';
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=success.php">';
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<form id="jsform" method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>Chose Your Browser: <select name = "currentsta" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "1") echo "selected"; ?>>Employed</option>
<option value = "2" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "2") echo "selected"; ?>>UnEmployed</option>
</select>
</p>
<div id="employer">
Current Designation: <label><input type="text" name="desig" size="50" /></label>
<span class="error"><?php echo $currentdesErr?></span>
<br>
Current CTC: <label><input type="text" size="50" /></label><br>
</div>
<!--currentstatus starts here-->
<script type="text/javascript">
$('p select[name=currentsta]').change(function(e){
if ($('p select[name=currentsta]').val() == '1'){
$('#employer').show();
}else{
$('#employer').hide();
}
});
</script>
<!--currentstatus Ends here-->
<!--Submit Button-->
<input type="button" value = "Submit" onClick=" document.getElementById('jsform').submit();" />
</form>
</body>
</html>
The desig input field will be empty for unemployed option as it is not being filled. Hence you should consider both the conditions. Also don't include database.php in the if block . Instead inside the success.php
<html>
<head>
<style>
#employer
{
display:none;
}
.error
{
color:#F00;
}
</style>
<?php
$currentdes="";
$currentdesErr="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
if(empty($_POST["desig"]) && $_POST["currentsta"]==1)
{
$currentdesErr="* Current Designation is Required";
$valid=false;
echo "<style>#employer{display:block;}</style>";
}
else
{
$currentdes=test_input($_POST["desig"]);
}
//if valid then redirect
if($valid){
//include 'database.php';
header('Location:success.php');
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<form id="jsform" method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>Chose Your Browser: <select name = "currentsta" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "1") echo "selected"; ?>>Employed</option>
<option value = "2" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "2") echo "selected"; ?>>UnEmployed</option>
</select>
</p>
<div id="employer">
Current Designation: <label><input type="text" name="desig" size="50" /></label>
<span class="error"><?php echo $currentdesErr?></span>
<br>
Current CTC: <label><input type="text" size="50" /></label><br>
</div>
<!--currentstatus starts here-->
<script type="text/javascript">
$('p select[name=currentsta]').change(function(e){
if ($('p select[name=currentsta]').val() == '1'){
$('#employer').show();
}else{
$('#employer').hide();
}
});
</script>
<!--currentstatus Ends here-->
<!--Submit Button-->
<input type="button" value = "Submit" onClick=" document.getElementById('jsform').submit();" />
</form>
</body>
</html>
If on selection of unemployed option, you want to redirect to another page, then redirect it using JavaScript.
In the script at the end of the page, the modification would be -
$('p select[name=currentsta]').change(function(e){
if ($('p select[name=currentsta]').val() == '1'){
$('#employer').show();
}else{
//$('#employer').hide();
//This redirects to next page on selecting the option.
window.location.href= "success.php";
}
});
I'm trying to set up simple example for form validation, whether field is empty or not. If field is not empty action redirect me to page ok.php and if not back to formvalidation.php. and change css of the field. I have problem with returning error array back to formvalidation.php and testing it to change css for input field. What am I doing wrong?
formvalidation.php
<?php require("includes/functions.php"); ?>
<?php
global $errors;
?>
<form action="posting.php" method="p">
<ul>
<li id="field">
<label for="field">Contact person </label>
<input
<?php
if (empty($errors)) {
echo "style=\"background-color: #ECECEC;\"";
} else {
if (in_array("field", $errors)) {
echo "style=\"background-color: red;\"";}
} else {
echo "style=\"background-color: #ECECEC;\"";
}
}
?>
type="text" name="field"/>
</li>
<li>
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
action.php
<?php require("includes/functions.php"); ?>
<?php
$errors = form_validation ();
if (!empty($errors)) {
redirect_to("formvalidation.php");
} else {
redirect_to("ok.php");
}
?>
function
<?php
function form_validation () {
$errors = array ();
$required_fields = array('field');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$errors[] = $fieldname;
}
}
return $errors;
}
After redirect $error variable is empty use $_SESSION
<?php
$_SESSION['error']=form_validation ();
if (!empty($_SESSION['error'])) {
redirect_to("formvalidation.php");
} else {redirect_to("ok.php");}
?>
And in formvalidation.php
$error=$_SESSION['error'];
unset($_SESSION['error']);
don't forget to ensure that session_start() is on the top of your code
Just take a look at this tutorial: http://www.html-form-guide.com/php-form/php-form-validation.html. It's implemented more object-oriented.