【问题标题】:Uploading photo to server to use as profile picture.将照片上传到服务器以用作个人资料图片。
【发布时间】:2013-06-08 20:39:36
【问题描述】:

我现在正在处理一个问题。目前,我有一个注册表单,它接受用户的一些字段和个人资料图片的图片上传字段。当前正在将个人资料图片名称插入数据库,但在查看目标位置的文件夹时,没有图片的迹象。现在页面变成白色,并在左上角加载了一个小小的破碎图片。有什么建议吗?

个人资料页面

<?PHP
ob_start();
error_reporting(E_ALL);
ini_set('display_errors',"On");
session_start();
if (!isset($_SESSION['username'])) {
    header('location:login.php');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style>

</style>
<!--[if lt IE 9]>

        <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>

    <![endif]-->        

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<script>  $(document).ready(function(){

                $('#login-trigger').click(function(){

                    $(this).next('#login-content').slideToggle();

                    $(this).toggleClass('active');                  



                    if ($(this).hasClass('active')) $(this).find('span').html('&#x25B2;')

                        else $(this).find('span').html('&#x25BC;')

                    })

          });
</script>
</head>

<body>
<header class="cf">

<nav></nav>

</header>
<h1 style="text-align:center"> The Animator - BETA</h1>
<hr />
<div id="nav" style="text-align:center">
<ul style="text-align:center">
<li><a href= "theanimator.html" ><strong>Home</strong></a></li>
<strong><li><a href= "industrial.html" >Industrial</a></li>
<li><a href= "educational.html" >Education</a></li>
<li><a href= "independent.html"  >Independent</a></li>
<li><a href= "emergent.html"  >Emergent</a></li>
<li><a href= "team.html" >Team</a></li>
<li><a href= "project.html"  >Project</a></li>
<li><a href= "budget.html" >Budget</a></li>
<li><a href= "profile.html" >Profile</a></li></strong>
</ul>
</div>
<hr />
<div style="padding-left:19%"><input type="text" value="search" />
<input type="button" value="Search!" name="search"/>
</div>
<h1 style="text-align:center">Profile</h1>
<div style="padding-left:15%; padding-right:15%; font-family: Arial, Helvetica, sans-serif;">
  <div style="font-size:18px; text-align:center; font-family: Arial, Helvetica, sans-serif;">
    <p>
      <?php 

    $querytest = "SELECT * FROM account WHERE idaccount = " . $_GET['idaccount'];
    $result = mysql_query($querytest);

    echo $_SESSION['idaccount'];
  ?>
    </p>
    <p>
      <?php

echo $_SESSION['username'];
  ?>
    </p>
  </div>
  <p style="text-align:center;"><?php echo $_SESSION['email'];?></p>
    <div style="font-size:18px; width:100px; text-align:left; margin-left:201px; padding-left:10pt">Specialties</div>
</div>
  <div style="width:100%; float:left;">
  <div style="width:30%">
  <?php
 $db_name = "animator"; // Database name
  $link = mysql_connect('localhost', 'root', 'admin');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
mysql_select_db($db_name) or die("Could not connect to Database" .mysql_error());
  $result = mysql_query("SELECT * FROM animator.account WHERE idaccount=" . $_SESSION['idaccount'] . ";");
  if (!$result) { // add this check.
    die('Invalid query: ' . mysql_error());
}
while($row = mysql_fetch_array($result))
{
 header("Content-type: image/jpeg");
     echo mysql_result($result, 0);
} 

   ?>
   </div>
  <div class="previous_work" id="previous_work" style="width:70%; float:left; margin-left:2%;">
  <hr />
  <li>3D Animation</li>
  <li>Scriptwriting</li>
  <li>CGI Animation </li>
</div>
<hr />
  </div>
  &nbsp;
  <hr />
<?php echo $_SESSION['bio']; ?>
</p>
</div>
  </p>
<p>&nbsp;</p>
</div>
<div id="footer"> <hr />
  <p><strong><u><a href="about.html">About The Animator</a> | <a     href="contact.html">Contact</a> | <a href="privacy.html">Privacy Policy</a> | <a     href="faq.html">FAQ</a></u></strong><u> | <strong><a     href="questionnaire.html">Questionnaire</a> |</strong></u> <strong><a     href="reports.html">Admin Reports</a> |</strong></u></p>
</div>
</body>
</html>

注册页面并上传照片

<?php
error_reporting(E_ALL);
ini_set('display_errors',"On");
include ('database_connection.php');
$target = "/var/www/profile";

if (isset($_POST['formsubmitted'])) {
    $error = array();//Declare An Array to store any error message  
    if (empty($_POST['name'])) {//if no name has been supplied 
        $error[] = 'Please Enter a name ';//add to array "error"
    } else {
        $name = $_POST['name'];//else assign it a variable
    }

    if (empty($_POST['e-mail'])) {
        $error[] = 'Please Enter your Email ';
    } else {


        if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
           //regular expression for email validation
            $Email = $_POST['e-mail'];
        } else {
             $error[] = 'Your EMail Address is invalid  ';
        }


    }


    if (empty($_POST['Password'])) {
        $error[] = 'Please Enter Your Password ';
    } else {
        $Password = $_POST['Password'];
    }


    if (empty($error)) //send to Database if there's no error '

    { // If everything's OK...

        // Make sure the email address is available:
        $query_verify_email = "SELECT * FROM account  WHERE email ='$Email'";
        $result_verify_email = mysqli_query($dbc, $query_verify_email);
        if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
            echo ' Database Error Occured ';
        }

        if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .


            // Create a unique  activation code:
            $activation = md5(uniqid(rand(), true));
            $target = $target . basename($_FILES['photo']['name']);

//This gets all the other information from the form
            $pic=($_FILES['photo']['name']);
            if(!isset($_FILES['photo'])) {
$error[] = "No photo selected !";
}



            $query_insert_user = "INSERT INTO `account` ( `username`, `passwords`, `email`, `picture`) VALUES ( '$name', '$Password', '$Email ' , '$pic')";


            $result_insert_user = mysqli_query($dbc, $query_insert_user);
            if (!$result_insert_user) {
                echo 'Query Failed ';
            }

            if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.


                // Send the email:
                $message = " To activate your account, please click on this link:\n\n";
                $message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
                mail($Email, 'Registration Confirmation', $message, 'From: systemadminstrator@theanimator.com');

                // Flush the buffered output.


                // Finish the page:
                echo '<div class="success">Thank you for
registering! A confirmation email
has been sent to '.$Email.' Please click on the Activation Link to Activate your account </div>';


            } else { // If it did not run OK.
                echo '<div class="errormsgbox">You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
            }

        } else { // The email address is not available.
            echo '<div class="errormsgbox" >That email
address has already been registered.
</div>';
        }

    } else {//If the "error" array contains error msg , display them



echo '<div class="errormsgbox"> <ol>';
        foreach ($error as $key => $values) {

            echo '  <li>'.$values.'</li>';



        }
        echo '</ol></div>';

    }

    mysqli_close($dbc);//Close the DB Connection

} // End of the main Submit conditional.



