PHP + iframe upload file function example

Time:2021-5-11

In this paper, an example of PHP + iframe to achieve the function of uploading files. The details are as follows:

We create iframe dynamically and modify the target of the form to achieve file upload without jump.

Specific implementation steps

1. Capture form submission events
2. Create an iframe
3. Modify the target of the form and point to iframe
4. Delete iframe

The code of file.html is as follows:

<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
 <meta charset="UTF-8">
 <title></title>
</head>
<body>
 <form action="upfile.php" method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
  < input type = submit "name = submit" value = upload / >
 </form>
 <div></div>
</body>
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript">
$("#upfileForm").bind("submit", function() {
 var ifrName = 'upfile' + Math.random();
 var ifr = $("<iframe name='" + ifrName + "' width='0' height='0' frameborder='0'></iframe>");
 $("body").append(ifr);
 $(this).attr("target", ifrName);
});
</script>
</html>

The code of upfile.php is as follows:


<?php
$uploadDir = './upload/';
if(!file_exists($uploadDir)) {
  @mkdir($uploadDir, 0777, true);
}
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
  echo "<script>parent.document.getElementById('result').innerHTML='OK';</script>";
} else {
  echo "<script>parent.document.getElementById('result').innerHTML='NO';</script>";
}

More about PHP related content, interested readers can see the site topic: “PHP file operation summary”, “PHP directory operation skills summary”, “PHP commonly used traversal algorithm and skills summary”, “PHP data structure and algorithm tutorial”, “PHP programming algorithm summary” and “PHP network programming skills summary”

I hope this article is helpful for PHP programming.