<?
php
require '../vendor/autoload.php'; // Download as Excel file
use PhpOffice\PhpSpreadsheet\Spreadsheet; $writer = new Xlsx($spreadsheet);
use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $demoFilePath = 'demo_file.xlsx';
use PhpOffice\PhpSpreadsheet\IOFactory; $writer->save($demoFilePath);
session_start(); header('Content-Type:
if (!isset($_SESSION['adminusername']) || application/vnd.openxmlformats-
!isset($_SESSION['admincourse'])) { officedocument.spreadsheetml.sheet');
// Redirect to login page header('Content-Disposition: attachment;
header("Location: admin_login.php"); filename="demo_student_file.xlsx"');
exit; readfile($demoFilePath);
} unlink($demoFilePath);
// Handle download demo file exit;
}
if (isset($_GET['download_demo'])) { // Handle file upload and preview
$spreadsheet = new Spreadsheet(); if ($_SERVER['REQUEST_METHOD'] == 'POST' &&
$sheet = $spreadsheet->getActiveSheet(); isset($_FILES['excel_file'])) {
// Set headers $fileTmpPath = $_FILES['excel_file']['tmp_name'];
$sheet->setCellValue('A1', 'id')
->setCellValue('B1', 'roll') try {
->setCellValue('C1', 'name') $spreadsheet = IOFactory::load($fileTmpPath);
->setCellValue('D1', 'username') $sheet = $spreadsheet->getActiveSheet();
->setCellValue('E1', 'password') $rowCount = $sheet->getHighestRow(); // Get
->setCellValue('F1', 'semester'); the total number of rows
$columnCount = $sheet-
// Add demo data >getHighestColumn(); // Get the highest column (A, B,
$sheet->fromArray([ C,...)
[1, 78, 'Parmar sahil',
'ty@78','sahil@78',6], // Check if there are 5 columns
[2, 79, 'Parmar Yash', 'ty@79','yash@79',6], $columnCount =
[3, 90, 'Patel Adil', 'ty@80','adil@80',6], \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnInde
], null, 'A2');
xFromString($columnCount); // Convert column letter } else {
to number echo "<script>alert('Please upload a
if ($columnCount === 6) { valid file!');</script>";
$data = $sheet->toArray(); }
$username=$data[1][3];
$password=$data[1][4];
if (!preg_match('/^(?=.*[a-zA-
Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{3,}$/',
$username)) { } catch (Exception $e) {
echo "<script>alert('Username echo "<script>alert('"."Please upload valid
must contain at least one letter, one number, and one file " . $e->getMessage()."');</script>";
special character.');</script>"; }
}
}
else if (!preg_match('/^(?=.*[a-zA- // Handle final submission
Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{3,}$/', if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$password)) { if ( isset($_POST['submit_data']) &&
echo "<script>alert('Password isset($_SESSION['uploaded_data'])) {
must contain at least one letter, one number, and one $uploadedData = $_SESSION['uploaded_data'];
special character.');</script>";
}
else $servername = "localhost";
{ $username = "root";
$_SESSION['uploaded_data'] = $password = "";
$data; $dbname = $_SESSION['admincourse'];
$conn = new mysqli($servername, $username,
header('Location: ' . $password, $dbname);
$_SERVER['PHP_SELF']); if ($conn->connect_error) {
} die("Connection failed: " . $conn-
>connect_error);
}
if ($usernameResult->num_rows > 0)
$checkTableQuery = "SHOW TABLES LIKE {
'student_info'"; echo "<script>alert('Username
$result = $conn->query($checkTableQuery); $username is already
$resultcreate=false; taken.');window.history.back();</script>";
if ($result->num_rows == 0) { exit;
$sql="CREATE TABLE `student_info` (`id` }
INT(200) NOT NULL AUTO_INCREMENT , `roll` INT(200) if (!preg_match('/^(?=.*[a-zA-
NOT NULL , `name` VARCHAR(25) NOT NULL , `username` Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{4,}$/',
VARCHAR(25) NOT NULL , `password` VARCHAR(25) NOT $uploadedData[$i][4])) {
NULL , `semester` INT(25) NOT NULL , PRIMARY KEY echo "<script>alert('Password for
(`id`)) ENGINE = MyISAM"; username $username must contain at least one letter,
$resultcreate=$conn->query($sql); one number, and one special character and atleast 4
} charecter long');window.history.back();</script>";
else exit;
{ }
$resultcreate=TRUE; $password=password_hash($uploadedD
} ata[$i][4],PASSWORD_DEFAULT);
$semester=$uploadedData[$i][5];
if ($resultcreate === TRUE) { $sql = "INSERT INTO `student_info`
//insert the data into the table (roll, name, username, password, semester)
$j=1; VALUES ('$roll', '$name',
for($i=1;$i<count($uploadedData);$i++) '$username', '$password', '$semester')";
{ if($conn->query($sql) === TRUE)
$roll=$uploadedData[$i][1]; {
$name=$uploadedData[$i][2]; $j=$j*1;
$username=$uploadedData[$i][3]; }
$checkUsernameQuery = "SELECT * else
FROM `student_info` WHERE `username` = '$username'"; {
$usernameResult = $conn- $j=0;
>query($checkUsernameQuery); }
} <head>
if($j!=0) <meta charset="UTF-8">
{ <meta name="viewport" content="width=device-
echo "<script>alert('Data inserted width, initial-scale=1.0">
successfully');</script>"; <title>Excel File Upload</title>
header("Location: <link rel="stylesheet"
student_list.php"); href="../examiner/style/addquesitonwithexcel.css">
exit; </head>
} <body>
else
{ <h2>Excel File Upload Instructions</h2>
echo "<script>alert('something <div class="instructions">
went wrong try again');</script>"; <p>Please follow the given syntax for
} creating your Excel file:</p>
<table>
} else { <tr>
echo "<script>alert('something went <th>id</th>
wrong try again');</script>"; <th>roll</th>
} <th>name</th>
<th>username</th>
$conn->close(); <th>password</th>
unset($_SESSION['uploaded_data']); <th>semester</th>
} </tr>
if (isset($_POST['cancel'])) { <tr>
unset($_SESSION['uploaded_data']); <td>1</td>
} <td>78</td>
<td>Parmar sahil</td>
} <td>ty@078</td>
?> <td>sahil@78</td>
<td>6</td>
<!DOCTYPE html> </tr>
<html lang="en"> <tr>
<td>2</td>
<td>96</td> <?php if (!isset($_SESSION['uploaded_data'])): ?>
<td>Purohit jaimin</td> <h2>Upload Your Excel File</h2>
<td>ty@096</td> <form action="" method="post"
<td>jaimin@96</td> enctype="multipart/form-data">
<td>6</td> <input type="file" name="excel_file"
</tr> accept=".xls,.xlsx" required>
<tr> <button type="submit">Upload and
<td>1</td> Preview</button>
<td>118</td> </form>
<td>Ven prakash</td> <?php else: ?>
<td>ty@118</td> <h2>Preview of Uploaded File</h2>
<td>ven@118</td> <table>
<td>6</td> <?php foreach ($_SESSION['uploaded_data']
</tr> as $row): ?>
</table> <tr>
<p><strong>Note:</strong></p> <?php foreach ($row as $cell): ?>
<ul> <td><?php echo
<li>Username must be unique</li> htmlspecialchars($cell); ?></td>
<li>you must me provide 6 colums <?php endforeach; ?>
(id,roll,name,username,password,semester) in </tr>
order</li> <?php endforeach; ?>
<li>username must be in the form of </table>
student@123 format because it will not change</li> <form action="" method="post">
<li><a href="?download_demo=true"> <button type="submit"
<button>Download Demo File</button></li> name="cancel">Cancel</button>
</a> <button type="submit"
</ul> name="submit_data">Submit Data</button>
</form>
</div> <?php endif; ?>
</body>
</html>