php 在 onsubmit 内部时在页面加载时激活

php Activating On Page Load While Inside Of onsubmit

我有一个 php 函数可以在提交表单时在目录中创建一个文件。 代码是:

<form id="myForm" onSubmit="<?php
    error_reporting(E_ALL);
    $directory = __DIR__ . "/images/"; $filecount = 0; $files = glob($directory . "*");  if ($files){ 
    $filecount = count($files); }
    $filecount = $filecount + 1;
    $pagename = 'image_'.$filecount;

    $newFileName = './images/'.$pagename;
    $newFileContent = 'Page Content';
    if (file_put_contents($newFileName, $newFileContent) !== false) {
    echo "File created (" . basename($newFileName) . ")";
    } else {
    echo "Cannot create file (" . basename($newFileName) . ")";
    }
?>">
       <input placeholder="Username 0/25" name="user" id="user" maxlength="25" required>
       <input placeholder="Password 0/45" name="password" id="password" maxlength="45" required>
       <input placeholder="Image Name" name="name" id="name">
       <input type="file" placeholder="Image" accept="image/*" name="img" required>
       <button type="submit">Upload</button>
       </form>

问题是它在页面加载时自动激活..有没有办法解决这个问题

The problem is that it auto activates on page load

要防止在您按下提交时自动加载页面,您可以使用这个技巧 "return false; \"..." 但它不会创建图像文件:/只是停止页面操作。

    if (file_put_contents($newFileName, $newFileContent) !== false) {
    echo "return false; \"File created (" . basename($newFileName) . ")";
    } else {
    echo "return false; \" Cannot create file (" . basename($newFileName) . ")";
    }

我试图模仿你的项目,但我使用的是 txt 文件而不是图像。 我用了 AJAX

index.html

<html>
    <body>
      <form id="myForm">
            <button type="submit">create a file</button>
       </form>
       <script src="script.js"></script>
    </body>
</html>

script.js

document.getElementById('myForm').onsubmit = function(e){
  e.preventDefault();
  var xhr = new XMLHttpRequest();
  xhr.open('GET','creating.php');
  xhr.onreadystatechange = function(){
    console.log(xhr.readyState)
    if(xhr.readyState == XMLHttpRequest.DONE)
        if(xhr.response.startsWith('Woow'))
          alert('File created successfully!');
        else
          alert('Something went wrong!');
  }
  xhr.send();
}

creating.php

<?php
    $directory = __DIR__ . "/files/";
    $filecount = count(glob($directory . "*")) + 1;
    
    $newFileName = $directory.'txt_'.$filecount.'.txt';
    $newFileContent = "some text... in a file number $filecount.";
    
    if(file_put_contents($newFileName, $newFileContent))
        echo "Woow!";
    else
        echo "Oups!";
?>