-2

I am trying to make a posting system for a project I am working on. Problem is, for some reason, all $_POST values are null, even if they are supposed to be set. As a result, my PHP script does not work.

I can't tell why this is the case, as it was working fine just yesterday. How can I fix this?

<?php
function show_posts($posts, $parent_id = -1) {
   $html = '';
   if ($parent_id != -1) {
       // If the posts are replies sort them by the "submit_date" column
       array_multisort(array_column($posts, 'submit_date'), SORT_ASC, $posts);
   }
   
   $resultCount = 0;

   // Iterate the posts using the foreach loop
   foreach ($posts as $post) {

    if (($_GET['search_query']) != "") {
        if ($post['parent_id'] == $parent_id) {
            if (strpos(implode($post), $_GET['search_query'])) {
                $resultCount++;

                //check if optional variables are not set
                $screenshot = $post['screenshot'];
                if ($screenshot.trim() == "") {
                    $screenshot = "https://ppcplanet.org/images/noscreenshot.png";
                }

                $serial = $post['serial'];
                if ($serial.trim() == "") {
                    $serial = "n/a";
                }

                $source = $post['source'];
                if ($source.trim() == "") {
                    $source = "n/a";
                }

                $html .= '
                <div class="post">
                    <br><br>
                    <div>
                        <h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3>
                        <span class="date">' . time_elapsed_string($post['submit_date']) . '</span>
                    </div>
                    <br>
                    <img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/>
                    <br><br>
                    <h2 class="content"><b><a href=' . nl2br(htmlspecialchars($post['url'], ENT_QUOTES)) . ' target="_blank">' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</a></b></h2>
                    <br>
                    <p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p>
                    <p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p>
                    <p class="content"><b>Original Source: </b> <a href =' . nl2br(htmlspecialchars($source, ENT_QUOTES)) . ' target="_blank">' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</a></p>
                    <p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p>
                    <p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p>
                    <a class="reply_post_btn" href="#" data-post-id="' .  $post['id'] . '">Add on... (ex. another version, manual, etc.)</a>
                    ' . show_write_post_form($post['id']) . '
                    
                    <div class="replies">
                    ' . show_posts($posts, $post['id']) . '
                    </div>
                </div>
                <br><br><br>
                ';
                
                ob_clean();
                echo(strval($resultCount) . ' result(s) found for "' . $_GET['search_query'] . '"'); //display number of results
            }
        }
    }
    else
    {
        //add each post to HTML variable
        if ($post['parent_id'] == $parent_id) {
            //check if optional variables are not set
            $screenshot = $post['screenshot'];
            if ($screenshot.trim() == "") {
                $screenshot = "https://ppcplanet.org/images/noscreenshot.png";
            }

            $serial = $post['serial'];
            if ($serial.trim() == "") {
                $serial = "n/a";
            }

            $source = $post['source'];
            if ($source.trim() == "") {
                $source = "n/a";
            }

            $html .= '
            <div class="post">
                <h2></h2>
                <br><br>
                <div>
                    <h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3>
                    <span class="date">' . time_elapsed_string($post['submit_date']) . '</span>
                </div>
                <br>
                <img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/>
                <br><br>
                <h2 class="content"><b><a href=' . nl2br(htmlspecialchars($post['url'], ENT_QUOTES)) . ' target="_blank">' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</a></b></h2>
                <br>
                <p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p>
                <p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p>
                <p class="content"><b>Original Source: </b> <a href =' . nl2br(htmlspecialchars($source, ENT_QUOTES)) . ' target="_blank">' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</a></p>
                <p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p>
                <p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p>
                <a class="reply_post_btn" href="#" data-post-id="' .  $post['id'] . '">Add on... (ex. another version, manual, etc.)</a>
                ' . show_write_post_form($post['id']) . '
                
                <div class="replies">
                ' . show_posts($posts, $post['id']) . '
                </div>
            </div>
            <br><br><br>
            ';
        }
    }
       
   }

   return $html;
}

