Jump to content

Recommended Posts

I wrote this really nice posting system for a site I'm working on. Problem is, I messed it up somehow, and now I can retrieve $_POST variables so I can post stuff to a MySQL database. I'm really new to PHP, and I have no idea what I did wrong.

HTML code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="The PPC Planet software archive.">
    <meta name="author" content="JohnS and VP44">
    <title>PPC Planet Public Archive</title>

    <link rel="canonical" href="https://getbootstrap.comhttps://getbootstrap.com/docs/4.5/examples/jumbotron/">

    <!-- Bootstrap core CSS -->
    <link href="https://getbootstrap.com/docs/4.5/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

    <!-- Favicons -->
    <link rel="apple-touch-icon" href="images/ppc.png" sizes="180x180">
    <link rel="icon" href="images/ppc.png" sizes="32x32" type="image/png">
    <link rel="icon" href="images/ppc.png" sizes="16x16" type="image/png">
    <meta name="theme-color" content="#28A745">


    <style>
        .bd-placeholder-img {
            font-size: 1.125rem;
            text-anchor: middle;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }
        
        @media (min-width: 768px) {
            .bd-placeholder-img-lg {
                font-size: 3.5rem;
            }
        }
        
        .cover {
            background-image: url("images/earth.jpg");
            background-size: cover;
            background-color: rgba(0, 0, 0, .8);
            background-blend-mode: multiply;
        }
    </style>
    <link href="stylesheets/2kstyle.css" rel="stylesheet" type="text/css">
    <link href="stylesheets/archivestyle.css" rel="stylesheet" type="text/css">
    <link href="stylesheets/posts.css" rel="stylesheet" type="text/css">
</head>

