2015-09-19 135 views
0

基本上我正在尝试做的是 - 创建一个页面来上传文件。下面是代码及其工作罚款:如何从javascript中调用php函数

<!DOCTYPE html> 
    <html> 
    <head> 
    <script type="text/javascript"> 
      function wow_default_alert() {alert("Successfully saved!"); } 
     </script> 
    </head> 
    <body> 

    <form action="index.php" method="post" name="myForm" enctype="multipart/form-data"> 
     Select image to upload: 
     <input type="file" name="fileToUpload" id="fileToUpload"> 
     <input type="submit" value="Upload Image" name="submit"> 
    </form> 

    <?php 

     if(isset($_POST["submit"])) { 
      if (!file_exists('.\\tigerimg\\')) 
      { 
       mkdir('.\\tigerimg\\', 0777, true); 
      } 
      $target_dir = '.\\tigerimg\\'; 
      $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
      $uploadOk = 1; 
      $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
      // Check if image file is a actual image or fake image 


       $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
       if($check !== false) { 
        "File is an image - " . $check["mime"] . "."; 
        $uploadOk = 1; 
       } else { 
        "File is not an image."; 
        $uploadOk = 0; 
       } 

      // Check if file already exists 
      if (file_exists($target_file)) { 
       echo "Sorry, file already exists."; 
       $uploadOk = 0; 
      } 
      // Check file size 
      if ($_FILES["fileToUpload"]["size"] > 500000) { 
       echo "Sorry, your file is too large."; 
       $uploadOk = 0; 
      } 
      // Allow certain file formats 
      if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" 
      && $imageFileType != "gif") { 
       echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
       $uploadOk = 0; 
      } 
      // Check if $uploadOk is set to 0 by an error 
      if ($uploadOk == 0) { 
       echo "Sorry, your file was not uploaded."; 
      // if everything is ok, try to upload file 
      } else { 
       if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) 
       { 
       // echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
       echo '<script type="text/javascript"> 
         wow_default_alert(); 
         </script>'; 
       } else { 
        echo "Sorry, there was an error uploading your file."; 
       } 
      } 
     } 
    ?> 

但问题是,如果我再刷新页面-after成功上传一个文件,它的工作原理与同一职位的值。

以前我使用下面的代码来取消设置发布数据 - 这对其他页面起作用。

清晰代码1

<?php 
    session_start(); 

     if(strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) 
     { 
      $_SESSION['postdata'] = $_POST; 
      header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']); 
      exit; 
     } 

     if(isset($_SESSION['postdata'])) 
     { 
      $_POST = $_SESSION['postdata']; 
      unset($_SESSION['postdata']); 
     } 
    ?> 

,但我不能在这一个使用它。它显示错误:

Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 41 
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 47 
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\up\index.php on line 47 
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 62 

所以,我试图也清楚FILES阵列太通过添加3行与上面的代码。

清晰代码2

<?php 
    session_start(); 

     if(strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) 
     { 
      $_SESSION['postdata'] = $_POST; 
      $_SESSION['filedata'] = $_FILES; //new code 
      header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']); 
      exit; 
     } 

     if(isset($_SESSION['postdata'])) 
     { 
      $_POST = $_SESSION['postdata']; 
      $_FILES = $_SESSION['filedata']; //new 

      unset($_SESSION['postdata']); 
      unset($_SESSION['filedata']); //new 
     } 
    ?> 

,但现在它仅显示一个错误:

Warning: getimagesize(C:\xampp\tmp\php1A2F.tmp): failed to open stream: No such file or directory in C:\xampp\htdocs\up\index.php on line 51. 

>>>所以,这里是一个question-为什么会出现这种情况?

好了,现在我想另一种方式把上面的[清楚代码1] PHP函数功能remove_post()里面并调用它只是成功uploading-的代码后,在那里我叫警报。

这次它的工作正常。但现在问题是没有出现警报。那么,当用户单击alert中的ok时,是否可以调用remove_post()函数。

+0

你不能直接从客户端脚本调用PHP函数。如果你想要一个php函数的结果,你可以使用ajax来连接它。请记住,新的获取或发布是一个分离的过程。 – Codebeat

回答

1

它看起来像你试图复制OK来自W3Schools网站,这不是最好的地方。无论如何,在这种情况下,我想你可能想要做的所有的处理你的页面的顶部,像这样:

<?php 
// Not sure if you are storing anything in sessions... 
session_start(); 
// Create a root 
define("ROOT_DIR",__DIR__); 
// Create a function so you can customize it if you want to 
function SaveFileToDisk($dir = '/tigeimg/',$allow = array("image/png","image/jpeg","image/gif")) 
    { 
     // Make directory if not exists 
     if(!is_dir($mkdir = ROOT_DIR.$dir)) { 
       if(!mkdir($mkdir,0755,true)) 
        return 'mkdir'; 
      } 
     // Filter filename 
     $name  = preg_replace("/[^0-9a-zA-Z\.\_\-]/","",$_FILES["fileToUpload"]["name"]); 
     // Assign name 
     $filename = (!empty($name))? $name : false; 
     // If empty, record error 
     if(!$filename) 
      $error[] = 'nofile'; 
     // Get mime type 
     $mime = (!empty($_FILES["fileToUpload"]["tmp_name"]))? getimagesize($_FILES["fileToUpload"]["tmp_name"]) : false; 
     // Record if invalid 
     if(!$mime) 
      $error[] = 'invalid'; 
     // Filter out double forward slashes (if user decides to change $dir) 
     // and adds too many forward slashes 
     $final = str_replace("//","/",ROOT_DIR."/".$dir."/".$filename); 
     // If file exists, record error 
     if(is_file($final)) 
      $error[] = 'exists'; 
     // If too big record error 
     if($filename > 500000) 
      $error[] = 'size'; 
     // If not in the allowed file types, record error 
     if(!in_array($_FILES["fileToUpload"]["type"],$allow)) 
      $error[] = 'type'; 
     // Return array of errors 
     if(!empty($error)) 
      return $error; 
     // True or false if no errors are recorded previously 
     return (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$final)); 
    } 

// Just create a simple error returning function 
// This is expandable by adding error descriptions stored in database if desired 
function ErrorReporting($value = false) 
    { 
     $msg['invalid'] = "INVALID File!"; 
     $msg['type'] = "The file you are trying to upload is not a valid image type."; 
     $msg['exists'] = "The file you are trying to upload is already uploaded."; 
     $msg['size'] = "The file you are trying to upload is too large."; 
     $msg['nofile'] = "The file you are trying to upload has no name."; 

     if($value === true) 
      return "Successfully uploaded!"; 
     elseif(is_array($value)) { 
       foreach($value as $error) { 
         $err[] = (!empty($msg[$error]))? $msg[$error]:""; 
        } 

       if(!empty($err)) 
        return implode("",$err); 
      } 
     else 
      return "File failed to upload."; 
    } 

// If post is submitted 
if(isset($_POST["submit"])) 
    // Run the uploader function 
    $success = SaveFileToDisk(); 

?><!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript"> 
<?php 
    // if there is an upload, run the js alert 
    if(isset($success)) { 
?> 
function error_alert(errmsg) 
    { 
     alert(errmsg); 
    } 

error_alert("<?php echo ErrorReporting($success); ?>"); 
<?php } 
?> 
</script> 
</head> 
<body> 

<form action="" method="post" name="myForm" enctype="multipart/form-data"> 
    Select image to upload: 
    <input type="file" name="fileToUpload" id="fileToUpload"> 
    <input type="submit" value="Upload Image" name="submit"> 
</form> 
</body> 
</html> 
+0

很酷。抱歉,迟到的接受。它的工作完美,除了 - 当没有选择文件,点击提交按钮比显示错误。感谢代码:-) –

+0

出于好奇,它显示了什么错误? – Rasclatt

+0

对不起,我在一个不同的电脑atm。仍然运行代码和我发现的下面的错误:警告:getimagesize():文件名不能在C:\ xampp \ htdocs \ up \ index.php在第22行中为空.......如果我从那里刷新它显示 - 你想上传的文件没有名字。无效文件!。您尝试上传的文件不是有效的图像类型。 .........我会再次让你知道,当我回到家,坐在我的电脑上,看到我说的错误:-) –

0

用户后点击OK警报可以调用PHP函数作为

alert('Your alert'); 
document.write(' <?php remove_post(); ?> '); 

你remove_post()函数将调用用户点击后警报

+0

nope ..显示与清除代码相同的错误-1 –