PHP-意外的其他在线33和32

时间:2019-06-12 03:00:25

标签: php html mysql

我正在为游戏服务器制作一个面板,并且试图使其在惩罚表中检查现有的user_id,以便只能将其禁止一次。

我在另一台服务器上尝试过。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <thread>
#include <mutex>
#include <random>
#include <cstring>
#include <cstdlib>
#include <cmath>

#include "my_common_code.h"

const std::string PATHNAME = "words.txt";

struct leaderBoard {
    float score;
    std::string playerName;
};

std::vector<std::string> words;
std::vector<leaderBoard> lb;
std::mutex mutex1;

std::string getRandomWord();
void handleClientFunction(socket_ptr clientSocketPtr);
std::string addToLeaderBoard(const std::string &playerName, float score);

int main(int argc, char *argv[]) {

    try {
        // check for correct number of arguments
        if (argc != 2)
            throwRuntimeError("Invalid argument count");

        // store the passed argument 
        char *port = argv[1];

        // check if the argument contains all digits
        // convert the passed argument to ints
        int portNumber = std::atoi(port);
        if ((portNumber < 0) || (portNumber > 65535))
            throwRuntimeError("Invalid port number");

        std::ifstream inFile(PATHNAME);
        std::string line;
        while (inFile >> line) {
            words.push_back(line);
        }
        inFile.close();

        if (words.empty())
            throwRuntimeError("No words read from file");

        int listeningSocket;
        int clientSocket;
        socklen_t addressLength;
        sockaddr_in serverAddress;
        sockaddr_in clientAddress;
        int opt = 1;

        //////////////////////////////// Socket creation //////////////////////////////////////////////////////////////////
        socket_ptr listeningSocketPtr( socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) );
        listeningSocket = listeningSocketPtr.get();
        if (listeningSocket == -1)
            throwRuntimeError("socket", errno);

        if (setsockopt(listeningSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
            throwRuntimeError("setsockopt", errno);

        serverAddress.sin_family = AF_INET;
        serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
        serverAddress.sin_port = htons(portNumber);

        ////////////////////////////// Socket binding /////////////////////////////////////////////////////////////////////
        if (::bind(listeningSocket, reinterpret_cast<sockaddr*>(&serverAddress), sizeof(serverAddress)) < 0)
            throwRuntimeError("bind", errno);

        if (portNumber == 0) {
            addressLength = sizeof(serverAddress);
            if (getsockname(listeningSocket, reinterpret_cast<sockaddr*>(&serverAddress), &addressLength) < 0)
                throwRuntimeError("getsockname", errno);
        }

        ////////////////////////////////// listening //////////////////////////////////////////////////////////////////////
        if (listen(listeningSocket, 5) < 0)
            throwRuntimeError("listen", errno);

        ///////////////////////////// start game ///////////////////////////////////
        std::cout << "\nWelcome to hangman game server! \n";
        std::cout << "\nListening on port: " << ntohs(serverAddress.sin_port) << " \n";
        std::cout << std::endl;

        do {
            ///////////////////////////////// accepting /////////////////////////////////////////////////////////////////////
            addressLength = sizeof(clientAddress);
            socket_ptr clientSocketPtr( accept(listeningSocket, reinterpret_cast<sockaddr*>(&clientAddress), &addressLength) );

            if (clientSocketPtr.get() == -1)
                throwRuntimeError("accept", errno);

            std::thread t(handleClientFunction, std::move(clientSocketPtr));
            t.detach();
        }
        while (true);
    }
    catch (const std::exception &ex) {
        std::cerr << ex.what() << std::endl;
        return -1;
    }

    return 0;
}

std::string getRandomWord()
{
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_int_distribution<int> dist(0, words.size()-1);
    return words[dist(gen)];
}

void handleClientFunction(socket_ptr clientSocketPtr) {

    int clientSocket = clientSocketPtr.get();

    try {
        // receive player name from client
        std::string playerName = readString(clientSocket);

        // chose a word at random for the client to process
        std::string word = getRandomWord();

        // print the word to the screen
        std::cout << "Word to guess is: " << word << std::endl;

        // dashed representation of the word
        std::string dashed(word.length(), '_');

        char guess;
        bool correct;
        int32_t countCorrect = 0;
        int numGuess = 0;

        do {
            // send dashed word for client to display
            sendString(clientSocket, dashed);

            // receive a guess from the client and check if it is valid
            guess = readChar(clientSocket);

            correct = false;
            ++numGuess;

            // check if the word contains the guessed letter
            auto idx = word.find(guess);
            while (idx != std::string::npos) {
                if (dashed[idx] != guess) {
                    correct = true;
                    dashed[idx] = guess;
                    ++countCorrect;
                }
                idx = word.find(guess, idx+1);
            }

            // send the guess response from the server
            sendBool(clientSocket, correct);
            sendInt32(clientSocket, countCorrect);
        }
        while (countCorrect < word.length());

        float score = std::round((static_cast<float>(numGuess) / static_cast<float>(word.length())) * 100) / 100;

        std::string lBoardString = addToLeaderBoard(playerName, score);
        sendString(clientSocket, lBoardString);
    }
    catch (const std::exception &ex) {
        std::cerr << ex.what() << std::endl;
    }
}

std::string addToLeaderBoard(const std::string &playerName, float score) {
    std::lock_guard g(mutex1);

    lb.emplace_back({score, playerName});
    std::sort(lb.begin(), lb.end(),
        [](const leaderBoard &lhs, const leaderBoard &rhs) {
            return lhs.score < rhs.score;
        }
    );

    std::ostringstream oss;
    for (auto &p : lb) {
        std::cout << p.playerName << std::endl;
        std::cout << p.score << std::endl;
        oss << "Name: " << p.playerName << ", " << "Score: " << p.score << "\n";
    }
    return oss.str();
}

我希望它能够处理http请求

1 个答案:

答案 0 :(得分:1)

我看到您的代码有很多错误:

if!empty变量的$reason代码检查$userid

然后将它们添加到代码中

<?php
$host       = "localhost";
$dbusername = "asta";
$dbpassword = "*****";
$dbname     = "asta";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
        . mysqli_connect_error());
} else {

  $userid = filter_input(INPUT_POST, 'userid');
  $reason = filter_input(INPUT_POST, 'reason');
  $duration = filter_input(INPUT_POST, 'duration');
  if (!empty($userid)) {
    if (!empty($reason)) {
        $sql    = "SELECT `user_id` FROM `punishments` WHERE `user_id`='$userid'";
        $result = $conn->query($sql);
        if ($result->num_rows >= 1) {
            echo "The user with userid '$userid' is already banned.";
        } else {
            $sql = "INSERT INTO punishments (user_id, reason, duration, origin_id, type, time, active) values ('$userid','$reason','$duration','10','2','1','1')";
            if ($conn->query($sql)) {
                echo "The user with userid '$userid' has been banned!";
            } else {
                echo "Error: " . $sql . "" . $conn->error;
            }
            $conn->close();
        }
    } else {
        echo "REASON should not be empty";
        die();
    }
  } else {
    echo "USERID should not be empty";
    die();
  }

}
?>