Issue pushing an element in an array.(array_push) - php

I did this php code
<?php
if (!isset($_GET['id']) or !is_numeric($_GET['id'])) {
header('Location: index.php');
} else {
extract($_GET);
$id = strip_tags($id);
require_once 'config/functions.php';
$errors = array();
if (!empty($_POST)) {
extract($_POST);
$author = strip_tags($author);
$comment = strip_tags($comment);
if (empty($author)) {
$errors = array_push($errors, 'Entre a nickname');
}
if (empty($comment)) {
$errors = array_push($errors, 'Entre a comment');
}
var_dump($comment);
var_dump($author);
var_dump($errors);
if (count($errors) == 0) {
$comment = addComment($id, $author, $comment);
$sucess = 'Your comment has been sent';
unset($author);
unset($comment);
}
}
$article = getArticle($id);
$comments = getComments($id);
}
However, when I submitted the form I saw that every time the submission was successful so I decided to dump the variables $errors , $comment and $author to try to solve the issue. Here, the array $errors no matter what was empty. I tried not to put the comment or the author or even both but it still isn't working.
Could you help me out with this problem guys because I really don't know from where it comes from?

In PHP array_push() is a function which allows you to push multiple elements into the array, and the result of that function is the number of elements added. The array itself is passed as reference in the first argument.
However, you do not need to call this function.
Note: If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.
You can just use the array append operator
if(!$comment) {
$errors[] = 'Entre a comment';
}
On unrelated note, you should never trust user input. Do not extract() your $_GET or $_POST super-globals!

Related

Return not working on empty check function PHP

Thank you for help. Anyway, i'm a student and i'm stuck making a function that does a simple empty() check on a key in a array. If it is empty() -> it will fill in the error and print it on a div element.
This is my code:
function validateData($data, $formErrors) {
if (empty($data)) {
$formErrors = 'name is required.';
}
echo $formErrors;
}
Executing the function:
$data = $_POST;
$formErrors = [];
// Elementen valideren
validateData($data['name'], $formErrors['name'] = '');
This is the thing that i want to achieve:
if (empty($data['surname'])) {
$formErrors['surname'] = 'Surname is required.';
}
Looks like it is not returning the value of that key or whatelse?
Thanks alot!
You need to make it a reference parameter with & if you want to assign it in the function.
function validateData($data, &$formErrors) {
if (empty($data)) {
$formErrors = 'name is required.';
}
echo $formErrors;
}
And you can't use an expression when passing a reference parameter, it has to be just the variable. It should be:
$formErrors = ['name' => ''];
validateData($data['name'], $formErrors['name']);

How to handle empty post (upto 20 post) without using empty() and "&&" operator

I am receiving post values. I want a suggestion for logic to handle empty or not set post values.
Is there such a way if one of them receives empty post, the $Data array should not receive anymore values and make it empty. In other words, i am trying to immitate the try and catch feature. If on any POST is empty, ignore reading the rest of POST and make that array as empty
Is my second draft considred valid?
First draft
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWSCHEDULE_SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWSCHEDULE_SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}
if(empty($DATA)){
//do something
}else{
//do something else
}
Second draft
try{
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTITLE');
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTYPE');
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
unset($DATA);
}
You can use one if statement with all required POST parameters.
if(!empty($_POST['var1']) && !empty($_POST['var2']) && !empty($_POST['var3']) && !empty($_POST['var4'])):
/*and then assign all the POST values to a $DATA array as you want.*/
$DATA['var1'] = $_POST['var1'];
$DATA['var2'] = $_POST['var2'];/* and so on..*/
endif;
I personally prefer to white list values that I loop through and assign.
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
$at_least_one_empty = false;
foreach($valid_keys as $data_key)
{
$data[$data_key] = isset($_POST[$data_key])
? trim($_POST[$data_key]) // Remove accidental user whitespace.
: ''; // If unsubmitted - set to empty string.
if($data[$data_key] === '')
$at_least_one_empty = true;
}
if($at_least_one_empty) {
unset($data);
} else {
process($data);
}
Note with the sample code above an unsubmitted value will be assigned the empty string. This might not be the behaviour you want.
However if you just want to assign and check you received all inputs this might do (no filtering or validation):
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
foreach($valid_keys as $data_key)
$data[$data_key] = $_POST[$data_key] ?? null;
$not_all_received = in_array(null, $data, true);

PHP check empty post data in array

