Почему файл не читается из отправляемого

У меня есть код, который должен отправлять файл на php с помощью js. Это не работает. Ранее я пытался просмотреть отправляемое изображение. Это не сработало. Если кто-то хотел посмотреть, что делает код, это пример входа в систему: username:john & password:1234. Если кто-нибудь может мне помочь, заранее спасибо.

Это HTML

<!DOCTYPE html>
<html>
    <head>
        <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src = "https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script>
        <script>
            // Initialize Firebase
            var config = {
                apiKey: "AIzaSyCg8CauUyZeBGffR_2yAv7hkb-pD9zuzrA",
                authDomain: "push-notifications-affa8.firebaseapp.com",
                databaseURL: "https://push-notifications-affa8.firebaseio.com",
                projectId: "push-notifications-affa8",
                storageBucket: "push-notifications-affa8.appspot.com",
                messagingSenderId: "1027448457059"
            };
            firebase.initializeApp(config);
        </script>
        <link rel = "manifest" href = "/manifest.json">
        <title>MegaLords</title>
        <link rel = "stylesheet" href = "styles/main.css">
        <style>
            #fileToUpload {
                display:none;
            }
            #logout {
                all: initial;
                font-family: "Comic Sans MS", "Comic Sans", cursive;
                cursor: pointer;
            }
            #logout:hover{
                color: blue;
            }
        </style>
        <script src = "script/main.js"></script>
    </head>
    <body>
        <div id = "test" class = "topnav">
            <a class=active>Home</a>
            <a href=news.php>News</a>
            <a href=contact.php>Contact</a>
            <a href=about.php>About</a>
            <a href=buy.php>Buy</a>
            <?php
                if (isset($_COOKIE['username'])){
                    echo    "<a href=game.php>Play</a>";
                    echo    "<button onclick = " . "document.getElementById('id04').style.display='block'" . ">Profile</button>";

                }else{
                    echo "<button onclick = " . "document.getElementById('id01').style.display='block'" . ">Sign Up</button>";
                    echo "<button onclick = " . "document.getElementById('id02').style.display='block'" . "> Login</button>";
                }
                ?>
        </div>
        <div id = "id01" class = "modal" style = 'padding-top: 50px;'>
            <form id=signUpForm class = "modal-content">
                <span onclick = "document.getElementById('id01').style.display='none'" class = "close" title = "Close Modal">&times;</span>
                <div class = "container">
                    <h1>Sign Up</h1>
                    <p>Please fill in this form to create an account.</p>
                    <hr>
                    <p id  = "errusra" class = "err"></p>
                    <label><b>Username</b></label>
                    <input id = "signUpUsername" type = "text" placeholder = "Enter Username" class = "profile" required>
                    <p id = "erremaila" class = "err"></p>
                    <label><b>Email</b></label>
                    <input type = "text" placeholder = "Enter Email" id = "signUpEmail" class = "profile" required>
                    <p id = "errpswa" class = "err"></p>
                    <label><b>Password</b></label>
                    <input id = "signUpPassword"type = "password" placeholder = "Enter Password" class = "profile" required>
                    <p id = "errrepswa" class = "err"></p>
                    <label><b>Repeat Password</b></label>
                    <input type = "password" placeholder = "Repeat Password" id = "passwordRepeat" class = "profile" required>
                    <label>
                        <input type = "checkbox" checked = "checked" style = "margin-bottom:15px"> Remember me
                    </label>
                    <p>By creating an account you agree to our <a href = "#" style = "color:dodgerblue">Terms & Privacy</a>.</p>
                    <div class = "clearfix">
                        <button type = "button" onclick = "document.getElementById('id01').style.display='none'" class = "cancelSignUpbtn">Cancel</button>
                        <button type = "submit" class = "signupbtn">Sign Up</button>
                    </div>
                </div>
            </form>
        </div>
        <div id = "id02" class = "modal" style = "padding-top: 50px;">
            <form id = "loginform"class = "modal-content animate">      
                <div class = "imgcontainer">
                    <span onclick = "document.getElementById('id02').style.display='none'" class = "close" title = "Close Modal">&times;</span>
                    <img src = "images/loginformimg.png" alt = "Avatar" class = "avatar">
                </div>
                <div class = "container">
                    <p id = "loginerr" class = 'err'></p> 
                    <label><b>Username</b></label>
                    <input id = "loginUsername"type = "text" placeholder = "Enter Username" class = "profile" required>
                    <label><b>Password</b></label>
                    <input id = "loginPassword"type = "password" placeholder = "Enter Password" class = "profile" required>
                    <label>
                        <input type = "checkbox" checked = "checked" name = "cookies"> Remember me
                    </label>
                </div>
                <div class = "container" style = "background-color:#f1f1f1; overflow:auto;">
                    <button type = "submit"style = "background-color: #4CAF50;
                                                color: white;
                                                padding: 14px 20px;
                                                margin: 8px 0;
                                                border: none;
                                                cursor: pointer;
                                                width: 100%;">Login</button>
                    <button type = "button" onclick = "document.getElementById('id02').style.display='none'" class = "cancelLoginbtn loginButton">Cancel</button>
                    <span class = "psw">Forgot <a href = "#">password?</a></span>
                </div>
            </form>
        </div>
        <div id = "id04" class = "modal" style = "padding-top: 50px;">
            <form id = "changeInfoForm"class = "modal-content animate">
                <div class = "imgcontainer">
                    <?php
                        if (isset($_COOKIE['profilepic'])){
                            echo "<span onclick = " . '"document.getElementById(' . "'id04').style.display='none' " .  '" class = "close" title = "Close Modal">&times;</span>
                                <label for = "fileToUpload">
                                    <img src = "players/'. $_COOKIE['username']. '/' . $_COOKIE['profilepic'] . '" alt = "Avatar" class = "avatar" id = "img">
                                </label>
                                <input type = "file" name = "fileToUpload" id = "fileToUpload">';
                        }else{
                            echo "<span onclick = " . '"document.getElementById(' . "'id04').style.display='none' " .  '" class = "close" title = "Close Modal">&times;</span>
                                <label for = "fileToUpload">
                                    <img src = "images/loginformimg.png" alt = "Avatar" class = "avatar">
                                </label>
                                <input type = "file" name = "fileToUpload" id = "fileToUpload">';
                        }
                    ?>
                </div>
                <div class = "container">
                    <label>
                        <b>Username:</b> <input id=changeusername class = "profile" name = "username"value = <?php echo $_COOKIE['username'];?>>
                    </label>
                    <br>
                    <label>
                        <b>Email:</b> <input id=changeemail class = "profile" name = "email"value = <?php if (isset($_COOKIE['email'])){ echo $_COOKIE['email']; } ?>>
                    </label>
                    <br>
                    <label>
                        <b>New Password:</b> <input id = "changerepassword"type = "password" name = "password"class = "profile" >
                    </label>
                    <br>
                    <label>
                        <b>Current Password:</b> <input id=changepassword type = "password" name = "new-password"class = "profile" required>
                    </label>
                    <br>
                </div>
                <div class = "container" style = "background-color:#f1f1f1; overflow:auto;">
                    <input type = "submit"style = "background-color: #4CAF50;
                                                color: white;
                                                padding: 14px 20px;
                                                margin: 8px 0;
                                                border: none;
                                                cursor: pointer;
                                                width: 100%;" value = "Change Profile Info"name = "submit">
                    <button type = "button" onclick = "document.getElementById('id04').style.display='none'" class = "cancelLoginbtn loginButton">Cancel</button>
                    <span class = "psw"><a id = "logout"onclick = "logout()">Logout</a></span>
                </div>
            </form>
        </div>
        <script src = "profile.js"></script>
        <?php include 'selectimage.php'?>
        <h1>Welcome to MegaLords</h1>
        <p>MegaLords is a place where mortals can become gods, and fallen gods can become true gods once more. Becoming a god is a very difficult process, and cannot be explained. Contact me if you wish to become a god.
            <h4>Requirements</h4>
            <ul>
                <li>You must have beaten the game</li>
                <li>You must be a mortal or fallen god</li>
                <li>You must be weaker than a lower god</li>
                <li>You cannot be a mythical creature, but we are looking for mythical creatures</li>
            </ul>
            <h4>Instructions</h4>
            <ol>
                <li>Beat the game</li>
                <li>The Owner will immediately contact you, if not contact them</li>
                <li>The Owner will grant you goddhood</li>
            </ol>
        </p>
        <footer>
            <p>Posted by: Electrox</p>
            <p>Contact information: <a href = "mailto:[email protected]">[email protected]</a>.</p>
        </footer>
    </body>
