php-如何记录哪个用户点击链接下载文件

时间:2017-04-17 13:31:54

标签: php html sql

我正在尝试记录哪个用户已在SQL数据库中下载了文件。上传的每个文件都将其路径显示为站点上的链接,允许用户从服务器上的文件夹下载该文件。我无法弄清楚如何记录哪个用户下载了文件。如何查询特定用户点击特定链接的数据库?我将用户ID存储为会话变量,因此拥有用户ID不是问题。我显示可下载文件的代码如下:

<?php
      session_start();

        $servername = "localhost";
            $username = "root";
            $password = "";
            $dbname = "project_website1";
            $user_id = $_SESSION[ 'user_id' ];

        // Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            } 

            $sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
                $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                    echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
                // output data of each row
            while($row = $result->fetch_assoc()) {
                    //echo "<tr><td>" . $row["file"]. "</td><td>" . $row["title"]. "</td><td>" . $row["deadline_claim"]. "</td></tr>";
                    echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='" .$row["file"]. "'>CLAIM</td></a>";



                }
                    echo "</table>";
            } else {
                    echo "0 results";
        }

            $conn->close();
?>  

2 个答案:

答案 0 :(得分:0)

如果您希望它纯粹是PHP,如建议的那样,只需使用文件表中行的task_id即可。这是一个基本的例子,注意到我重新组织了一些元素以帮助保持脚本清洁。理想情况下,您希望将功能保留在不同的页面上,并在您想要使用它们时包含它们。使您的脚本更清晰,更易于阅读。

# Better to make a function/class to do your database so you can reuse it easily.
function getConnection( $servername = "localhost", $username = "root",$password = "",$dbname = "project_website1")
    {
        # Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        # Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        return $conn;
    }

# Make a task retrieval function/class that will deal with getting the rows only
function getTasks($con,$id=false)
    {
        $sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
        # I am assuming your task_id values are numeric, so I don't sanitize here
        if ($id) {
            if(is_numeric($id))
                # Append sql
                $sql .= " WHERE `task_id` = '{$id}'";
            else
                # You shouldn't get this exception unless someone is trying to
                # Manually put something else here via injection attempt
                throw new Exception("Id must be numeric!");
        }

        $result = $con->query($sql);

        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $new[] = $row;
            }
        }
        # Send back rows
        return (!empty($new))? $new : array();
    }

# This is more of a listener, but it will cut down on some redundant check-script
function getFileId()
    {
        if(!empty($_GET['file']) && is_numeric($_GET['file']))
            return (!empty($_GET['action']) && $_GET['action'] == 'download')? $_GET['file'] : false;

        return false;
    }

# As noted, you would include the functions here...
session_start();
# Get session id
$user_id = $_SESSION[ 'user_id' ];
# Get the database connection
$conn    = getConnection();
# If there is a download
if(!empty($_GET['action']) && $_GET['action'] == 'download') {
    # Get the tasks, could be based on id or all
    $tasks   = getTasks($conn, getFileId());
    # Save to the database, make sure that you either bind parameters, or
    # check that the values are numeric (if they are supposed to be numeric)
    # Also check the count here first for the task before inserting. Make an error if not.
    # Usually means user is trying to manipulate the request
    $conn->query("INSERT into downloads (`fileid`,`userid`) VALUES('".$tasks[0]['task_id']."','".$user_id."')");
    # Download file. If you want to obfuscate the file, you would use
    # download headers instead:
    # http://php.net/manual/en/function.readfile.php
    header('Location: '.$tasks[0]['file']);
    # Stop execution
    exit;
}

# Get all tasks
$tasks   = getTasks($conn);
# If there are rows, output them
if (!empty($tasks)) {
    echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
    # output data of each row
    foreach($tasks as $row) {
        echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='?action=download&file=" .$row["task_id"]. "'>CLAIM</td></a>";
    }
    echo "</table>";
} else {
    echo "0 results";
}

$conn->close();

最后说明,我没有测试过,所以要注意这一点。

答案 1 :(得分:0)

您在html中调用脚本的标题

<head>
   <script laqnguage="javascript" src="myfunction.js" type="text/javascript"></script> 
</head>

然后在你的php循环中跳出php

?>
<form name"myform" method="get" action="<? php echo $row["file"]; ?>"> 
<input type="button" name="name" Value"<? php echo $row["file"]; ?>" onClick="setinsertAction();" />
</form>

然后再次跳转到php

<?php

现在创建一个名为myfunction.js的文件并将其放在

function setinsertAction() {
document.myform.action = "HERE PUT YOUR PHP FILE THAT WILL DO THE QUERY";
document.myform.submit()'
}

如果一切顺利,它应该检索文件下载并执行你的PHP脚本如果你替换.js文件中的查询的php文件,如果它失败让我知道