Reputation: 171
I am trying to protect some pdf files with password, using an onclick functions as shown in the code below
What I am trying to achieve here:
If the user inserted the correct ID, the script gives him the corresponding href link for his pdf file that should contains:
certificates/First_Last_ID.pdf
where "First" & "Last" are php variables, and the php variable ID = the js var truePassword
Ex. If I clicked on the row of Jon Doe and inserted the correct password AAA0000
I get the following link:
window.location.href = '/certificates/Jon_Doe_AAA000.pdf';
Achieving this requires adding some variables in the link name, maybe!
Please Advice
<html>
<body>
<?php
$con=mysqli_connect("localhost","x","y","z");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Academy");
// Fetching Data from MySql
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['First'] . " " . $row['Last'] . "</td>";
echo "<td>" . $row['Program'] . "</td>";
echo "<td>" . $row['Date Accredited'] . "</td>";
echo "<td>" . $row['Grade'] . "</td>";
echo "<td>" . "<a href='javascript:void(0);' onclick='myFun(event);validate()'><img src='../SVG/certificate_logo.svg' /><span id='ID' style='display:none;'>" . $row['ID'] ."</span></a>" . "</td>";
echo "</tr>";
}
mysqli_close($con);
?>
<script>
var truePassword;
var password;
function myFun(e){
truePassword = (e.target.nextSibling.innerText);
}
function validate(){
password = prompt('Enter Your Course Reservation ID (Case Sensitive)', 'YYY0000');
if (password==truePassword) {
window.location.href = '/certificates/<?php echo $row['First']."_".$row['Last'] ?>.pdf'; //relative to domain
}else{
alert ("Wrong ID");
return;
}
}
</script>
</body>
</html>
Upvotes: 2
Views: 1958
Reputation: 875
Changed the last "td" with the following
echo "<td>" . "<a href='javascript:void(0);' onclick='myFun(event);validate(this.id)' id='" . $row['First'] . "_" . $row['Last'] . "'><img src='../SVG/certificate_logo.svg' /><span id='ID' style='display:none;'>" . $row['ID'] ."</span></a>" . "</td>";
Try this
<script>
var truePassword;
var password;
function myFun(e){
truePassword = (e.target.nextSibling.innerText);
}
function validate(clicked_ele_id){
password = prompt('Enter Your Course Reservation ID (Case Sensitive)', 'YYY0000');
if (password==truePassword) {
window.location.href = '/certificates/' + clicked_ele_id + '_' + password + '.pdf'; //relative to domain
}else{
alert ("Wrong ID");
return;
}
}
</script>
Upvotes: 1
Reputation: 23
I would suggest using an AJAX call for this. That way you also keep your password checking server side.
Upvotes: 0
Reputation: 312
You could just include the PHP variables in the href:
echo "<td>" . "<a href='".$row['First']."_".$row['Last']."_".$row['ID'].".pdf'";
Upvotes: 0