Есть ли более короткий и более оптимальный способ проверить параметр GET?

Я проверяю, существует ли параметр в URI. Затем я проверяю, является ли это число или нет, а затем я проверяю, существует ли сообщение на форуме. Есть ли более короткий и лучший способ сделать это вместо того, чтобы повторяться?

Там страница Извините.php — страница ошибки, которую я включаю.

Я даже не знаю, правильно ли я поступаю. Я все еще довольно новичок в этом.

<!DOCTYPE html>
<html lang="en">
<head>
<?php
//require head
require '../partials/head.php';
?>
<title>KTOWN | </title>
</head>
<body>
<?php
//sidenav
include '../partials/sidenav.php';
?>
<div class="container">
<?php
//header
include '../partials/header.php';
?>
<main>
<?php

if(!isset($_GET['id'])){

include '../partials/sorry.php';

}else{
if(!is_numeric($_GET['id'])){

include '../partials/sorry.php';

}else{
$postId = (int)$_GET['id'];
$qry = '
SELECT forum_posts.id AS postId, forum_cats.name AS catName, site_users.username AS postAuthor, forum_posts.post_title AS postTitle, forum_posts.post_content AS postContent, forum_posts.is_anon AS postAnon, forum_posts.show_post AS showPost
FROM forum_cats
JOIN forum_posts ON forum_cats.id = forum_posts.post_cat_id
JOIN site_users ON site_users.id = forum_posts.post_author_id
WHERE forum_posts.id = ?';
$getPost = $conn->prepare($qry);
$getPost->bind_param('i',$postId);
$getPost->execute();
$result = $getPost->get_result();

if($result->num_rows < 1){
include '../partials/sorry.php';
}else{

while($row = $result->fetch_object()){
$postId = $row->postId;
$postTitle = $row->postTitle;
$postAuthor = $row->postAuthor;
$postAnon = $row->postAnon;
$showPost = $row->showPost;
$postContent = $row->postContent;
}

if($showPost === 0){
include '../partials/sorry.php';
}else{
?>

<div class="forum_post">
<h1><?php echo $postTitle; ?></h1>
<?php
if($postAnon === 1){
echo '<h2 class="forum_post__author">by <i class="fa fa-user-secret"></i> Anonymous</h2>';
}else{
echo '<h2 class="forum_post__author"> by '.$postAuthor.'</h2>';
}
?>
<p class="forum_post__content"><?php echo $postContent; ?></p>
<button class="btn btn--red"><i class="fa fa-flag"></i> Report</button>
</div>
<form class="forum-reply-form">
<h2>Reply Here</h2>
<div class="fgrp">
<textarea name="replyContent" id="replyContent" cols="30" rows="6" class="input input__textarea"></textarea>
</div>
<div class="fgrp">
<button id="subbut" class="btn btn--orange">Submit</button>
</div>
<div class="errbox"></div>
</form>
<div style="box-shadow:0 0 3rem #ccc; margin:1rem;padding:1rem;"><h2><i class="fa fa-reply"></i> Replies</h2></div>


<?php
}
}
}
}
?>
</main>
</div>
</body>
<script src="../js/sidenav.js"></script>
<script>
document.querySelector('#subbut').addEventListener('click',function(evt){
evt.preventDefault();
var content = document.querySelector('#replyContent').value.trim();
var errs = 0;
var errbox = document.querySelector('.errbox');
errbox.innerHTML = '';
var errmsg = [];
if(content.length < 100){
errs++;
errmsg.push('<p>Please add more content to your reply.</p>');
}
if(errs !== 0){
for(var i =0; i < errmsg.length; i++){
errbox.insertAdjacentHTML('beforeend',errmsg[i]);
}

}else{
errbox.innerHTML = '';

//Submit reply

}



});
</script>
</html>

0

Решение

Я бы пошел с комбинацией нуль-коалесцирующий оператор а также filter_var()

if ($postId = filter_var($_GET['id'] ?? null, FILTER_VALIDATE_INT)) {
// all good, $postId is numeric
} else {
include '../partials/sorry.php';
}

?? это современный и менее многословный эквивалент isset() троичное заявление, например

$id = isset($_GET['id']) ? $_GET['id'] : $someDefaultValue;

Доступно с PHP 7.0.

2

Другие решения

По крайней мере, вы можете спасти себя гнездование:

Когда используешь andлюбое выражение будет ложным, если крайнее левое подвыражение уже ложно. Любое выражение справа даже не будет оцениваться.

Итак, вы можете использовать:

if(isset($_GET['id']) && is_numeric($_GET['id'])){
//show content
}else{
include '../partials/sorry.php';
}

is_numeric($_GET['id']) не будет оцениваться, если isset($_GET['id']) возвращает false, следовательно, нет проблем с возможными нулевыми ссылками.

1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector