Within range values PHP

Really quick question but am i doing something wrong? I’m building a review system everything works great but there is one area that can be manipulated and my fix is not working so can someone tell me what i’m doing wrong? Thanks

Right now there are 5 stars each with value 1,2,3,4,5 but if you inpsect element you can manipulate that to 8000 and then you get 8000 stars so can somone see what i’m doing wrong? For some reason if i select the 1 or 5 radio button it works fine but when i do the 2,3,4 it breaks so all help much appreciated :slight_smile:

            if ( empty($data['rating']) ) {
                $data['review_err'] = 'Nice try! Rating must be between 1 and 5!!';
            } elseif ($data['rating'] > 1 && $data['rating'] < 5) {
                $data['review_err'] = 'Nice try! Rating must be between 1 and 5!';
            }

That is looking for a value greater than 0 and less than 6.
Don’t you mean less than 0 or more than 6?

@SamA74 Thanks for quick reply its been a long day so my brain is a tad slower but im just trying to check the numbers are no less than 1 and no more than 5!

Otherwise they can manipulate and do this which i did during my testing:
https://gyazo.com/f9936b4cc2cfbbed674f0aa46feb1965

If it’s > 1 and < 5, this isnt an error. You’ve made your Correct case your Error case. And even then, it should be >= and <= to include 1 and 5.

How about a little function to clip the range and return a valid result whatever goes in?

function validrange($value, $min = 1, $max = 5){ // Enter a value. Optional to set different min and max
	$int = round(abs($value));  // Ensure you have a positive integer
	if($int < $min){ $result = $min ;}	// Too small, up it
	elseif($int > $max){ $result = $max ;}	// Too big, cap it
	else{ $result = $int ;}	// Within range, OK
	return $result ;
}
1 Like

Shorthand it, Sam.
$result = min($max,max($min,(round(abs($value)))));

2 Likes

Thanks @m_hutley + @SamA74 now im going to sleep :slight_smile:

What the fun is with this rounding and abs and blocks of code and piles of variables? KISS!

echo (in_array($submitted_value, range(1,5))) ? ‘Ok’ : ‘Error’;

1 Like

That is a lot neater.

Depends if you want to return an error or force the closest valid value and continue.

In this case we are talking about ratings so there no valid closest values. Valid values are only 1-5. Anything else, there is a problem somewhere and submission should be rejected.

3 Likes

Yes, generally any evidence of deliberate form/URL tampering I will ditch the (ab)user.
So maybe in this case it’s not the time for friendly “try again” messages or helping them on their way to a submission.

eh… depends on the range. speed-wise, comparison of three numbers is going to be faster than an array search of an arbitrary number of members…

This OP is an exact and specific use case. There is no “depends”. Valid range is 1-5. Feel free to post a different solution if you like. Many ways to do the same thing. In this case I dont see speed ever being an issue submitting a rating.

OP, when your done with your nap I would be interested to see the code where your values are being manipulated. I suspect there are probably other issues with the code. If your not already doing it, you should use a repository such as Git Hub. It will make it easier to review your code as a whole for those who want to.

I assume it’s just a list of radio buttons with numeric values, 1 - 5. Eg:-

<input type="radio" name="rating" value="1">
<input type="radio" name="rating" value="2">
<input type="radio" name="rating" value="3">
<input type="radio" name="rating" value="4">
<input type="radio" name="rating" value="5">

Anyone could easily go into Inspect and edit the values to whatever they want, like 50000, 3.4, -20, bobby-tables, anything you like, just as with any form input. So just a case of post submission validation, which we now have a few versions of to choose from.

It should be as you posted, but if you learn anything from these forums you know you can’t trust an op’s code without seeing it. For all we know he is using GET or doing who-knows-what. Nevertheless, changing a form submission is a trivial task.

@SamA74 @benanamen

Here is my code, let me know if there is something wrong :slight_smile: :

