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.
Related
Using core PHP only and nothing else, like JavaScript or clientside programming, I need PHP to check if the form's required fields are filled in or not, and display error message if missed. I need to check using procedural style programming as I'm not into OOP yet and don't understand it.
Html Form
<html>
<head>
<title>
Searchengine Result Page
</title>
</head>
<body>
<form method = 'POST' action = "">
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<label for='url'>url</label>
<input type='url' name='url' id='url' required>
<br>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' required>
<br>
<label for='description'>description</label>
<input type='text' name='description' id='description' required>
<br>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' required>
<br>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' required>
<br>
<button type='submit'>Search!</button>
</form>
</body>
</html>
Php Form Validator
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels_count = count($required_labels);
for($i=0; $i!=$required_labels_count; $i++)
{
if(!ISSET(in_array(($_POST['$required_labels[$i]']),$required_labels))) //Incomplete line as I don't know how to complete the code here.
{
echo 'You must fill-in the field' .'Missed field\'s label goes here'; //How to echo the missed field's label here ?
}
}
?>
I know I need to check against associated array values as it would be easier and less code, but I don't know how to do it.
Notice my error echo. It's incomplete as I don't know how to write that peace of code.
How would you check with the shortest possible code using procedural style?
Anything else I need to know?
NOTE: I do not want to be manually typing each $_POST[] to check if the required ones are filled in or not. I need PHP to loop through the $required_labels[] array and check. Or if you know of any shorter way of checking without looping then I want to know.
First we will have an empty $errors array, and then we will apply the validations, and if any of them fails, we will populate the $errors.
Finally using a helper function errorsPrinter we will print the errors under their labels.
For you PHP validation part use the below code. Note that I also added the part to validate the string and int types too.
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$inputs = $_POST;
$errors = [];
foreach($required_labels as $label) {
if(!isset($inputs[$label]) || empty($inputs[$label])) {
$errors[$label] = array_merge(
["You must fill-in the field."],
$errors[$label] ?? []
);
}
}
foreach($strings_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_string($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be string"],
$errors[$label] ?? []
);
}
}
foreach($ints_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_int($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be int"],
$errors[$label] ?? []
);
}
}
function errorsPrinter($errors, $key)
{
$output = '<ul>';
if(!isset($errors[$key])) {
return;
}
foreach($errors[$key] as $error) {
$output = $output. '<li>' . $error . '</li>';
}
print($output . '</ul>');
}
?>
inside the form you can do something like this:
<form method='POST' action="">
<?php errorsPrinter($errors, 'submission_id') ?>
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<?php errorsPrinter($errors, 'website_age') ?>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<?php errorsPrinter($errors, 'url') ?>
<label for='url'>url</label>
<input type='url' name='url' id='url' >
<br>
<?php errorsPrinter($errors, 'anchor') ?>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' >
<br>
<?php errorsPrinter($errors, 'description') ?>
<label for='description'>description</label>
<input type='text' name='description' id='description' >
<br>
<?php errorsPrinter($errors, 'keyphrase') ?>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' >
<br>
<?php errorsPrinter($errors, 'keyword') ?>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' >
<br>
<button type='submit'>Search!</button>
</form>
Note that the errorsPrinter is just a helper and you can remove it and use $errors array as you want. The sample output of errors is like this:
[
"url" => ["You must fill-in the field."],
"anchor" => ["You must fill-in the field."],
"description" => ["You must fill-in the field."],
"keyphrase" => ["You must fill-in the field."],
"keyword" => ["You must fill-in the field."],
"website_age" => ["This input should be int"]
]
$errors = [];
foreach($required_labels as $field) {
if (!isset($_POST[$field]) || $_POST[$field] == '') {
$errors[$field] = "{$field} cannot be empty";
// echo "${field} cannot be empty";
}
}
And then to output those errors:
<?php
if (count($errors)) {
?>
<div id='error_messages'>
<p>Sorry, the following errors occurred:</p>
<ul>
<?php
foreach ($errors as $error) {
echo "<li>$error</li>";
}
?>
</ul>
</div>
<?php
}
And you could directly output the errors next to the input as well:
<input type="text" id="first_name" name="first_name" placeholder="First Name" />
<?php if (isset($errors['first_name'])) echo "<div class='error_message'>{$errors['first_name']}</div>";?>
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 ...
}
}
I have this piece of code and I want to show result in the third input box not in the input box and hole page and i want to know if i can a $_GET['$vairbles'] whiten functions
NOTE : I’m beginner in php programming
Here is my code :
<?php
$email = "mail#somedomain.com";
if (isset($_GET['txt1']) and isset($_GET['txt2'])) if (!empty($_GET['txt1']) and!empty($_GET['txt2'])) {
$tex1 = $_GET['txt1'];
$tex2 = $_GET['txt2'];
echo "They are all filled.<br>";
} else {
echo "Please fill in first and second Fields";
}
shwor();
Function shwor() {
global $email;
global $tex1;
global $tex2;
$len1 = strlen($tex1);
$len2 = strlen($tex2);
if ($len1 and $len2 > 0) if ($tex1 == $tex2) echo "matched ";
else echo "Does not match";
}
?>
<form action:"email.php" method="GET">
<input 1 type="text" name="txt1"><br><br>
<input 2 type="text" name="txt2"><br><br>
<input 3 type="text" name="Result" value = "<?php shwor();?>"><br><br>
<input type="submit" value="Check matches"><br>
</form>
everything works, just misspelled in this line:
<form action:"email.php" method="GET">
should be:
<form action="email.php" method="GET">
..and remember to name your file email.php that the data will be sent to the file itself ;-)
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.
I have code in html for a form which needs to be filled. When the button 'OK' is clicked, values are sent to a php script. I use $_POST. Can I display the same form when input is not of the right format but do this only inside my php script?
This is where I check some of my fields but I don't know how to re-display the form.
if (isset($_POST["name"])) {
$name = $_POST["name"];
}
if (isset($_POST["date"])) {
$date = $_POST["date"];
}
Thanks a lot.
You could try something like this:
<?php
foreach($_POST as $key => $value) {
$$key = $value;
}
?>
<form method="post" action="">
<input type="text" name="name" value="<?php echo !empty($name) ? $name : 'Fill in your name'; ?>" />
<input type="text" name="age" value="<?php echo !empty($age) ? $age : 'Fill in your age'; ?>" />
<input type="text" name="what" value="<?php echo !empty($what) ? $what : 'what'; ?>" />
<input type="text" name="ever" value="<?php echo !empty($ever) ? $ever : 'ever'; ?>" />
<input type="submit" value="Go" />
</form>
If you are looking for a php template engine to split the PHP and HTML, I recommand Smarty
EDIT
To split the HTML and PHP without an engine, you could do something like combine the functions file_get_contents() and str_replace like here:
Template.html
<form method="post" action="">
<input type="text" name="name" value="#_name_#" />
<input type="submit" value="Go" />
</form>
PHP
<?php
$template = file_get_contents('template.html');
foreach($_POST as $key => $value) {
$template = str_replace('#_'.$key.'_#', !empty($value) ? $value : '');
}
echo $template;
?>
That way you get the .html file, and replace #_name_# with the post or a default value.
Still I recommand you to use Smarty