PHP ob_flush not working on foreach - php

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

Related

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

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;

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 fopen not working

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');

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">

PHP: Remove Simple Session with Get-Method

I want to Remove the Sessions from this php code, actually if someone searches i get this url search.php?searchquery=test but if I reload the page, the results are cleaned. how can I remove the Sessions to get the Results still, if someone reloads the page? this are the codes:
search.php
<?php
session_start();
?>
<form method="get" 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']);
}
?>
querygoogle.php
<?php
session_start();
$url = 'http://www.example.com';
$handle = fopen($url, 'rb');
$body = '';
while (!feof($handle)) {
$body .= fread($handle, 8192);
}
fclose($handle);
$json = json_decode($body);
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: search.php?searchquery=" . $_GET['searchquery']);
exit;
?>
thank you for your help!!
This is against google's terms of use. Use google API

Categories