// This function is the template for the write post form
function show_write_post_form($parent_id = -1) {
    $rand = randomIdentifier(); //generate random identifier string
    
    $html = '
    <div class="write_post" data-post-id="' . $parent_id . '">
       <form>
           <h2 style="color: white;">New Post</h2>
           <br>
           <input name="parent_id" type="hidden" value="' . $parent_id . '">
           <label for="name">Title:</label>
           <input style="width: 100%;" id="name" name="name" type="text" placeholder="Enter a title..." required>
           <br><br>
           <label for="screenshot">Screenshot (if applicable):</label>
           <input style="width: 100%;" id="screenshot" name="screenshot" type="url" placeholder="Screenshot URL">
           <br><br>
           <label for="type">URL:</label>
           <input style="width: 100%;" id="url" name="url" type="url" placeholder="Download URL" required>
           <br><br>
           <label for="type">Description:</label>
           <textarea name="content" id="content" placeholder="Write a description..." required></textarea>
           <br><br>
           <label for="type">Original Source (if known):</label>
           <input style="width: 100%;" id="source" name="source" type="url" placeholder="Original Source URL">
           <br><br>
           <label for="type">Serial (if applicable):</label>
           <input style="width: 100%;"  id="serial" name="serial" type="text" placeholder="Serial">
           <br><br>
           <label for="name">Your Name/Nickname:</label>
           <input style="width: 100%;"  id="postauthor" name="postauthor" type="text" placeholder="Enter your name..." required>
           <br><br>
           <br>

           <label for="type">Choose a type:</label>

           <select name="type" id="type">
             <option value="freeware">Freeware</option>
             <option value="abandonware">Abandonware</option>
             <option value="self-made">I wrote it myself</option>
           </select>

           &nbsp;&nbsp;&nbsp;

           <label for="category">Category:</label>

           <select name="category" id="category">
           <option value="app">App</option>
           <option value="game">Game</option>
           <option value="driver">Driver</option>
           <option value="manual">Manual</option>
           <option value="setup">Setup</option>
           <option value="ROM">ROM</option>
           <option value="other">Other</option>
           </select>         

           <br><br>
           <h2 style="color: white;">Post identifier string</h2>
           <input name="identifier" id="identifier" style="width: 100%;" readonly="true" type="text"" value="' . $rand . '">
           <br>
           <p style="color: red;">This is your post identifier string. It can be used to delete this post in the future without having to contact an admin. <b>Make sure you do not lose it!</b></p>
           <br><br>
           <h2 style="color: white;">Make sure your submission meets the following criteria:</h2>

           <br>
           
                <p> This submission is appropriate and doesn\'t have any mature content. - We want PPC Planet to be a safe place for people of all ages. Inappropriate submissions will be removed!</p>
                <p> This submission is either freeware, abandonware, or self-made. - No piracy! It\'s not fair to the developer(s).</p>
                <p> This submission has been tested, and works as advertised. - We don\'t want to have a bunch of broken software on the archive.</p>
                <p> This submission is not already on the archive. - Be sure that you are posting something unique!</p>
                <p> This submission is related to Pocket PCs. - Remember, this is an archive of Pocket PC software.</p>
            
            <br>

            <p><b>By following these rules, we can make the archive a fun (and totally rad) place for everyone!</b></p>
           
            <br><br>

            <p style="color: red; font-size: xx-large; "><b>Make sure you have proofread your post, as you will not be able to edit it once it has been posted. Additionally, make sure you write your down identifier string somewhere if you have not already.</b></p>
           
            <br><br>

            <button type="submit">Create Post</button>

            <br><br>
       </form>
   </div>
   
   ';

   return $html;
}

if (isset($_GET['search_query'])) {
   // Check if the submitted form variables exist
   if (($_POST['name']).trim() != "") {
       $stmt = $pdo->prepare('INSERT INTO posts (page_id, parent_id, name, screenshot, url, content, serial, type, category, identifier, source, postauthor, submit_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW())');
       $stmt->execute([ 1, $_POST['parent_id'], $_POST['name'], $_POST['screenshot'], $_POST['url'], $_POST['content'], $_POST['serial'], $_POST['type'], $_POST['category'], $_POST["identifier"], $_POST["source"], $_POST["postauthor"] ]);
       exit('Your post has been submitted! You can reload the page to see it.');
   }
   else
   {
   // Get all posts by the Page ID ordered by the submit date
   $stmt = $pdo->prepare('SELECT * FROM posts WHERE page_id = ? ORDER BY submit_date DESC');
   $stmt->execute([ 1 ]);
   $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
   // Get the total number of posts
   $stmt = $pdo->prepare('SELECT COUNT(*) AS total_posts FROM posts WHERE page_id = ?');
   $stmt->execute([ 1 ]);
   $posts_info = $stmt->fetch(PDO::FETCH_ASSOC);
   }
} else {
   exit('No search query specified!');
}


function randomIdentifier() {
   $pass = 0;
   $complete = false;
    
    while (!$complete)
    {
        //generate random identifier string until it is unique
        $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()';
        $pass = array();
        $alphaLength = strlen($alphabet) - 1;
        for ($i = 0; $i < 100; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }

        include('mysqlconnect.php');
        
        $pdo = new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
        $data = implode($pass);

        $stmt = $pdo->prepare( "SELECT identifier FROM posts WHERE identifier =:id" );
        $stmt->bindParam(':id', $data, PDO::PARAM_STR);
        $stmt->execute();
        $myIdentifier = $stmt->fetch();
        if (!$myIdentifier) {
            //identifier is unique
            $complete = true;
        }
    }

    return $data;
}
?>

<?=show_write_post_form()?>

<?=show_posts($posts)?>

You can try it out for yourself here. All help is appreciated!

ADyson
  • 57,178
  • 14
  • 51
  • 63
JohnS
  • 13
  • 1
  • 6
  • 1
    Seems like your sending a GET request from your client. You can inspect all HTTP request in debugging console (F12 > Network). Enable "Preserve Log" to maintain log when switching to new sites. – Code Spirit Sep 07 '20 at 13:38
  • @CodeSpirit Thanks for the reply! How could I change this to a POST request? (Sorry, I'm REALLY new to PHP) – JohnS Sep 07 '20 at 13:39
  • learn HTTP and diffrence of Client and Server first. This error is in your client side (HTML / JavaScript). Workaround would be to change `$_POST` into `$_GET` which is the more applicable solution here. – Code Spirit Sep 07 '20 at 13:43
  • @CodeSpirit I'd never recommend submitting a complex form like this via GET. For one thing all the data is exposed on the querystring (and thus could be logged by a server or shared around), secondly you could run into problems with max URL length and so on. – ADyson Sep 07 '20 at 13:49
  • @ADyson Complexity of data has nothing to with the HTTP method you choose to send it. As I see it the form provides filters so the request `get` something and the filters influence what is `get`ed. Also you have the ability to share the link to your filter results to other people. – Code Spirit Sep 07 '20 at 13:51
  • @CodeSpirit actually it does matter - because as I said, there's a maximum length a URL can be in certain browsers and environments. And there's a security consideration too - personal data shouldn't be put on a querystring as part of a URL, where it can potentially be logged by webservers, proxy servers, routers etc. Plus, _this_ form is submitting new data, not filtering results. It's not a search query, it's data entry. So yes a search form could submit a GET, that's fine, but not a data entry form. It's definitely primarily sending data in this case, not retrieving it. – ADyson Sep 07 '20 at 13:54

2 Answers2

0

$_POST in PHP collects any variables submitted in the body of a HTTP POST request.

However your HTML form is submitting a GET request (which is the default if you don't specify the method). You can fix this by specifying the method attribute of the form:

<form method="post">
ADyson
  • 57,178
  • 14
  • 51
  • 63
-1

$_POST superglobal is only available in POST requests. You seem to be rendering your content in a GET request.