How do i create .txt file with PHP code in VScode - php

I have just started to learn PHP, and started it with VS Code
But unfortunately when trying to create a new simple 'data.txt' file, but without any luck. here is the code
<?php
mb_internal_encoding('UTF-8');
echo '<pre>' . print_r($_POST, true) . '</pre>';
$pageTitle = 'Форма';
include 'header.php';
$groups = [1 => 'Приятели', 2 => 'Бивши', 3 => 'Бъдещи', 4 => 'Колеги'];
$error = true;
if ($_POST) {
$username = trim($_POST['username']);
$phone = trim($_POST['phone']);
$selectedGroup = (int) $_POST['group'];
if (mb_strlen($username) < 4) {
echo '<p>Името е прекалено късо</p>';
$error = true;
}
if (mb_strlen($phone) < 6 || mb_strlen($phone) > 12) {
echo '<p>Невалиден Телефон</p>';
$error = true;
}
if (!array_key_exists($selectedGroup, $groups)) {
echo '<p>Невалидна Група</p>';
$error = true;
}
if (!$error) {
$result = $username . '!' . $phone . '!' . $selectedGroup;
file_put_contents('data.txt', $result);
}
}
?>
Списък
<form method="POST">
<div> Име: <input type="text" name="username" /> </div>
<div>Телефон <input type="text" name="phone" /> </div>
<div>
<select name="group">
<?php foreach ($groups as $key => $values) {
echo '<option value="' . $key . '">' . $values . '</options>';
} ?>
</select>
</div>
<div><input type="submit" name="Добави" /> </div>
</form>
<?php include 'footer.php';
?>
Every time i reload the server it does not create any new '.txt' file, even when i try with different values i am not able to create.enter code herenter code heree
I looked up to find different information, i have tried to change the permissions to -- 755 -- 'Path' ==>> /var/www/html.
The same goes to debugging, i have tried but no errors are displaying, assuming it is some small thing i tried to look into the code 100 times but with no result.
Thanks in Advance.

There's no condition where $error could be false (you initialize it to true and only set it to true), so you can never enter the if(!$error){ block.
You'll probably want to change that initial
$error = true;
to
$error = false;

Related

I can't seem to get my post form working correctly in PHP, despite hours of troubleshooting as well as it being a relatively simple program

I'm new to PHP and am having trouble with what seems like a relatively simple program. I can't get my $_POST['Username'] to equal my $temp and therefore never echo'success!'; even if i echo every check and i can physically see that they equal, success never prints. Any help is greatly appreciated <3.
<?php
if(isset($_POST['submit']))
{
if (file_exists('logins.txt'))
{
echo 'The file was found' . '<br>';
$file = fopen('logins.txt', 'r');
while (feof($file) == false)
{
$temp = fgets($file, 20);
if ($temp === $_POST['Username'])
{
echo'success!';
}else
{
echo 'failed' . '<br>';
echo $temp . '<br>';
echo $_POST['Username'] . '<br>';
}
};
fclose($file);
}
}
?>
<HTML>
<body>
<form action="" method="post">
Username
<input type="text" name="Username" size="30" value="">
Password
<input type="text" name="Password" size="30" value="">
<input type="submit" name="submit" value="Login">
</form>
</body>
</HTML>
Picture of the output using a textfile with the letters a - e
replace
if ($temp === $_POST['Username'])
with
if (trim($temp) == trim($_POST['Username']))
you probably have some space or something in your file
to better understand what is going on you can try to replace
echo $temp . '<br>';
echo $_POST['Username'] . '<br>';
with
var_dump($temp,$_POST['Username'])

PHP ob_flush not working on foreach

I have written a script to perform some actions using foreach, it's working fine, the only problema is that it waits until the the end of all the actions to display the output, what I want is to display the output in real time, while the script is still running.
I had tried the suggestions on this question, but it didn't work for me. Below is my script.
<form name="dataform" id="dataform" method="POST">
<textarea name="data" id="data" placeholder="username|useremail|userpass" rows="10"></textarea> <br>
<input type="text" maxlength="1" name="separator" id="separator" value="|">
<button type="submit" name="iniciar" id="iniciar">Iniciar!</button>
</form>
<?php
if (isset($_POST['iniciar'])) { // Start only if the "iniciar" button is pressed
ob_start();
foreach(explode("\n", $_POST['data']) as $line) {
// Get Separator, Explode and set variables
$explode = explode($_POST['separator'], $line);
// Remove white spaces
$explode = preg_replace('/\s+/', '', $explode);
$username = $explode[0];
$useremail = $explode[1];
$userpass = $explode[2];
$response = "Success, new user registered!";
if (strpos($response, "Success") !== false) {
echo "<b style='color: green;'>Success, new user registered! </b> | ~> " . $username . ' | ' . $useremail . ' | ' . $userpass . "<br>";
ob_flush();
sleep(5); // only for debug purposes
}
else {
echo "<b style='color: red;'>Oh, no! Something went wrong! :(</b>" . "<br>";
}
}
}
?>

