为什么这个PHP代码在从用户输入创建动态链接时第二次运行正常?

I am trying to create a query screen for reports. I have created a php code by getting support from here and other sites. But the problem is; when a user input report serial number and submits it, the page only reload. After reload; when the user enters serial again to the field and hits submit, this time the code works but only for the 1st serial entered, no matter the second serial is.

I have tried to change the parts of my code but could not find a solution.

I am trying to create a system like, user will enter a serial to the field and when hits to submit button; a new window pop out and directs user to a link which has been created based on user input.

For example, user entered "234" as the serial number and hit submit button. The new window will go to the; "example.com/reports/report234.pdf"

Here is the code I have problem with;

<?php
if(isset($_POST['submit']))
{
    $seri = $_POST['seri'];
    $url = "https://www.example.com/wp-content/uploads/Rapor/".$seri.".pdf";    
}
?>
<form method="post" action="<?php echo $url; ?>">
    <input type="text" name="seri"><br>
    <input type="submit" name="submit" value="Sorgula"><br>
</form>

That's because you're setting the redirect $url as the form action. That results in the following:

  1. Form action is empty, thus the form will be sent to the page itself
  2. The serial number and the $url is created and set as the form action
  3. Now when the user submits the form again it will be directed to the $url set, regardless of what he has filled in the seri field this time

Here is an example of a more correct approach to your problem:

<?php
if(isset($_POST['submit']))
{
    $seri = $_POST['seri'];
    Header("Location: https://www.ozguncicek.com.tr/wp-content/uploads/Rapor/$seri.pdf");
}
?>
<form method="post">
    <input type="text" name="seri"><br>
    <input type="submit" name="submit" value="Sorgula"><br>
</form>

Note there's no need to set an action to the form since you're going to redirect the user when he submits the form.

Another important point is checking if seri isn't empty before redirecting the user. That could be accomplished as simple as:

<?php
    if(isset($_POST['submit']) && $_POST['seri'])

Redirect after form submit,

<?php
if(isset($_POST['submit']))
{
    $seri = $_POST['seri'];
    $url = "https://www.example.com/wp-content/uploads/Rapor/".$seri.".pdf";     
    header("Location: ".$url);   
}
?>
<form method="post" action="<?php echo $url; ?>">
    <input type="text" name="seri"><br>
    <input type="submit" name="submit" value="Sorgula"><br>
</form>