Попытка заполнения формы и создания отдельного CSV-файла при каждой ее отправке. Когда форма заполнена, страница перезагружается, но в настоящее время файл не создается.
Я знаю, что есть много других способов сделать это, но я очень новичок в этом, и таким образом я мог лучше понять, чем другие.
<?php
if (isset($_POST["submit"])){
//collect form data
$name = $_POST["name"];
$email = $_POST["email"];
$customer = $_POST["customer"];
$reseller = $_POST["reseller"];
$standardusers = $_POST["standardusers"];
$ucusers = $_POST["ucusers"];
$recording = $_POST["recording"];
$firewall = $_POST["firewall"];
//check name is set
if ($name ==''){
$error[] = 'Name is required';
}
//check for a valid email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error[] = 'Please enter a valid email address';
}
//check customer name is set
if ($customer ==''){
$error[] = 'Customer Name is required and must match ConnectWise';
}
//check reseller name is set
if ($reseller ==''){
$error[] = 'Reseller Name is required and must match ConnectWise';
}
//check standardusers is set
if ($standardusers ==''){
$error[] = 'Number of users is required';
}
//check ucusers is set
if ($ucusers ==''){
$error[] = 'Number of users is required';
}
//if no errors carry on
if (!isset($error)){
//# Title of the CSV
$Content = "Name, Email, Customer, Reseller, Standard Users, UC Users, Call Recording, Firewall\n";
//set the data of the CSV
$Content .= "$name, $email, $customer, $reseller, $standardusers, $ucusers, $recording, $firewall\n";
//# set the file name and create CSV file
$filename = "formdata-".date("d-m-y-h:i:s").".csv";
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename = "'.$FileName.'";');
echo $Content;
echo gethostname();
exit();
}
}
?>
После того, как форма отправлена, она должна отправить файл .csv на сервер и сообщить пользователю, что форма была успешно отправлена.
Это успешно работает
<?php
if (isset($_POST["submit"])){
$data = array();
$data['name'] = $_POST["name"] ?? '';
$data['email'] = $_POST["email"] ?? '';
$data['customer'] = $_POST["customer"] ?? '';
$data['reseller'] = $_POST["reseller"] ?? '';
$data['standardusers'] = $_POST["standardusers"] ?? '';
$data['ucusers'] = $_POST["ucusers"] ?? '';
$data['recording'] = $_POST["recording"] ?? '';
$data['firewall'] = $_POST["firewall"] ?? '';
$errors = '';
foreach ($data as $key => $value) {
if ($key == 'recording' || $key == 'firewall'){ } //do nothing
else {
if (empty($value)) {
//Field is empty && email
if ($key == 'email') {
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)){
$errors .= 'Please enter a valid email address \r\n ';
}
} else {
//Field is empty && !email
$errors .= $key.' field is required. \r\n ';
}
}
}
}
//if no errors carry on
if (empty($errors)){
//# Title of the CSV
$Content = "Name, Email, Customer, Reseller, Standard Users, UC Users, Call Recording, Firewall\n";
//set the data of the CSV
// Added '' in each field as a delimiter
// $Content .= "'".$data['name']."', '".$data['email']."', '".$data['customer']."', '".$data['reseller']."', '".$data['standardusers']."', '".$data['ucusers']."', '".$data['recording']."', '".$data['firewall']."'\n";
$row = '';
foreach ($data as $key => $value){
$row .= $value.","; //Append data to csv
}
//Remove trailing comma
$row = mb_substr($row, 0, -1);
$Content .= $row;
//# set the file name and create CSV file
// $filename = "formdata-".date("d-m-y-h:i:s").".csv";
// header('Content-Type: application/csv');
// header('Content-Disposition: attachment; filename = "'.$FileName.'";');
// echo $Content;
// echo gethostname();
// exit();
$csv_handler = fopen ('csvfile.csv','w');
if (fwrite ($csv_handler,$Content)){
echo 'Data saved to csvfile.csv';
} else {
echo "File not saved successfully";
}
fclose ($csv_handler);
} else {
echo $errors;
}
}
?>
Я тестировал с помощью этой формы, отправляя в скрипт
<form class = "" action = "3.php" method = "post">
<input type = "text" name = "name" placeholder = "name" >
<input type = "text" name = "email" placeholder = "email" >
<input type = "text" name = "customer" placeholder = "customer" >
<input type = "text" name = "reseller" placeholder = "reseller" >
<input type = "text" name = "standardusers" placeholder = "standardusers" >
<input type = "text" name = "ucusers" placeholder = "ucusers" >
<input type = "text" name = "recording" placeholder = "recording" >
<input type = "text" name = "firewall" placeholder = "firewall" >
<input type = "submit" name = "submit" value = "submit">
</form>
Это здорово. Единственная проблема, которую я вижу, это то, что параметры «запись» и «брандмауэр» необходимы, а их не должно быть. Как исключить эти варианты? Вот как они устанавливаются в форме. <p><label class = "checkbox">Call Recording?<br><input type='checkbox' name='recording' value=''><span class = "checkmark"></span></label></p> <p><label class = "checkbox">Firewall?<br><input type='checkbox' name='firewall' value=''><span class = "checkmark"></span></label></p>
@quigleyvision для необязательных полей, если вы не хотите вручную писать операторы if в первом цикле foreach, вы можете просто поместить N/A в резервное назначение ?? 'Н/Д'
так что-то вроде этого перед массивом? if (isset($_POST['recording'])) { $recording = "Yes"; } else { $recording = "No";
Спасибо, это очень помогло! Я изменил вывод файла, чтобы включить временную метку, поэтому он будет создавать несколько файлов каждый раз, когда он будет заполнен. $timestamp = date("Y-m-d_H-i-s"); //$timestamp takes the current time $myFile = "new_deployment.".$timestamp.".csv"; // add timestamp to the file name $csv_handler = fopen ($myFile,'w');
Добро пожаловать в Stack Overflow. Обновите свой вопрос, указав минимальный, полный и проверяемый пример, демонстрирующий проблему. Покажите нам, что вы уже пробовали.