Controller Code:

    public function reviews($id)
    {
        if($_SERVER['REQUEST_METHOD']=='POST'){
            
            $_POST = filter_input_array(INPUT_POST,FILTER_SANITIZE_STRING);
            
            $getSettings = $this->setting->getAll();
            $getCategories = $this->setting->getCategories();
            $getItemById = $this->item->getItemById($id);
            $getItemReviews = $this->item->getItemReviews($id);
            
            $data = [
                'getSettings' => $getSettings,
                'getCategories' => $getCategories,
                'getItem' => $getItemById,
                'getItemReviews' => $getItemReviews,
                'review' => trim($_POST['review']),
                'rating' => trim(validrange($_POST['rating'])),
                'user_id' => '1',
                'item_id' => $id,
                'review_err' => '',
                'rating_err' => ''
            ];
            
            if( empty($data['review']) ){
                $data['review_err'] = 'Your review cannot be empty!';
            }
            
            if ( empty($data['review_err']) && empty($data['rating_err'])){
                if( $this->item->addReview($data) ){
                    flash('comment_alert', 'Review Added', 'alert alert-success');
                    redirect('item/reviews/'.$id.'/');
                } else{
                    die('Something went wrong');
                }
            } else {
                $this->view('item/item-reviews', $data);
            }

        } else{
            
            $getSettings = $this->setting->getAll();
            $getCategories = $this->setting->getCategories();
            $getItemById = $this->item->getItemById($id);
            $getItemReviews = $this->item->getItemReviews($id);
            
            $data = [
                'getSettings' => $getSettings,
                'getCategories' => $getCategories,
                'getItem' => $getItemById,
                'getItemReviews' => $getItemReviews,
                'review' => '',
                'rating' => ''
            ];
            if($getItemById == false) { redirect('error'); die(); }
            $this->view('item/item-reviews', $data);     
        }
    }
    
    public function deletereview($id)
    {
        if($_SERVER['REQUEST_METHOD']=='POST') {
            
         $review = $this->item->getReviewDetails($id);
         $data = [
                'user_id' => '1',
                'review_id' => $id
        ];
         
         if($review[0]['user_id'] != '1'){
            flash('comment_alert', 'Something went wrong!', 'alert alert-danger rounded');
            redirect('item/reviews/'.$review[0]['item_id'].'/');
            die();
         }
         
         if( $this->item->deleteReview($data) ){
            flash('comment_alert', 'Review Deleted', 'alert alert-success');
            redirect('item/reviews/'.$review[0]['item_id'].'/');
         } else {
            die('Something went wrong');
         }

      } else {
         redirect('');
      }
    }

Model Code:

    public function getReviewDetails($id)
    {
        $bind = [':id' => $id];
        $results = $this->db->select('msi_items_reviews','id = :id', $bind);
        return $results;
    }
    
    public function addReview($data)
    {
        $date = date("Y-m-d H:i:s");
        $data1 = [
            'user_id' => $data['user_id'],
            'review' => $data['review'],
            'rating' => $data['rating'],
            'item_id' => $data['item_id'],
            'status' => '1',
            'date' => $date
        ];
        $this->db->insert('msi_items_reviews', $data1);
        return true;
    }
    
    public function deleteReview($data)
    {
        $bind = [
            ':id' => $data['review_id'],
            ':user_id' => $data['user_id']
        ];
        $this->db->delete('msi_items_reviews', 'id = :id AND user_id = :user_id', $bind);
        return true;
    }

View Code:

<div class="col-sm-8">
    <div class="row">
        <div class="col-12">
            <?php echo flash('comment_alert'); ?>
        </div>
        <?php if( $data['getItemReviews'] == FALSE ) { ?>
            <div class="col-12">
                <div class="alert alert-primary shadow-1" role="alert">
                    <b><i class="fas fa-info-circle"></i> No Reviews Found!</b>
                </div>
            </div>
            <?php } else { foreach($data['getItemReviews'] as $review) : ?>
                <div class="col-lg-12 col-md-12 col-sm-12 mb-3">
                    <div class="card h-100 shadow-1">
                        <div class="card-body card-padding">
                            <div class="float-left"><img itemprop="image" width="80" class="img-fluid rounded mr-4" src="<?php echo FULL_ROOT;?>/uploads/items/<?php echo $data['getItem'][0]['id']; ?>/<?php echo $data['getItem'][0]['icon_img']; ?>" alt="<?php echo $data['getItem'][0]['name']; ?>"></div>
                            <div class="clearfix">
                                <div class="float-right">
                                    <p><i class="far fa-clock mr-1"></i>
                                        <?php echo helper_format_date_5(strtotime($review['date'])); ?>
                                    </p>
                                </div>
                                <div class="mb-2 font-weight-bold">
                                    <a>
                                        <?php echo $review['username']; ?>
                                    </a> <span class="badge badge-success">Purchased</span></div>
                                <div class="mb-2">

                                    <b>Rating:</b>
                                    <?php
$rate = $review['rating'];
for ($x = 0; $x < $rate; $x++) {
    echo '<i class="fas fa-star"></i>';
}
for ($x = 0; $x < 5-$rate; $x++) {
    echo '<i class="far fa-star"></i>';
}
?>

                                </div>
                                <div>
                                    <p>
                                        <?php echo $review['review']; ?>
                                    </p>
                                </div>

                                <form class="float-right" action="<?php echo FULL_ROOT;?>/reviews/delete/<?php echo $review['id']; ?>" method="post">
                                    <input type="submit" value="Delete" class="btn btn-sm btn-lightb">
                                </form>

                            </div>

                        </div>
                    </div>
                </div>
                <?php endforeach;  } ?>
    </div>

    <div class="card shadow-1">
        <div class="card-body">
            <form action="" method="post" class="mb-0">
                <h6>Leave a review</h6>
                <div class="form-group">
                    <div class="custom-control custom-radio custom-control-inline">
                        <input type="radio" id="1" value="1" name="rating" class="custom-control-input">
                        <label class="custom-control-label" for="1">1</label>
                    </div>
                    <div class="custom-control custom-radio custom-control-inline">
                        <input type="radio" id="2" value="2" name="rating" class="custom-control-input">
                        <label class="custom-control-label" for="2">2</label>
                    </div>
                    <div class="custom-control custom-radio custom-control-inline">
                        <input type="radio" id="3" value="3" name="rating" class="custom-control-input">
                        <label class="custom-control-label" for="3">3</label>
                    </div>
                    <div class="custom-control custom-radio custom-control-inline">
                        <input type="radio" id="4" value="4" name="rating" class="custom-control-input">
                        <label class="custom-control-label" for="4">4</label>
                    </div>
                    <div class="custom-control custom-radio custom-control-inline">
                        <input type="radio" id="5" value="5" name="rating" class="custom-control-input" checked>
                        <label class="custom-control-label" for="5">5</label>
                    </div>
                </div>

                <div class="form-group mb-0">
                    <textarea name="review" class="form-control <?php echo (!empty($data['review_err'])) ? 'is-invalid' : ''; ?>" id="exampleFormControlTextarea1" rows="4">
                        <?php echo $data['review']; ?>
                    </textarea>
                    <span class="invalid-feedback"><?php echo $data['review_err']; ?></span>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </div>

</div>

Where is your validrange function defined?

Also, which framework is this? You don’t seem to be leveraging it much.

Its defined in my helper and its a custom MVC framework!

    public function __construct()
    {
        $this->load_helper(['view']);
        $this->load_helper(['url']);
        $this->load_helper(['date']);
        $this->load_helper(['session']);
        $this->load_helper(['custom']);
        $this->setting = $this->model('Settings');
        $this->user = $this->model('Items');
    }

Which helper? Can you show the code?

<?php

// Controls Categories Menu Dropdown
function sub($cat, $id)
{
    echo '<div class="dropdown-menu" role="menu">';
    echo '<a class="dropdown-item hide-me" role="presentation" href="#"><i class="fas fa-fire mr-2"></i> Most Popular</a>';
    echo '<div class="dropdown-divider hide-me" role="presentation"></div>';
    foreach($cat as $category) {
        if($category['parent_id'] == $id){
            echo '<a class="dropdown-item" role="presentation" href="'.FULL_ROOT.'/category/'.$category['id'].'/'.slugify($category['name']).'"><i class="'.$category['icon'].' mr-2"></i>'.$category['name'].'</a>';
        }
    }
    echo '</div>';
}

// Controls Categories Sidebar
function sub1($cat, $id)
{
    echo '<div class="collapse" id="collapse'.$id.'" role="menu">';
    foreach($cat as $category) {
        if($category['parent_id'] == $id){
            echo '<a class="dropdown-item py-2" role="presentation" href="'.FULL_ROOT.'/category/'.$category['id'].'/'.slugify($category['name']).'"><i class="'.$category['icon'].' ml-4 mr-2"></i>'.$category['name'].'</a>';
        }
    }
    echo '</div>';
}

// Checks Review Range
function validrange($value, $min = 1, $max = 5){ // Enter a value. Optional to set different min and max
    $result = min($max,max($min,(round(abs($value)))));
	return $result ;
}