2017-05-07 85 views
-1
<form action = "<?php $_SERVER["PHP_SELF"];?>" class="register-form" method="post" name="form1" encype="multipart/form-data"> 
    <input type="text" placeholder="Username" name="username" maxlength="15" required/> 
    <input type="text" placeholder="Email Address" name="email" maxlength="30" required/> 
    <input type="password" placeholder="Password" name="password" maxlength="15" required/> 
    <input type="password" placeholder="Confirm Password" name="conf_password" maxlength="20" required/> 
    <input type="file" name="file" accept="image/*"/> 
    <button href="../index.html">create</button> 
</form> 

这些是我的HTML标签。 我想为此字段设置一个默认图像。图像的名字是default-avatar.jpeg
我写了这个代码:
用php为MySQL数据库设置用户的默认图像

if (isset($_POST["file"])){ 
    $file = addslashes($_POST["file"]); 
    echo "Yes<br>"; 
} 
elseif(empty($_POST['file'])){ 
    $file = "default-avatar.jpeg"; 
    echo "No<br>"; 
} 

所以我建议当用户选择另一个文件中,$file变量得到另一个值,当用户不选择一个文件时, $file停留的值default-avatar.jpeg

但是文件字段的值永远不会为空。当我试图echo它总是有一些价值。如果用户选择另一个文件,变量$file的值是该文件,但是当它不是该值时(我认为它是空的)。所以isset($_POST["file"])总是为真。我该如何解决这个问题?

+0

[你不能](http://stackoverflow.com/questions/1696877/how-to-set-a-value-to-a-file-input-in-html)。附注:无论你想完成什么,'addslashes()'都是错误的工具。 –

回答

0

文件存储在$_FILES,而不是在$_POST。所以数据必须以$ _FILES发送。在这种情况下,empty()函数将有所帮助。

$temp = $_FILES['file']['tmp_name']; 
$error = $_FILES['file']['error']; 

define("UPLOAD_DIR", "../images/users/"); 

if (isset($_FILES['file']) && !empty($_FILES["file"])) { 
    $file = $_FILES["file"]["name"]; 

    $uploadfile = UPLOAD_DIR . $file;//implode() 

    if (!$error>0) { 
     move_uploaded_file($temp, $uploadfile); 
     echo "<p>Success<p>"; 
    } 
    else{ 
     $file = "default-avatar.jpeg"; 
     echo "<p>An error occurred.</p>"; 
     exit; 
    } 
0

试试这个:

if (isset($_POST["file"])) 
{ 
    if($_POST["file"] == "") 
    { 
     $file = "default-avatar.jpeg"; 
     echo "No<br>"; 
    } 
    else 
    { 
     $file = addslashes($_POST["file"]); 
     echo "Yes<br>"; 
    } 
} 
+0

问题是这个'$ _POST [“file”] ==“”'不起作用,因为文件字段的值永远不会为空 –

+0

@Ani,我刚刚看到您发布在其他答案上的评论。由于您已将输入类型设置为'file',因此您可能想查看以下内容:http://stackoverflow.com/questions/37182801/does-input-type-files-appear-in-post –

+1

是的,因为文件是存储在'$ _FILES'中,而不是'$ _POST'。感谢这个链接。 –