<body style="background-color: black; color: white;">
    <nav class="navbar navbar-dark fixed-top green">
        <a class="navbar-brand" href="index.html"><b>PPC</b>Planet</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample09" aria-controls="navbarsExample09" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

        <div class="collapse navbar-collapse" id="navbarsExample09">
            <ul class="navbar-nav mr-auto ">
                <li class="nav-item">
                    <a class="nav-link" href="index.html">Home</span></a>
                </li>
                <li class="nav-item active">
                    <a class="nav-link" href="archive.html">Archive <span class="sr-only">(current)</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="news.html">News</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="contact.html">Contact</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="about.html">About</a>
                </li>
            </ul>
        </div>
    </nav>

    <br><br><br><br>
    <script src="https://www.google.com/recaptcha/api.js"></script>

    <div class="content home">
        <h2 style="color: white;"><b>PPC Planet Public Archive</b></h2>
        <br>
        <div id="backDiv">
            <a href="deletepost.php"><b>(🗑) Delete or (🚩) report a post</b></a>
            <br><br>
            <button id="backDiv" class="greenBtn" onclick="back()">« back</button>
            <br><br><br>
        </div>

        <div id="postsDiv" class="posts content home"></div>
        <div id="captcha">
            <p>To prevent spam and unwanted submissions, we require that you complete the CAPTCHA below.</p>
            <br>
            <div class="g-recaptcha brochure__form__captcha" data-sitekey="6Ldku8QZAAAAABQJVhyfOnVljIoUoihUuBUfaFJn" required></div>
            <br><br><br>
            <input type="checkbox" id="findCheck" onchange="findToggle()">
            <label for="findCheck">Filter Listings</label>
            <br>
            <div style="display: none;" id="searchDiv">

                <!--text input-->
                <input type="radio" id="textsearch" name="filters" value="textsearch">
                <label for="textsearch">Search by text</label> &nbsp;&nbsp;&nbsp;

                <input style="width: 75%;" placeholder="Show results that contain inputted text..." type="text" id="searchTxt" />

                <br><br>

                <!--type picker-->
                <input type="radio" id="typesearch" name="filters" value="typesearch">
                <label for="typesearch">Search by type</label> &nbsp;&nbsp;&nbsp;

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

                <!--category picker-->
                <input type="radio" id="categorysearch" name="filters" value="categorysearch">
                <label for="categorysearch">Search by category</label> &nbsp;&nbsp;&nbsp;

                <select name="categoryselect" id="categoryselect">
                    <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>
            </div>
            <br><br>
            <button class="greenBtn" onclick="callValidation()">Visit Archive</button>
        </div>
    </div>
    <br><br><br><br>

    <script>
        document.getElementById("postsDiv").style.display = "none";
        document.getElementById("captcha").style.display = "block";
        document.getElementById("searchDiv").style.display = "none";
        document.getElementById("backDiv").style.display = "none";

        function callValidation() {
            if (grecaptcha.getResponse().length == 0) {
                //if CAPTCHA not complete
                alert('Please complete the CAPTCHA.');
            } else {
                //reset reCAPTCHA and show + hide stuff
                grecaptcha.reset()
                document.getElementById("postsDiv").style.display = "block";
                document.getElementById("backDiv").style.display = "block";
                document.getElementById("captcha").style.display = "none";

                //show posts
                if (document.getElementById("findCheck").checked == true && document.getElementById("typesearch").checked == true) {
                    document.getElementById("searchTxt").value = document.getElementById("typeselect").value;
                } else if (document.getElementById("findCheck").checked == true && document.getElementById("categorysearch").checked == true) {
                    document.getElementById("searchTxt").value = document.getElementById("categoryselect").value;
                }

                //fetch posts from database
                var posts_search_query = document.getElementById("searchTxt").value;
                fetch("posts.php?search_query=" + posts_search_query).then(response => response.text()).then(data => {
                    document.querySelector(".posts").innerHTML = data;
                    document.querySelectorAll(".posts .write_post_btn, .posts .reply_post_btn").forEach(element => {
                        element.onclick = event => {
                            event.preventDefault();
                            document.querySelectorAll(".posts .write_post").forEach(element => element.style.display = 'none');
                            document.querySelector("div[data-post-id='" + element.getAttribute("data-post-id") + "']").style.display = 'block';
                            document.querySelector("div[data-post-id='" + element.getAttribute("data-post-id") + "'] input[name='name']").focus();
                        };
                    });
                    document.querySelectorAll(".posts .write_post form").forEach(element => {
                        element.onsubmit = event => {
                            event.preventDefault();
                            fetch("posts.php?search_query=" + posts_search_query, {
                                method: 'POST',
                                body: new FormData(element)
                            }).then(response => response.text()).then(data => {
                                element.parentElement.innerHTML = data;
                            });
                        };
                    });
                });
            }
        }

        function back() {
            document.getElementById("backDiv").style.display = "none";
            document.getElementById("postsDiv").style.display = "none";
            document.getElementById("captcha").style.display = "block";
            document.getElementById("searchTxt").value = "";
        }

        //when filter toggle changed
        function findToggle() {
            if (document.getElementById("findCheck").checked == true) {
                //when checked
                document.getElementById("searchDiv").style.display = "block";
                document.getElementById("searchTxt").style.display = "block";
                document.getElementById("categoryselect").style.display = "block";
                document.getElementById("typeselect").style.display = "block";
                document.getElementById("textsearch").checked = true;
            } else {
                //when unchecked
                document.getElementById("searchDiv").style.display = "none";
            }
        }
    </script>

    <footer class="container center white ">
        <p>&copy; PPC Planet Team 2020</p>
        <br>
    </footer>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js " integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj " crossorigin="anonymous "></script>
    <script>
        window.jQuery || document.write('<script src="https://getbootstrap.com/docs/4.5/assets/js/vendor/jquery.slim.min.js "><\/script>')
    </script>
    <script src="https://getbootstrap.com/docs/4.5/dist/js/bootstrap.bundle.min.js " integrity="sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf " crossorigin="anonymous "></script>

</body>

</html>

PHP code:

<?php
include('mysqlconnect.php');
error_reporting(E_ALL);
try {
    $pdo = new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
} catch (PDOException $exception) {
    // If there is an error with the connection, stop the script and display the error
    exit('Failed to connect to database!' . $exception);
}

// Below function will convert datetime to time elapsed string
function time_elapsed_string($datetime, $full = false) {
   $now = new DateTime;
   $ago = new DateTime($datetime);
   $diff = $now->diff($ago);
   $diff->w = floor($diff->d / 7);
   $diff->d -= $diff->w * 7;
   $string = array('y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second');
   foreach ($string as $k => &$v) {
       if ($diff->$k) {
           $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
       } else {
           unset($string[$k]);
       }
   }
   if (!$full) $string = array_slice($string, 0, 1);
   return $string ? implode(', ', $string) . ' ago' : 'just now';
}

// This function will populate the posts and posts replies using a loop
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 method="post">
           <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 (isset($_POST['name'])) {
       $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.');
   }
   
   // 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;
}
?>

<div class="post_header">
    <span style="color: white;" class="total"><?=$posts_info['total_posts']?> total post(s)</span>
    <a style="color: white;" href="#" class="write_post_btn" data-post-id="-1">Create Post</a>
</div>


<?=show_write_post_form()?>

<?=show_posts($posts)?>

 

How can I fix this so posting works again? All help is appreciated!

Link to comment
https://forums.phpfreaks.com/topic/311442-cant-get-_post-information/
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.