?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration Form</title>





<style type="text/css">
body {
    font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
    font-size:12px;
}
.registration_form {
    margin:0 auto;
    width:500px;
    padding:14px;
}
label {
    width: 10em;
    float: left;
    margin-right: 0.5em;
    display: block
}
.submit {
    float:right;
}
fieldset {
    background:#EBF4FB none repeat scroll 0 0;
    border:2px solid #B7DDF2;
    width: 500px;
}
legend {
    color: #fff;
    background: #80D3E2;
    border: 1px solid #781351;
    padding: 2px 6px
}
.elements {
    padding:10px;
}
p {
    border-bottom:1px solid #B7DDF2;
    color:#666666;
    font-size:11px;
    margin-bottom:20px;
    padding-bottom:10px;
}
a{
    color:#0099FF;
font-weight:bold;
}

/* Box Style */


 .success, .warning, .errormsgbox, .validation {
    border: 1px solid;
    margin: 0 auto;
    padding:10px 5px 10px 50px;
    background-repeat: no-repeat;
    background-position: 10px center;
     font-weight:bold;
     width:450px;

}

.success {

    color: #4F8A10;
    background-color: #DFF2BF;
    background-image:url('images/success.png');
}
.warning {

    color: #9F6000;
    background-color: #FEEFB3;
    background-image: url('images/warning.png');
}
.errormsgbox {

    color: #D8000C;
    background-color: #FFBABA;
    background-image: url('images/error.png');

}
.validation {

    color: #D63301;
    background-color: #FFCCBA;
    background-image: url('images/error.png');
}



</style>

</head>
<body>


<form action="registeraccount.php" method="post" class="registration_form" enctype="multipart/form-data">
  <fieldset>
    <legend>Registration Form </legend>

    <h2 style="text-align:center">Create an account!</h2>
    <p style="text-align:center"> <span>Already a member? <a href="login.php">Log in</a></span> </p>

    <div class="elements">
      <label for="name">Name :</label>
      <input type="text" id="name" name="name" size="25" />
    </div>
    <div class="elements">
      <label for="e-mail">E-mail :</label>
      <input type="text" id="e-mail" name="e-mail" size="25" />
    </div>
    <div class="elements">
      <label for="Password">Password:</label>
      <input type="password" id="Password" name="Password" size="25" />
      <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
      </div>

      <br />

    <div class="submit">
     <input type="hidden" name="formsubmitted" value="TRUE" />
      <input type="submit" value="Register" />

    </div>
  </fieldset>
