Home > Back-end >  How to add input value to URL in php
How to add input value to URL in php

Time:10-25

I have a question from php and I'm not expert in php.

1.I have html page with one form include a text box and submit button .

2.I have a static target url like this : https://example.com/invoice/XXXXXXXXXXXXXX

XXXXXXXXXXXXXX is just numbers and has 14 characters.

*** What I need is that my customer enter its 14 characters number in input text form and when it submit , goes to target url.I want to check input form for entry numbers too.

I make a sample form like this but not work:

        <form action="https://example.com/invoice"  method="get">
          <input type="text" id="peyid" name="peyid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="14" ><br><br>
          <input type="submit" value="submit">
        </form>

What can I do?

CodePudding user response:

As hassan said , you can do this only with javascript. This will redirect to the url what you desired.

document.querySelector("form").onsubmit = function(){
    this.setAttribute("action",this.getAttribute("action") "/" document.querySelector("[name=peyid]").value);
}

For example If document.querySelector("[name=peyid]").value = 12345678901234 The url will look like https://example.com/invoice/12345678901234?peyid=12345678901234

So if you just need to redirect to that url you don't even need form just

<input type="text" id="peyid" name="peyid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="14" ><br><br>
<input type="button" value="submit">

<script>
    document.querySelector("[type=button]").onclick = function(){
        location.href = `https://example.com/invoice/${document.querySelector("[name=peyid]").value}`;
    }
</script>

CodePudding user response:

Using PHP—to receive a form value, validate it, apply it to a URL, and redirect the client to that location, use $_POST, preg_match(), and header().

https://example.com/invoice/index.php:

<?php

if ( isset($_POST['peyid']) && preg_match("/^\d{14}$/", $_POST['peyid']) ) {

    header("Location: http://www.example.com/invoice/{$_POST['peyid']}");
    exit;

}

?>
<html><head><title>oops</title></head><body>An error occurred.</body></html>
  • Related