PHP fopen not working - php

I just can't figure this out, I keep getting Unable To Create Group.
What I'm attempting to do is you submit a forum, and it creates a file with some info in it. If the group name already exist(the file) then tell them that. Though I keep getting as I stated "Unable To Create Group" as my die message.
This is the PHP part:
<?php
if($_POST['ownername'] && $_POST['groupname']){
$ownername = htmlspecialchars($_POST["ownername"]);
$groupname = htmlspecialchars($_POST["groupname"]);
echo 'Owner is ' . $ownername . ' and the group is ' . $groupname;
$groupfile = '/groups/' . $groupname . '.txt';
if(file_exists($groupfile) == false){
$newgroup = fopen($groupfile, 'w') or die("Unable to create group");
$txt = "Users:" . $ownername;
fwrite($newgroup, $txt);
fclose($myfile);
echo "<font style='color:green'>The group has been created! You may access it <a href='chat.php?group=" . $groupname . "'>here</a></font>";
} else {
echo "<font style='color:red'>The group name is taken, please use another name or wait for it to be released</font>";
}
}
?>
Then this is my HTML part:
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
<input type="text" name="ownername" placeholder="Username"/>
<input type="text" name="groupname" placeholder="Group Name"/>
<input type="submit" value="Create"/>
</form>
Any and all help is appreciated, thank you very much!

If the filename doesn't exist yet, use 'x' instead of 'w' to create a file and allow writing into.
$newgroup = fopen($groupfile, 'x');

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>";
}
}
}
?>

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 form error issue

There is probably a simple solution for this but i'm not very proficient in php! Basically I want to submit a form and the user be returned with a thank you overlay image without refresh. I've managed to get this to work BUT now the form validating isn't working properly...
I need to make my overlay only appear after the form validating is successful, if it isn't successful I need to display the error instead of the thank you overlay...
I know I could use ajax for this form but I don't want to rely on javascript!
At the minute the validating is working, but the image is being overlayed on top of it...
This is php code:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter your name</li>";
}
if(empty($_POST['formTown']))
{
$errorMessage .= "<li>You forgot to enter your town</li>";
}
$varName = $_POST['formName'];
$varTown = $_POST['formTown'];
$varAge = $_POST['formAge'];
$varEmail = $_POST['formEmail'];
$varOne = $_POST['hidden-one'];
$varTwo = $_POST['hidden-two'];
$varThree = $_POST['hidden-three'];
$varFour = $_POST['hidden-four'];
$varFive = $_POST['hidden-five'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,"\n" . $varName . ", " . $varTown . ", " . $varAge . ", " . $varEmail . ", " . $varOne . $varTwo . $varThree . $varFour . $varFive);
fclose($fs);
}
}
?>
This is my html (with the php code):
<?php
if (isset($_POST['formSubmit'])) {
print "<div class=\"thank-you\"><a href='enter.php'><img src='images/thankyou-overlay.png'/></a></div>\n";
}
?>
<div id="mainContainer">
<p>Just complete your entry details below.</p>
<?php
if(!empty($errorMessage)) {
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" target="_self">
<div class="inputContainer">
<label class="text" name="name">Full Name:</label>
<input type="text" class="box" name="formName" value="<?=$varName;?>">
</div>
... more html inputs...
</form>
Whatever you are going to do, you have to use Javascript. You can choose AJAX either using an iframe where you direct your post to, and reading it in a javascript to check status of posting.
Edit:
Like this you can post it:
<form action="do_stuff.aspx" method="post" target="my_iframe">
<input type="submit" value="Do Stuff!" />
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
So after the post, you have to read status from this iframe, (in other words de HTML output from it).
First , i am having difficulty comprehending what you are trying to do : But still i can point out a few things that have better alternates ;
You should put this code
if($_POST['formSubmit'] == "Submit")
{
...
}
above the form for the functionality you want
and also the above if should have an else to show the form when there are errors.
like
else
{
---form---
}
try this and c if it helps

How can I create a Searchstring for a Google AJAX Search API?

i have this code to get the search resutls from the api:
querygoogle.php:
<?php
session_start();
// Here's the Google AJAX Search API url for curl. It uses Google Search's site:www.yourdomain.com syntax to search in a specific site. I used $_SERVER['HTTP_HOST'] to find my domain automatically. Change $_POST['searchquery'] to your posted search query
$url = 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&start=20&q=' . urlencode('' . $_POST['searchquery']);
// use fopen and fread to pull Google's search results
$handle = fopen($url, 'rb');
$body = '';
while (!feof($handle)) {
$body .= fread($handle, 8192);
}
fclose($handle);
// now $body is the JSON encoded results. We need to decode them.
$json = json_decode($body);
// now $json is an object of Google's search results and we need to iterate through it.
foreach($json->responseData->results as $searchresult)
{
if($searchresult->GsearchResultClass == 'GwebSearch')
{
$formattedresults .= '
<div class="searchresult">
<h3>' . $searchresult->titleNoFormatting . '</h3>
<p class="resultdesc">' . $searchresult->content . '</p>
<p class="resulturl">' . $searchresult->visibleUrl . '</p>
</div>';
}
}
$_SESSION['googleresults'] = $formattedresults;
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
?>
search.php
<?php
session_start();
?>
<form method="post" action="querygoogle.php">
<label for="searchquery"><span class="caption">Search this site</span> <input type="text" size="20" maxlength="255" title="Enter your keywords and click the search button" name="searchquery" /></label> <input type="submit" value="Search" />
</form>
<?php
if(!empty($_SESSION['googleresults']))
{
echo $_SESSION['googleresults'];
unset($_SESSION['googleresults']);
}
?>
but with this code, I cant add a searchstring..
how can i add a search string like search.php?search=keyword ?
thanks
ok, have it! changed into this code:
querygoogle.php
$_SESSION['googleresults'] = $formattedresults;
header("Location: search.php?searchquery=" . $_GET['searchquery']);
exit;
... &start=20&q=' . urlencode('' . $_GET['searchquery']);
search.php
<form method="get" action="querygoogle.php">

Categories