Add parameter to PHP - php

When I sent an image to the code below, uploadImage.php, through a POST method, how do I add a String parameter?
<?php
$hasError = false;
foreach( $_FILES as $i=>$file )
{
if ( $file['error'] )
{
$hasError = true;
}
}
if ( ! $hasError )
{
$myFilePath = '_uploads/'.'_'.$file["name"];
$dta = file_get_contents($file['tmp_name']);
file_put_contents($myFilePath, $dta);
}
else
{
echo('Stick custom error message here');
}
?>

If I understand you correctly, add to the page from where the form is submitted an input:
<form ....>
...
<input type="text" name="my_key" value="default value" />
</form>
You can then access it from $_POST:
if (array_key_exists("my_key", $_POST) && !is_array($_POST["my_key"]))
echo htmlentities($_POST["my_key"]);
else
//error handling; field was not included or multiple values were given

Related

How to get the name of input field with PHP

I'm trying to create a function. which will check if the field is empty or not. If the input is empty it'll push an error for that input in the error array.
$errors = ["name" => "Name is required"];
like so
How can I do this?
function checkRequiredFields($fields = [], $errors = [])
{
foreach ($fields as $field) {
if (is_blank($field)) {
$errors[$field] = "$field is required";
}
}
}
btw here's how my is_blank function looks:
function is_blank($value)
{
return !isset($value) || trim($value) === '';
}
You can check that the field has been submitted and doesn't hold the empty string:
<?php
function check_required_fields($fields, &$errors) {
foreach($fields as $fieldname) {
if(isset($_POST[$fieldname]) && $_POST[$fieldname] === '') {
$errors[$fieldname][] = "'$fieldname' is required.";
}
}
}
check_required_fields(['email'], $errors);
?>
<form method='POST'>
<input type='text' name='name'>
<input type='email' name='email'>
<input type='submit'>
</form>
You can get the values of the input fields with
$field = $_GET["field"]; // or $_POST["field"]; depending of your form.
But you need to sanitize properly your input values for security reasons.
https://www.php.net/manual/fr/function.filter-input.php
The empty() function is also what you're looking for.
if (empty($field)) {
$errors[$field] = "$field is required";
}
Checkout the documentation : https://www.php.net/manual/fr/function.empty.php
Take a look at the isset() function also.

Display error if empty field - PHP

I want to display an error on the same page if any field is empty.
I've got this, which works but the empty error is displayed as soon as the page is loaded instead of appearing once empty fields are submitted.
<?php
// Required field names
$required = array('triangleSide1', 'triangleSide2', 'triangleSide3');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field)
{
if (empty($_POST[$field]))
{
$error = true;
}
}
if ($error)
{
echo "ALL FIELDS ARE REQUIRED";
}
else
{
echo header('Location: formSuccess.php');
}
?>
Any ideas? -- UPDATE // IVE TRIED ALL ANSWERS, nothing has worked so far
Wrap everything you check on post in this:
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
// Your code containing checks here
}
This way, it will only trigger when a POST request is used.
If you have an input you know will always be submitted with the form, such as a hidden one:
<input type='hidden' name='formsubmit' value='1'>
Then you can test for this before validating the other inputs
if($_POST["formsubmit"]) {
// Required field names
$required = array('triangleSide1', 'triangleSide2', 'triangleSide3');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "ALL FIELDS ARE REQUIRED";
} else {
header('Location: formSuccess.php');
}
}
Also you don't echo the return of header()
OR another way ( I have something similar in one of my pages)
function check_presence($value){
return isset($value) && $value!=="";
}
function validate($required){
global $error
foreach($required as $field){
$value = trim($_POST[$field]);
if (!check_presence($value)){
$error = true;
}
}
return $error;
}
then on the page containing the form and its validation code
$required = array('triangleSide1', 'triangleSide2', 'triangleSide3');
if(isset($_POST["submit"]){
$error = validate($required);
if ($error){
echo "ALL FIELDS ARE REQUIRED";
}
}
Try isset instest of empty!!!
if (empty($_POST[$field]))
Become
if (isset($_POST[$field]))

function to check required form fields not working

I have a user defined function, it takes one argument as an array for the form required fields. It checks if these fields are empty or not. If they are empty it will return a message and stop processing the form.
<?php
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
}
}
return "You have errors";
}
$required_array = array('name', 'age');
if (isset($_POST['submit'])) {
echo check_required_fields($required_array);
}
?>
<html>
<body>
<form action="#" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
The function is returning this error even when the form required fields are filled? how to fix this?
How can i use just use the function with out writing the word echo before its name?
I want to use this function so i don't have to manually write the if and else statement for every field in the form.
I think you want to do like this?
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
return "You have errors"; //This indicates that there are errors
}
}
}
or why not just:
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname])) {
return "You have errors"; //This indicates that there are errors
}
}
}
UPDATE:
Change:
$required_array = array('name', 'age'); //This just sets strings name and age into the array
to:
$required_array = array($_POST['name'], $_POST['age']); //This takes the values from the form