</form>
<button onclick="window.location='theanimator.html';">Go Back!</button>
</body>
</html>

【问题讨论】:

  • 这显然是与path 相关的问题。
  • 我不明白这是怎么回事。我已经按照您的建议尝试了 / ,但仍然遇到同样的问题。
  • 我认为您的$target = $target . basename($_FILES['photo']['name']); 是问题所在并且令人困惑。您可能必须设置为$targetfile = $target . basename($_FILES['photo']['name']); 的影响,因为您已经声明了目标路径。
  • 还是没有解释为什么整个页面都是白色的,只显示一张破图。

标签: php html sql photo-upload


【解决方案1】:

注意:这是一个建议性答案。

删除或注释掉这一行:$target = "/var/www/profile";

并将我在下面发布的代码放在您的 mail() 函数下方,

或以上$message = "To activate your account... 并尝试/测试。

路径注释:关于我的代码中的$upload_path = './uploads/';, 这是假设您从服务器的root 运行脚本。

您可以尝试$upload_path = '/var/www/profile/uploads/';,但您需要保留尾部斜杠。

您还需要删除/注释掉$target = $target . basename($_FILES['photo']['name']);
或者更好的是,在那个空间使用我的代码。您必须测试它在哪个位置最有效。

这是我的(测试过的)代码:

$allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 9999999999; // Maximum filesize in BYTES - SET IN to a low number for small files
$upload_path = './uploads/'; // The place the files will be uploaded to (currently a 'files' directory).

$filename = $_FILES['photo']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.

// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');

// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['photo']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');

// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');

// Upload the file to your specified path.
if(move_uploaded_file($_FILES['photo']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed

// rest of your code to be placed below

【讨论】:

  • 非常感谢弗雷德的帮助。我给你答案是因为这将毫无问题地工作。我目前想出了另一种方法来做到这一点,因为我需要为每张图片分配一个唯一的 ID 并在上传之前更改文件名以避免图片被覆盖的可能性。现在我需要比较数据库中输入的数据(图片唯一 ID)并为配置文件提取适当的图片。
  • @ZachHarvey 谢谢扎克。有趣的是,您应该对“唯一 ID”这么说。我只是在另一件事上帮助别人,并告诉 OP 图像文件需要重命名为唯一 ID,原因有很多,其中一个是如果有些人从 iPod Touch 上传,iPhone,默认正在发送的名称称为image.jpg。如果您对此有任何问题,请给我留言,我可能有一个功能。干杯
  • @ZachHarvey 继续说明,我是否建议使用服务器的 UNIX 时间戳,以及上传者原始文件名的串联名称。
  • @ZachHarvey 我可以在我的回答中添加我编写并使用到今天的代码(随机数字名称以及用于重命名传入文件的额外内容)。您需要稍微调整一下以满足您的需求。告诉我。
  • @ZachHarvey 我上面查看图片的代码,可以放在move_uploaded_file(...下面。这将立即显示上传的图像。再一次,你必须修改它以适应你现在的脚本,干杯。
【解决方案2】:

这不是一个完整的修复,但我注意到了几件事

正如其他人所建议的那样,您没有将图片移动到您可以访问的位置。另外:

while($row = mysql_fetch_array($result)) { header("内容类型:图片/jpeg"); echo mysql_result($result, 0); }

在您将输出发送到浏览器之后,似乎正在使用 header() 术语。我确实注意到您正在使用 ob_start 来缓冲您的输出,但不认为这会阻止意外结果。

在同一代码块中,您似乎从 mysql 结果返回了整行,而不仅仅是 .jpg 数据。我怀疑这是更可能的问题,因为

$result = mysql_query("SELECT * FROM animator.account WHERE idaccount=" . $_SESSION['idaccount'] . ";");

正在返回一个包含数据库中所有字段的数组。对后一种理论的快速测试是将您的查询替换为

$result = mysql_query("SELECT picture FROM animator.account WHERE idaccount=" . $_SESSION['idaccount'] . ";");

很想听听你的结果。

【讨论】:

  • 感谢您的回复,但即使在将代码行替换为您的建议后,我仍然会得到一个顶部有破损图片的空白页。
  • Ok 你写一个简单的页面,用代码选择一张你知道在数据库中的图片(你是用phpmyadmin检查数据库内容吗?)然后只显示图片。这将帮助您排除故障,即使它很痛苦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 2014-04-14
  • 1970-01-01
  • 2015-12-09
相关资源
最近更新 更多