在哪里将PHP代码放在下面的PHP脚本中

时间:2012-04-22 00:17:41

标签: php javascript jquery

我在下面有一个javascript变量,它假设从imageupload.php(一个单独的页面)中检索$_SESSION['imagename']

var imagename = <?php echo json_encode(isset($_SESSION['imagename']) ? $_SESSION['imagename'] : null); ?>;

但是我的问题是我在哪里将这段代码放在php脚本中,以便会话变量包含文件名,并且能够通过上面的变量检索?

if (isset($_POST['fileImage'])) { // fileImage is the name of the file input
  $_SESSION['imagename'] =  $_FILES['fileImage']['name'];
}

$_SESSION['fileImage']['name'] = $_FILES['fileImage']['name'];

下面是php脚本:

$result = 0;

if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {  

    $parts = explode(".",$_FILES['fileImage']['name']);
    $ext = array_pop($parts);
    $base = implode(".",$parts);
    $n = 2;

    while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
    $_FILES['fileImage']['name'] = $base."_".$n.".".$ext;

    move_uploaded_file($_FILES["fileImage"]["tmp_name"], 
    "ImageFiles/" . $_FILES["fileImage"]["name"]);
    $result = 1;

}
    else
      {
      move_uploaded_file($_FILES["fileImage"]["tmp_name"],
      "ImageFiles/" . $_FILES["fileImage"]["name"]);
      $result = 1;


      }

?>

<script language="javascript" type="text/javascript">
window.top.stopImageUpload(<?php echo "'$result'";?>); // call backs javascript function
</script>

1 个答案:

答案 0 :(得分:0)

    $result = 0;

    if (isset($_POST['fileImage']) && ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))){
          //you must check for file type, else your website could be hacked.
       if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) { 
          //... 
       }
       else{
          //...
       }
    }

    $_SESSION['fileImage']['name'] = $_FILES['fileImage']['name'];