0

Hey guys I was practicing PHP and I am stuck.

I have an HTML file where I used the JS fetch function to take the user's email id and send it to register.php, which checks whether this email is saved in db or not.

If not, it will save it into db, and I have to verify it by sending a email to that email id. Soo what I have done is write code for sending a verification mail in register.php, but as register.php is kind of an API, executing mail verification functionality will timeout on the js side. So my question is: is there any way such that i write mail verification functionality in another PHP file, which executes if there is no email address stored in DB, with register.php triggering that file?

I thought about having js trigger the other php file once register.php responds, but I don't want to do that. If anyone has any keywords on which I can research to do this task that's also fine.

My html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XKCD Subscription</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1 class="main-heading">XKCD WebComics</h1>
    </header>
    <section class="split-2">
        <section class="section-left">
            <p class="sub-heading">Subscribe to our XKCD webcomics</p>
            <p class="pera">XKCD Subscription provides you the best webcomic at your mailbox every five minutes. So enjoy the free days with some of the best comics ever</p>
            <p class="pera">To get this Subscription please fillout the form given below</p>
            <form id="form">
                <input type="email" name="user_email" id="userEmail" placeholder="E-mail here">
                <input type="submit" value="Subscribe" id="submitButton">
            </form>
        </section>
        <div class="vr-line"></div>
        <section class="section-right">
            <h3  class="sub-heading">Some Pinned XKCD's comics</h3>
            <div class="box-arr">
                <div class="selected-img s1"><a class="hov-vis" href="https://xkcd.com/688" target="_blank">self_description</a></div>
                <div class="selected-img s2"><a class="hov-vis" href="https://xkcd.com/150" target="_blank">grownups</a></div>
                <div class="selected-img s3"><a class="hov-vis" href="https://xkcd.com/162" target="_blank">angular_momentum</a></div>
                <div class="selected-img s4"><a class="hov-vis" href="https://xkcd.com/730" target="_blank">circuit_diagram</a></div>
            </div>
            <p class="pera">*Images are clickable</p>
        </section>
    </section>
    <script>
        let mailFeild = document.getElementById("userEmail");
        let submit = document.getElementById("submitButton");
        submit.setAttribute("disabled","");
        mailFeild.addEventListener("keyup",function(event){
            if(!mailFeild.value){
                submit.setAttribute("disabled","");
            }else{
                submit.removeAttribute("disabled");        
            }
        })
        submit.addEventListener("click",function(event){
            event.preventDefault();
            fetch("http://localhost:8080/RTC_v2/public/registrar.php",
            {
                method:"POST",
                body: JSON.stringify({
                   "user_email" : mailFeild.value,
                }),
                headers:{
                    "Content-type":"application/json",
                }
            })
            .then((response)=> {return response.json()})
            .then((data)=>{
                alert(data['message']);
                document.getElementById("form").reset();
            })
            .catch((err)=>console.log(err))
        });
    </script>
</body>
</html>

The register.php file:

<?php
    header('Content-type: application/json');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Headers: Content-type,Access-Control-Allow-Origin,Access-Control-Allow-Methods');

    require dirname(__DIR__).'/_private/definations.php';
    $recieved = file_get_contents('php://input');
    $recieved = json_decode($recieved,true);
    $message = '';
    $success = false;
    $input_email = $recieved['user_email'];
    if(isset($input_email)){
        if($input_email){
            if($input_email == htmlentities($input_email,ENT_QUOTES)){
                if(filter_var($input_email,FILTER_VALIDATE_EMAIL)){
                    if($input_email ==  filter_var($input_email, FILTER_SANITIZE_EMAIL)){
                        if(!searchEmailIntoDB($input_email)){
                            if(putEmailIntoDB($input_email)){
                                $message = "$input_email is subscribed successfully";
                                $success = true;
                            }else{
                                $message = 'we are facing issues\nplease try again later';
                                reportIssue();
                            }
                        }else{
                            $message = "$input_email is already subscribed";
                        }
                    }else{
                        $message = 'Please remove special characters from your email id\n-except @ ';
                    }
                }else{
                    $message = 'Please enter valid Email Address ';
                }
            }else{
                $message = 'Please remove following characters from your email id\n <,>,",\',&';
                }
        }else{
            $message = 'Email feild can not be empty';
        }
    }
    $ret = [
            'message' => $message
            ];
    echo json_encode($ret);

    require dirname(__DIR__).'/_private/Email.php';
    $subject = 'Email verification for XKCD webComics';
    mailer($input_email,$subject,$body);
    
?>

(see the echo, below echo statements - all the code is for mail verification leads to timeouts, which I want to move in another php file so that it runs independently)

Tony Stark
  • 111
  • 1
  • 7
  • Please post relevant code snippets from your HTML file as well as your register.php file. – AndrewL64 May 28 '22 at 18:06
  • Done Sir,,,,,,, – Tony Stark May 28 '22 at 18:15
  • The general flow is: (1) user registers, (2) your code creates their account, marked as "pending" (so they can't log in yet) and sends a verification email. (3) that email has a link that opens a URL to a different PHP file that simply goes into the database, and marks the user as "active" rather than pending. Now their login will work. So your `register.php` should accept the user's email, check the db and either go "you're already registered" or create a new record with a verification id, then run `sendmail` with the a link to `verify.php?code=......` and you get to write that `verify.php`. – Mike 'Pomax' Kamermans May 28 '22 at 18:35
  • Does this answer your question? [Echo messages while php script still executes](https://stackoverflow.com/questions/4669822/echo-messages-while-php-script-still-executes) – JoelCrypto May 28 '22 at 18:37
  • but _even better_ is to not write your own user management software, because you're going to bake security exploits into your code through no fault of your own: you're new to programming, and you don't know everything there is to know about PHP exploiting. Well-tested libraries for user management protect you from those problems. – Mike 'Pomax' Kamermans May 28 '22 at 18:38
  • Don't do nested if-else ... nobody will understand the code in 2 days from now – helle May 28 '22 at 20:10
  • They are just steps of checking malicious inputs ignore it and consider it as if data not found it will save the data (inner most if) or return data found (second inner most else) – Tony Stark May 29 '22 at 02:59
  • @JoelCrypto no sir it does not work for me it still takes around 4.7s what I was asking is, is there any way to send some sort of triggering message from register.php so that another php file starts to executing? – Tony Stark May 29 '22 at 05:16

0 Answers0