</html>

Это сайт

https://omegalords.ga/

Это js

if (window.location.href == "http://megalords.000webhostapp.com"){
            window.location.href = "https://megalords.000webhostapp.com"
        }else {
            console.info(window.location.href)
        }
        // Get the modal
        var modalLogin = document.getElementById('id02');
        var modalSignUp = document.getElementById('id01');
        var modalProfile = document.getElementById('id04');
        var loginUsername = document.getElementById("loginUsername");
        var loginPassword = document.getElementById("loginPassword");
        var loginform = document.getElementById("loginform");
        var signUpEmail = document.getElementById("signUpEmail");
        var signUpUsername = document.getElementById("signUpUsername");
        var signUpPassword = document.getElementById("signUpPassword");
        var signUpRePassword = document.getElementById("passwordRepeat");
        var signUpForm = document.getElementById("signUpForm");
        var changeInfoUsername = document.getElementById("changeusername")
        var changeInfoEmail = document.getElementById("changeemail")
        var changeInfoPassword = document.getElementById("changepassword")
        var changeInfoRePassword = document.getElementById("changerepassword")
        var changeInfoForm = document.getElementById("changeInfoForm")
        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == modalLogin) {
                modalLogin.style.display = "none";
            }else if (event.target == modalSignUp) {
                modalSignUp.style.dis4play = "none";
            }else if (event.target == modalProfile){
                modalProfile.style.display = "none";
            }
        }
        var style = document.createElement('style');
        var topnav = document.getElementsByClassName('topnav')[0];
        var percent = 1/topnav.childElementCount * 100;

        style.innerHTML += ".topnav a, button{float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; BORDER: none; width: " + percent + "%; }"
        document.getElementsByTagName('head')[0].appendChild(style);
        var getEmail = function(){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function(){
                if (this.readyState === 4 && this.status === 200){
                    if (this.responseText == "Please Refresh"){
                        location.reload();
                    }else {
                        return;
                    }
                }else if (this.status == 404 || this.readyState === 0 || this.status == 404 && this.readyState === 0){
                    document.body.innerHTML = "File Not Found"
                }
            }
            xhttp.open("GET", "getemail.php", true)
            xhttp.send()
        }
        var getProfilepic = function(){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function(){
                if (this.readyState == 4  && this.status == 200){
                    if (this.responseText == "Please Refresh"){
                        location.reload();
                    }else if (this.responseText == "Your Account is Broken. The Dev Has Been Notified"){
                        document.body.innerHTML += this.responseText
                    }else if (this.responseText == "No Profile Picture Found"){
                        var confirmation = confirm("Would You like to Set a Profile picture?");
                        if (confirmation === true){
                            modalProfile.style.display = "block"
                        }
                    }
                }
            }
            xhttp.open("GET", 'getprofileimage.php', true)
            xhttp.send()
        }
        var signUp = function(event){
            event.preventDefault();
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function(){
                if (this.readyState == 4 && this.status == 200){
                    if (this.responseText == "        Sign Up Complete"){
                        location.reload();
                    }else{
                        if (this.responseText == "No"){
                            document.getElementById("errusra").innerHTML = this.responseText;
                        }else{
                            switch(this.responseText){
                                case "        *That Username Is Taken":
                                    document.getElementById("errusra").innerHTML = this.responseText;
                                    document.getElementById("erremaila").innerHTML = "";
                                    document.getElementById("errpswa").innerHTML = "";
                                    document.getElementById("errrepswa").innerHTML = "";
                                    break;
                                case "        *You may only have letters and numbers as a username":
                                    document.getElementById("errusra").innerHTML = this.responseText;
                                    document.getElementById("erremaila").innerHTML = "";
                                    document.getElementById("errpswa").innerHTML = "";
                                    document.getElementById("errrepswa").innerHTML = "";
                                    break;
                                case "        *You must have between 2 and 8 characters as username":
                                    document.getElementById("errusra").innerHTML = this.responseText;
                                    document.getElementById("erremaila").innerHTML = "";
                                    document.getElementById("errpswa").innerHTML = "";
                                    document.getElementById("errrepswa").innerHTML = "";
                                    break;
                                case "        *Invalid email":
                                    document.getElementById("erremaila").innerHTML = this.responseText;
                                    document.getElementById("errusra").innerHTML = "";
                                    document.getElementById("errpswa").innerHTML = "";
                                    document.getElementById("errrepswa").innerHTML = "";
                                    break;
                                case "        *You must have at least one lowercase, uppercase, and a number as a password":
                                    document.getElementById("errpswa").innerHTML = this.responseText;
                                    document.getElementById("errusra").innerHTML = "";
                                    document.getElementById("erremaila").innerHTML = "";
                                    document.getElementById("errrepswa").innerHTML = "";
                                    break;
                                case "        *You may only have between 3 and 12 characters as password":
                                    document.getElementById("errpswa").innerHTML = this.responseText;
                                    document.getElementById("errusra").innerHTML = "";
                                    document.getElementById("erremaila").innerHTML = "";
                                    document.getElementById("errrepswa").innerHTML = "";
                                    break;
                                case "        *Passwords do not match":
                                    document.getElementById("errrepswa").innerHTML = this.responseText;
                                    document.getElementById("errusra").innerHTML = "";
                                    document.getElementById("erremaila").innerHTML = "";
                                    document.getElementById("errpswa").innerHTML = "";
                                    break;
                                default:
                                    document.body.innerHTML =this.responseText
                                    console.info(this.responseText)
                            }
                        }
                    }
                }
            }
            xhttp.open("GET",'checkregister.php?eml=' + signUpEmail.value + '&usrnm=' + signUpUsername.value + '&psw=' + signUpPassword.value + '&repsw='+ signUpRePassword.value,true);
            xhttp.send();
        }
        var login = function(event){
                event.preventDefault();
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function(){
                    if (this.readyState == 4 && this.status == 200){
                        if (this.responseText == "Login Successful!"){
                            location.reload();
                        }else{
                            modalLogin.style.display = "block";
                            console.info(this.responseText)
                            document.getElementById("loginerr").innerHTML = this.responseText;
                        }
                    }
                }
                xhttp.open("GET",'checklogin.php?usrnm=' + loginUsername.value + '&psw=' + loginPassword.value,true)
                xhttp.send();
        }
        var logout = function(){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function(){
                if (this.readyState == 4 && this.status == 200){
                    location.reload();
                }
            }
            xhttp.open("GET",'logout.php', true);
            xhttp.send();
        }
        var changeInfo = function(event){
            event.preventDefault();
            var xhttp = new XMLHttpRequest();
            window.wormData = new FormData();
            var file = document.getElementById("fileToUpload").files[0];
            wormData.append('fileToUpload', file)
            wormData.append('username',changeInfoUsername.value);
            wormData.append('email',changeInfoEmail.value);
            wormData.append('password',changeInfoPassword.value);
            if (!(changeInfoRePassword.value == "")){
                wormData.append('new-password',changeInfoRePassword.value)
            }

            xhttp.onreadystatechange = function(){
                if (this.readyState == 4 && this.status == 200){
                    console.info(this.responseText)
                }
            }
            xhttp.open("POST","changeinfo.php",true);
            xhttp.send(wormData);
        }
        signUpForm.addEventListener('submit',signUp);
        loginform.addEventListener('submit',login);
        changeInfoForm.addEventListener('submit',changeInfo);
        getEmail();
        getProfilepic();

Это php

<?php
    include 'templates/connect.php';
    if (isset($_POST['username'])){
        $username = $_POST['username'];
    }
    if (isset($_POST['email'])){
        $email = $_POST['email'];
    }
    if (isset($_POST['password'])){
        $password = $_POST['password'];
    }
    if (isset($_POST["new-password"])){
        $newpassword = $_POST["new-password"];
    }
    $currusername = $_COOKIE['username'];
    $query = "SELECT * FROM `Users`
            WHERE `username` = '$currusername' AND `psw` = '$password';";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_row($result);
    $id = $row[0];
    //echo $row[3];
    if (!$result || mysqli_num_rows($result) === 0){
        echo $username . $password;
    }else{
        if ($row[1] === $username){
            if ($row[3] === $email || $email == ""){
                if (isset($newpassword)){
                    $query = "UPDATE `Users` SET `psw` = '$newpassword' WHERE `id` = '$id';";
                    echo $query;
                    $result = mysqli_query($conn, $query);
                }else {
                    echo "Everything is the same";
                }
            }
        }else if (isset($email)){
            if (isset($newpassword)){
                $query = "UPDATE `Users` SET `username` = '$username' WHERE id = '$id';
                        UPDATE `Users` SET `password` = '$newpassword' WHERE `id` = '$id';";
                rename('players/' . $row[1], 'players/' . $username);
                $result = mysqli_query($conn, $query);
            }
        }else if (isset($newpassword)){
            $query = "UPDATE `Users` SET `username` = '$username' WHERE id = '$id';
                    UPDATE `Users` SET `email` = '$email' WHERE id = '$id';
                    UPDATE `Users` SET `password` = '$newpassword' WHERE `id` = '$id';";
            $result = mysqli_query($conn, $query);
            rename('players/' . $row[1], 'players/' . $username);
        }else {
            echo "Everything is the same";
        }
    }
    foreach($_FILES as $data){
        echo $data[name];
    }
    if (isset($_FILES['fileToUpload'])){
        $target_dir = "players/". $_COOKIE['username'] . "/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        // Check if image file is a actual image or fake image
        if (file_exists($_FILES['fileToUpload']['tmp_name']) || is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if ($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
        // Check if file already exists
        if (file_exists($target_file)) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
        // Check file size
        if ($_FILES["fileToUpload"]["size"] > 500000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }
        // Allow certain file formats
        if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                echo basename( $_FILES["fileToUpload"]["name"]);
                $query = "UPDATE `Users` SET `userimage` = '". $_FILES["fileToUpload"]["name"] . "' WHERE `username` = '$currusername'";
                unlink("players/$row[1]/$row[5]");
                $result = mysqli_query($conn, $query);
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
    }
    }
?>

Это просто «тестовый код», верно? Вы не планируете оставлять все это совершенно незащищенным, просто вставьте какой-то пользовательский ввод в базу данных, код будет работать в течение любого промежутка времени?

gforce301 05.06.2018 18:12

Не могли бы вы объяснить, что вы имеете в виду? У меня сложилось впечатление, что, пока у кого-то нет пароля к базе данных, они не могут войти в базу данных?

Electrox Qui Mortem 05.06.2018 18:36

Да, это тестовый код. Я все же хотел бы знать, что не так в приведенном выше коде.

Electrox Qui Mortem 05.06.2018 19:12

Поместите этот атрибут в тег формы enctype = "multipart / form-data".

nicolascolman 05.06.2018 19:14

Это работает. Кстати, это ответ, а не комментарий @nicolascolman

Electrox Qui Mortem 05.06.2018 19:19

«Я все же хотел бы знать, что не так в приведенном выше коде». Вы имеете в виду, кроме двух явно очевидных вещей, о которых я уже упоминал, простых текстовых паролей в базе данных и уязвимости SQL-инъекций? Вы даже потрудились исследовать что-либо из них?

gforce301 05.06.2018 19:39

Конечно, я сделал. Я так и делаю сейчас. Почему ты спрашиваешь???

Electrox Qui Mortem 05.06.2018 19:41

Потому что вы сделали это заявление? «Я все же хотел бы знать, что не так в приведенном выше коде». Не очень хорошо с языком, да?

gforce301 05.06.2018 19:42

Так вы говорите, что когда я сказал: «Что не так с приведенным выше кодом?», Вы не поняли, что я имел в виду исходный вопрос, который задал?

Electrox Qui Mortem 05.06.2018 19:49

Почему каждый раз, когда я задаю вопрос или отвечаю на него, я вижу вас, и это плохо заканчивается?

Electrox Qui Mortem 05.06.2018 19:50

@ electrox-qui-mortem Я рада, что это помогло.

nicolascolman 05.06.2018 19:51
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
11
86
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вы должны установить атрибут enctype в своей форме, чтобы сервер мог читать файл.

<form id = "changeInfoForm" class = "modal-content animate" enctype = "multipart/form-data">

Другие вопросы по теме