Contact.php send email but doesn't redirect

I am working on the contact form for my Music Project's website.
The contact form seems to be working ok. If i input every field it sends the email (i get it ok on my gmail account) and if i don't input every field it gives error messages.
But the strange thing is that after i hit send i get a blank page (address: MySiteRoot/contact.php )and it doesn't redirect.
If i then click on the browsers "Go Back" button, i get the correct "error" messages, either the error or the message sent.
Why isn't is redirecting? Any ideas?
I have tried adding
exit();
after the
header('Location: /index.php');
but it didn't make any change.
I have both the index.php and the contact php on my site's root folder.
here is the code of my CONTACT.PHP
<?php
session_start();
require_once 'libs/phpmailer/PHPMailerAutoload.php';
$errors = [];
if(isset($_POST['name'], $_POST['email'], $_POST['message'])) {
$fields = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
];
foreach($fields as $field => $data) {
if(empty($data)) {
$errors[] = 'The ' . '<b>' . $field . '</b>' . ' field is required.';
}
}
if(empty($errors)) {
$m = new PHPMailer;
$m -> isSMTP();
$m -> SMTPAuth = true;
/*$m -> SMTPDebug = 1;*/
$m -> Host = 'smtp.gmail.com';
$m -> Username = ''; /* TOOK THEM OUT HERE ON THE POST ONLY */
$m -> Password = ''; /* TOOK THEM OUT HERE ON THE POST ONLY */
$m -> SMTPSecure = 'ssl';
$m -> SMTPKeepAlive = true;
$m -> Port = 465;
$m -> isHTML(true);
$m -> Subject = '4Elements Message';
$m -> Body = 'From: ' . $fields['name'] . ' (' . $fields['email'] . ')<p>' . $fields['message'] . '</p>';
$m -> FromName = '4Elements Contact';
$m -> AddAddress('anatis#gmail.com', 'Anatis');
if($m -> Send()) {
$errors[] = 'Thanks! Your message was sent!';
header('Location: /index.php');
} else {
$errors[] = 'Sorry, could not send email. Please try again later.';
}
}
} else {
$errors[] = 'Something went wrong.';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: /index.php');
on my INDEX.PHP i have at the beginning:
<?php
session_start();
require_once 'security.php';
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
?>
<!DOCTYPE HTML>
... THEN COMES SOME HTML CONTENT
Later on comes the FORM:
<?php if(!empty($errors)): ?>
<div class="panel">
<ul><li><?php echo implode('</li><li>', $errors); ?></li></ul>
</div> <!-- end of .panel -->
<?php endif; ?>
<form action="contact.php" method="post">
<label>
<input type="text" name="name" autocomplete="off" placeholder="Name" <?php echo isset($fields['name']) ? ' value="' . e($fields['name']) . '"' : ''?>>
</label>
<label>
<input type="email" name="email" autocomplete="off" placeholder="Email" <?php echo isset($fields['email']) ? ' value="' . e($fields['email']) . '"' : ''?>>
</label>
<label>
<textarea name="message" rows="10" placeholder="Message"><?php echo isset($fields['message']) ? e($fields['message']) : ''?></textarea>
</label>
<input id="submitbutton" type="submit" value="send">
</form>
and then at the end of the index.php i still have:
<?php
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>
i am working on my local server, with MAMP running PHP 5.6.2
Any ideas on what is going on? Thanks!
try to remove the header('Location: /index.php'); inside the m->Send() and let the only one at the end of the script.
Even replace $errors = [] with $errors = Array() at the begin.
Have you tried with using javascript instead of header('Location: /index.php');
echo '<script>window.location.href="/index.php";</script>'
Also, have you checked any warning or error log file. If you are getting this type of error message "Cannot modify header information - headers already sent" then try this link How to fix "Headers already sent" error in PHP
I hope it should work for you.

How to write to file with same name as HTML form field

I have made an attempt to write a PHP code that takes the contents of an HTML form then write them into a file. I have that down just fine, but I have another problem. I want to take an input of a field in the form and make it the file name that I am writing to.
Here is my PHP code:
<?php
if(isset($_POST['forwhom']) && isset($_POST['importance']) && isset($_POST['message'])) {
$file = "students.html";
$data = nl2br('-' . $_POST['forwhom'] . ':' . ' ' . $_POST['message'] . ' ' . $_POST['importance'] . "\n");
$ret = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "Success! Student added to database.";
}
}
else {
die('no post data to process');
}
?>
Currently, I am writing to the file "students.html" However, I want to write to the file "Dad.html", which happens to be the input in the field by the name of forwhom.
Basically, I am asking this: What do I use to replace "students.html" (line 3) so that the file name will be the same as the input of the field forwhom?
I apologize if that didn't make any sense. Thank you very much!
First check if data has been posted on your form using $_SERVER['REQUEST_METHOD'] == "POST".
For simplicity sake save all your "POST" requests in a variable eg.
$file = $_POST['forwhom'];
$importance = $_POST['importance'];
$message = $_POST['message'];
I sometimes find it much easier using empty() instead of isset().
Create a variable, lets say $status which would store all your messages, then any where in your HTML section you just use the $status to display the appropriate message to the user. Check below how i make use of $status in the form.
By doing so is much cleaner and makes your code more dynamic in a sense.
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$file = $_POST['forwhom'];
$importance = $_POST['importance'];
$message = $_POST['message'];
if (!empty($file) && !empty($importance) && !empty($message)) {
$data = nl2br('-' . $file . ':' . ' ' . $message . ' ' . $importance . "\n");
$file .= ".html";
$ret = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
if ($ret == true) {
$status = "Success! Student added to database.";
} else {
$status = "Error writing to file!";
}
} else {
$status = "Please enter name, email and message";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post">
<ul>
<li>
<label for="name">Name: </label>
<input type="text" name="forwhom" id="forwhom">
</li>
<li>
<label for="email">Email: </label>
<input type="text" name="importance" id="importance">
</li>
<li>
<label for="message">Your Message: </label><br>
<textarea name="message" id="message"></textarea>
</li>
<li>
<input type="submit" value="Go!">
</li>
</ul>
<?php if(isset($status)): ?>
<p><?= $status; ?></p>
<?php endif; ?>
</form>
</body>
</html>
I added a form just for explanation sake, hope it helps.

PHP function showing blank screen?

I am copying a youtube video tutorial for private messaging. The rest of the tutorial works fine, but as soon as I add this function to my site, my entire site goes blank and nothing is shown? No errors or anything, just a white screen? Have I done something wrong here? Here is the function:
<?php
function fetch_user_ids($usernames){
foreach ($usernames as &$name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
$names = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$names[$row['username']] = $row['userid'];
}
return $names;
}
?>
Here is the script to send the information:
<?php
if (isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if (empty($_POST['to'])){
$errors[] = 'You must enter atleast one name.';
}else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
}else{
$usernames = explode(',', $_POST['to']);
foreach ($usernames as &$name){
$name = trim($name);
}
$user_ids = fetch_user_ids($usernames);
if (count($user_ids) !== count($usernames)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($usernames, array_keys($user_ids)));
}
}
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty';
}
if (empty($_POST['body'])){
$errors[] = 'You body must have some text!';
}
if (empty($errors)){
//Send message
}
}
if (isset($errors)){
if (empty($errors)){
echo '<div class="msg success">Your message has been sent ! return</div>';
}else{
foreach ($errors as $error){
echo '<div class="msg error">', $error, '</div>';
}
}
}
?>
<form action="" method="POST">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" />
</div>
<div>
<textarea name="body" rows="10" cols="110"></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</form>
If I take away the "function" part, I can print the data, so it must be something to do with the function element?
I would suggest changing the !== to != and seeeing if that works, it could be interpreting it has a number and not as a bool
Make it simpler. Inside foreach, get rid of &$name and replace it with $name. Also check if your database is returning nothing.
foreach ($usernames as $name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
// Check if the query itself is failing or not here:
if(!$result) die("Failed to perform query");
$names = array();
// Check if the database is returning any rows or not:
print_r(mysql_num_rows($result));
while($row = mysql_fetch_assoc($result)){
$names[$row['username']] = $row['userid'];
}
return $names;

Categories