HTML markup
<input name="one[name]">
<input name="one[email]">
<input name="two[message]">
...
alot input
..
I pass that two array data from jquery to php, i need check if the field is empty by php and exit when find one of them is empty.
But i dont want do it one by one, can it done by php function like foreach or other?
This is what i tried but fail.
$data_one = $_POST['one'];
$data_two = $_POST['two'];
if (empty( $_POST['one'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Above code keep return field are filled message, whether i fill the input field or not.
Thanks so much.
$allFilled = true;
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
$allFilled = false;
exit('some fields are empty');
}
}
if($allFilled){
exit('all fields are filled');
}
Making use of array_filter and count functions
<?php
$data_one = $_POST['one'];
$data_one_filter = array_filter($_POST['one']); //Remove indexes of null or 0 - certainly name and email can't be 0
$data_one_count = count($_POST['one']); //count actual number of POST variables
$data_two = $_POST['two'];
if (count($data_one_filter) === $data_one_count) {
exit('fields are filled');
} else {
echo('some fields are empty');
// continue other function
}
You are sending data as array. So you seed to check this data as array like this:
$data_one = $_POST['one']['name'];
$data_two = $_POST['two']['message'];
if (empty( $_POST['one']['name'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Try this
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
exit('some field are empty');
}
}
echo "All fields are filled";

Won't read variable in function in another script

Whenever I leave my input field empty, $error['commment'] should be set and echoed, but it won't echo, but if I just say echo "some text";, it echo's it.
The comments function is in my functions.php file and $error[] = array() is given in my text.php file above my comments() function, so I don't understand why it's not working, please help guys.
The last bit of PHP code is in a while loop that has to display all the results of my SQL query.
Code above my HTML in text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
comments();
?>
Code in my functions.php:
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
$filledIn = true;
if (empty($text)) {
$error['comment'] = "No text filled in";
$filledIn = false;
}
}
}
This is the code in my text.php:
<?php
if(isset($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Because $error is not in the scope of the comments() function. So $error['comment'] never gets set.
Ideally you would want to do something like this:
text.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error['comment'] = comments();
functions.php
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
if (empty($text)) {
return "No text filled in";
}
}
return null;
}
text.php
<?php
if(!empty($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Rather than setting the array key "comments" directly I would use a return value from the comments() function to set it. This allows you to avoid having to use global variables.
Edit: I removed the $filledIn variable from comments() because it wasn't being used in the provided code.
#pu4cu
imo, since you dont come across as very advanced, so that you dont have to make many code changes to what you have now which might get you the minimal edits, and easiest for you to understand;
if in your comment function, you just return a response from this function, like a good little function does, then your response will be available when you call the function, when you set that function to a variable.
//functions.php (note this sets error to true to be failsafe, but this depends on how your using it. set the $response to an empty array in the first line instgad, i.e. array(); if you don't want it failsafe.
<?php
function comments()
{
$response = array(
'error' => TRUE,
'filledIn' => FALSE
);
if (isset($_POST['submit']))
{
$text = $_POST['text'];
$response['filledIn'] = TRUE;
if (empty($text))
{
$response['error']['comment'] = "No text filled in";
}
else{
$response['error'] = NULL;
}
}
return $response;
}
//index.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$response = comments();
//text.php
<?php
if($response['error']['comment'])) echo "<p class='error'>".$response['error']['comment']."</p>";
I find your code overly complicated, 3 files, 2 includes, and 1 function, when all you really needed is this:
$error = array();
$error['comment'] = empty($_POST['text']) ? "No text filled in" : $_POST['text'];
echo "<p class='error'>".$error['comment']."</p>";
Your scopes are all mixed up. Your comments() function checks for $_POST, which should be checked before the function is called, and then tries to set a variable within its scope, but you try to access the same variable from outside.
The correct way would be:
text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
if (isset($_POST['submit']) {
comments($_POST);
}
?>
functions.php
function comments($data){
if (isset($data['text'])) {
$text = $data['text'];
if (empty($text)) {
return array('comment' => 'No text filled in');
}
return true;
}
return null;
}
Then you can use the values returned by your function on to act on the result.

How can I set a variable variable from within a function in PHP?

I am making a form, some of which is optional. To show the output of this form, I want to be able to check whether a POST variable has contents. If it does, the script should make a new normal PHP variable with the same value and name as the POST variable, and if not it should make a new normal PHP variable with the same name but the value "Not defined". This is what I have so far:
function setdefined($var)
{
if (!$_POST[$var] == "")
{
$$var = $_POST[$var]; // This seems to be the point at which the script fails
}
else
{
$$var = "Not defined";
}
}
setdefined("email");
echo("Email: " . $email); // Provides an example output - in real life the output goes into an email.
This script doesn't throw any errors, rather just returns "Email: ", with no value specified. I think this is a problem with the way I am using variable variables within a function; the below code works as intended but is less practical:
function setdefined(&$var)
{
if (!$_POST[$var] == "")
{
$var = $_POST[$var];
}
else
{
$var = "Not defined";
}
}
$email = "email"; // As the var parameter is passed by reference, the $email variable must be passed as the function argument
setdefined($email);
Why don't you do it this way:
function setdefined($var)
{
if (isset($_POST[$var]) && !empty($_POST[$var]))
{
return $_POST[$var];
}
else
{
return "Not defined";
}
}
$email = setdefined('email');
echo("Email: " . $email);
The variable you create in first example is only available inside the function
You could make that unknown variable submitted by possibly malicious user, global one. To do so, add this to the start of your function:
global $$var ;
This is not only ugly, but maybe unsafe too.

Categories