email validation in php

I'm trying to validate my username as an email address, however PHP isn't letting me do this! what's wrong here?
//This checks if all the fields are filled or not
if (!empty($_POST['username']) ||
!empty($_POST['password']) ||
!empty($_POST['repassword']) ||
!empty($_POST['user_firstname']) ||
!empty($_POST['user_lastname']) ){
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
here is the form i used in register.php
<form action="createuser.php" method="post" name="registration_form" id="registration_form">
<label>Email</label>
<input name="username" type="text" id="username" size="50" maxlength="50" /><br />
Typo?
header('Location: register.php?msg=You didn't complete all of the required fields');
^---unescaped embedded quote
Your empty logic is also faulty. You're checking if any fields are NOT empty (e.g. filled out) and then complaining that they're not filled out. remove the ! to invert the logic.
if (empty(...) || empty(...) || etc...)
instead of this use regular expression for validating your email address
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!preg_match("^[^#]{1,64}#[^#]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!preg_match("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
and then check if it return true redirect it to location if not then simply throw an error
You would not get to Validate the email because your if statement is wrong .. it is checking if any of the post is not empty.
Replace it with
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])) {
For starters, look at the syntax highlighting for why you're getting parse errors.
header('Location: register.php?msg=You didn't complete all of the required fields');
needs to become:
header('Location: register.php?msg=You didn\'t complete all of the required fields');
How about you use javascript window.location? Sometimes header function is sensitive.And also put a submit button in your form since by default fields are empty when loaded.
if(isset($_POST['your_submit_button_name'])){
if (empty($_POST['username']) ||
empty($_POST['password']) ||
empty($_POST['repassword']) ||
empty($_POST['user_firstname']) ||
empty($_POST['user_lastname']) ){
?>
<script>
window.location = 'register.php?msg=You didn\'t complete all of the required fields';
</script>
<?php
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
}
NOTE: I remove "!" before your empty function since youre trapping the fields that are empty.
Try to use this solution:
$FormData = $_POST;
if(isset($FormData['button_name'])){
$Errors = array();
foreach ($$FormData as $key => $value) {
if(empty($value)) $Errors[] = 'Some message';
if($key = 'username'){
if(filter_var($value, FILTER_VALIDATE_EMAIL){
$Errors[] = 'The email address you entered is not valid';
}
}
}
if(empty($Errors)){
// #todo Do some action
} else {
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
}
function check_email($check) {
$expression = "/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/";
if (preg_match($expression, $check)) {
return true;
} else {
return false;
}
}
Now use this method as :
if(!check_email($_REQUEST['ContactEmail'])){
$register_error .="Enter the correct email address!<br />";
$reg_error=1;
}

How can I prevent my form being sent if a user writes misformated entries in my fields? ie. Letters in number fields

What happens:
When I write two values in both text boxes, the page doesn't show the Congratulations message as it should. When I write only 1 value, the correct thing happens, which is not show the congratulations message.
What should happen:
If a user writes only 1 value, the form should still appear with any previously filled out fields still there. If a user writes values in all of the fields, the Congratulations should appear.
Edit - Finally got it working, in case any other newbies want to check it out:
<html>
<head>
<?php
$validForm = false;
function getValue($field){
if(isset($_GET[$field])){
return htmlspecialchars(trim($_GET[$field]));
}
else{
return "";
}
}
function validateForm($value,$type){
$field = $_GET[$value];
//magic goes here.
switch ($type){
case 'required':
if (!isset($field) || ($field=="")){
global $validForm;
$validForm = false;
}
else{
global $validForm;
$validForm = true;
}
break;
case 'email':
$regexp = "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z-][0-9a-zA-Z-]+\.)+[a-zA-Z](2,6)$/";
if(isset($field) && preg_match($regexp,$field)){
global $validForm;
$validForm = true;
}
else {
global $validForm;
$validForm = false;
}
break;
case 'number':
if(!isset($field) || ($field=="") || (!is_numeric($field))){
global $validForm;
$validForm = false;
}
else{
global $validForm;
$validForm = true;
}
break;
default:
die('Validacion desconocida.');
}
}
?>
</head>
<body>
<?php validateForm('name','required'); ?>
<?php validateForm('lastname','required'); ?>
<?php if($validForm == false){ ?>
<form action="class2.php" method="get">
<dl>
<dt>First Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('name')) ?>" name="name" />
</dd>
<dt>Last Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('lastname')) ?>" name="lastname" />
</dd>
<br />
<dt>
<input type="submit" value="enviar" name="validate"/>
</dt>
</dl>
</form>
<?php
} else {
?>
<h1>Congratulations, you succesfully filled out the form!</h1>
<?php }
?>
</body>
there appears to be a problem with the $validForm variable in the validateForm function.
I think your assuming changes to $validForm inside the function change the same variable name outside the function. because you haven't set it as a global variable it won't do this for you.
You need to look at Variable scope in PHP.
http://php.net/manual/en/language.variables.scope.php
this will explain how you should handle this variable. you can return the value in the function..
e.g for that function just return the variable:
function validateField($value,$type){
//magic goes here.
switch ($type){
case 'required':
if (!isset($value) || ($value== "")){
$valid = false;
}
else{
$valid = true;
}
break;
case 'email':
$regexp = "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z-][0-9a-zA-Z-]+\.)+[a-zA-Z](2,6)$/";
if(isset($value) && preg_match($regexp,$variable)){
$valid = true;
}
else {
$valid = false;
}
break;
case 'number':
if(!isset($value) || ($value=="") || (!is_numeric($value))){
$valid = false;
}
else{
$valid = true;
}
break;
default:
die('Validacion desconocida.');
}
return $valid;
}
That will solve the problem in the function
to get the variable out do :
$formValid = true;
if (!validateField($_GET['name'],'required'))
{
$formValid = false;
}
if (!validateField($_GET['lastname'],'required'))
{
$formValid = false;
}
if ($formValid)....
The issue is that you're calling validateForm() after you check the value of $validForm. When you check $validForm right after your body tag, it is always going to be false. It will get set to true (assuming the form is valid) by the time it gets down past the second field, but you're already in the first branch of the if statement at that point, so the "congratulations" message will never be displayed.
To fix, just move your validation calls to before you check the value of $validForm:
<body>
<?php
validateForm($_GET['name'],'required');
validateForm($_GET['lastname'],'required');
if($validForm == false){ ?>
<form>
And so on.
2 things:
1) I don't think your $validForm variable is in scope with the function validateForm. It seems that you would need to call global on it inside the function
global $validate form.
2) you call validateForm after you set it to false. you need to do the checks before you do the conditional.

Categories