简体   繁体   English

如何将JavaScript变量发布到PHP文件以分配给PHP变量?

[英]How to post a javascript variable to a PHP file to assign to a PHP variable?

I have a webpage with several images. 我的网页上有几张图片。 Each image can be replaced by an other image on the same place. 每个图像都可以用同一位置上的其他图像替换。 Next to each image there is a form to upload the new image. 每个图像旁边都有一个用于上载新图像的表单。 Important is that the new filename must be replaced with a fixed name eg.: cat.jpg becomes image1.jpg , dog.jpg becomes image5.jpg , depending on the form used. 重要的是,新文件名必须用固定名称替换,例如: cat.jpg变为image1.jpgdog.jpg变为image5.jpg ,具体取决于所使用的格式。 I use this html code for a first image: 我将以下html代码用于第一张图片:

 <div class="w3-padding-8 w3-card-8 w3-center w3-third w3-container ">
                <div class="w3-padding-8 w3-card-8 w3-center w3-container"><img src="images/cat.jpg" class="w3-padding-8 style="width:100%"></div>
                <div class="w3-center w3-container">
                    <form method="POST" action="upload4.php" enctype="multipart/form-data">
                        <input type="file" multiple name="file[]" data-maxfilesize="5000000">
                        <input class="button-primary" type="submit" value="Submit 1">
                    </form>
                </div>
            </div>

In the upload4.php I have this code to receive the new file. 在upload4.php中,我有这段代码来接收新文件。 Now it assigns the name images/image1.jpg to it but I need a variable with the new filename in it. 现在,它为其分配了名称images/image1.jpg ,但是我需要一个带有新文件名的变量。

<?php 
$sentfile = 'images/image1.jpg';
if (is_array($_FILES['file']['name'])) {
    foreach($_FILES['file']['name'] as $k=>$filename) {
        $uploadfile = $sentfile;
        if (move_uploaded_file($_FILES['file']['tmp_name'][$k], $uploadfile)) {
            // ok
        } else {
            $error_message.= "Error while uploading file ".$filename."<br />";
        }
    }
} elseif(isset($_FILES['file']['name'])) {
    $uploadfile = $sentfile;
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
        // ok
    } else {
        $error_message = "Error while uploading file ".$_FILES['file']['name']."<br />";
    }
}
?>

How do I assign images/image1.jpg to $sentfile ? 如何将images/image1.jpg分配给$sentfile I think I need AJAX ? 我想我需要AJAX吗? But how? 但是如何? I know Javascript is client-side and php is serverside but how to communicate... 我知道Javascript是客户端,而php是服务器端,但是如何进行通信...

If i have understood correctly your question, what you are asking is to add a name to the image uploaded depending on the form used. 如果我正确理解了您的问题,您要问的是根据所使用的表单在上传的图像中添加一个名称。

You could add 您可以添加

<input type="hidden" value="here goes the desired name of the image" name="desired name">

and then get the value through $_POST['desired_name'] . 然后通过$_POST['desired_name']获取值。

You wont need ajax for this 您不需要为此的ajax

First change the input tag to look like below: 首先将输入标签更改为如下所示:

<input type="file" onchange="getNewName_one(this.value)" multiple name="file[]" data-maxfilesize="5000000">

Then your create a function in JS: 然后在JS中创建一个函数:

<script>
function getNewName_one(str) {
  var break_path = str.split('\\');  // make sure the \\ is actually two inorder for it to work
  var len = break_path.length - 1;  // we need to get the last entry of the loop
  var filename = break_path[len]; // filename contains only the filename now;
  document.cookie = "newImageName_one="+filename;
}
</script>

Then update the php now 然后立即更新php

<?php 

$sentfile = $_COOKIE['newImageName_one'];  
?>

If your are having problems with the filename itself; 如果您的文件名本身有问题; like your are getting some wierd names in the input type="file" just comment it. 就像您在输入type =“ file”中得到一些奇怪的名称一样,只需对其进行注释。 Thank you. 谢谢。

The new form: 新表格:

<form>
    <input type="file" onchange="changeFile(this.value)" name="file[]" />
</form>

The JS: JS:

<script>
    function changeFile(val) {

    var break_path = val.split('\\');
    var len = break_path.length - 1; 
    var filename = break_path[len];

    var ajaxCall = new XMLHttPRequest();
    ajaxCall.onreadystatechange = function(){
          if (ajaxCall.readyState === 4 && ajaxCall.status === 200) {
             var response = ajaxCall.responseText;
          }
      };


      ajaxCall.open("GET", "upload.php?fileName="+filename, true);
      ajaxCall.send();
    }
</script>

** you can use only one file upload.php *** **您只能使用一个文件upload.php ***

Then in the upload.php file: 然后在upload.php文件中:

<?php

if(isset($_GET['filename'])) {

$sentfile = $_GET['filename'];

}
if (is_array($_FILES['file']['name'])) {
  foreach($_FILES['file']['name'] as $k=>$filename) {
    $uploadfile = $sentfile;
    if (move_uploaded_file($_FILES['file']['tmp_name'][$k], $uploadfile)) {
        // ok
    } else {
        $error_message.= "Error while uploading file ".$filename."<br />";
    }
   }
} elseif(isset($_FILES['file']['name'])) {
$uploadfile = $sentfile;
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    // ok
} else {
    $error_message = "Error while uploading file ".$_FILES['file']['name']."<br />";
}
}

if($error_message != '') {
    echo 'Image Uploaded';
} else {
    echo $error_message;
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM