Refreshing Page With Php - php

I'm working on a php code where I'm echoing out form values and a file onto the page. I have that working fine but I want to implement a start over button when pressed will display the page again without the echoes. Any suggestions or better ways to do this?
<html>
<head>
</head>
<body>
<div class="page">
<h1>File Loader</h1>
<form method="post">
<label>Name:</label><input type="text" name="name"></br>
<label>Date:</label><input type="text" name="date"></br>
<input type="submit" name="submit" value="Submit">
<input type="button" name="startOver" value="Start Over" onclick="phpfile.php"></br>
</form>
</div>
<?php
if ($_POST['submit']) {
$name = $_POST['name'];
$date = $_POST['date'];
echo "Name: $name</br></br>";
echo "Date: $date</br>";
$file_handle = fopen("file.csv", "r");
while (!feof($file_handle) ) {
$fields_of_text = fgetcsv($file_handle, 2024);
$f = $fields_of_text;
$format = "%s %s %s %s %s %s %s %s %s %s %s";
echo "<br>" . sprintf($format, $f[0], $f[1], $f[2], $f[3], $f[4], $f[5], $f[6], $f[7], $f[8], $f[9], $f[10]);
echo "<br>";
echo "<br>";
echo "<br>";
}
fclose($file_handle);
} else {
header("Location: phpfile.php");
}
?>
</div>
</body>
</html>

You can easily use query string/post params.
You can use $_GET like below or you can use a hidden input and change that to 1 or 2 with the onclick and javascript if you need to use post.
</head>
<body>
<div class="page">
<h1>File Loader</h1>
<form method="post">
<label>Name:</label><input type="text" name="name"></br>
<label>Date:</label><input type="text" name="date"></br>
<input type="button" value="Submit" onclick="window.location.href='phpfile.php?SubmitType=1';">
<input type="button" value="Start Over" onclick="window.location.href='phpfile.php?SubmitType=2';">
</br>
</form>
</div>
<?php
if ($_GET['SubmitType'] == '1') {
$name = $_POST['name'];
$date = $_POST['date'];
echo "Name: $name</br></br>";
echo "Date: $date</br>";
$file_handle = fopen("file.csv", "r");
while (!feof($file_handle) ) {
$fields_of_text = fgetcsv($file_handle, 2024);
$f = $fields_of_text;
$format = "%s %s %s %s %s %s %s %s %s %s %s";
echo "<br>" . sprintf($format, $f[0], $f[1], $f[2], $f[3], $f[4], $f[5], $f[6], $f[7], $f[8], $f[9], $f[10]);
echo "<br>";
echo "<br>";
echo "<br>";
}
fclose($file_handle);
}
else {
header("Location: phpfile.php");
exit();
}
?>
</div>
</body>
</html>

Related

call variable using $_POST php

<body onload="cmdform.command.focus()">
<form method="POST" action="#" name="cmdform">
<textarea style="width:100%; height:90%; background:black; color:green;" name="textarea" cols="20" >
<?php
$name="My Name";
if (isset($_POST['submit'])){
if (!empty($_POST['command'])){
echo $me = $_POST['textarea'];
echo "\n";
echo $_POST['command'];
}else{
echo $me = $_POST['textarea'];
}
}
?>
</textarea>
<input type="text" name="command">
<input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="B2">
</form></body>
When I enter $name in textbox("command")
'My Name' should display in textarea
You can solve this with a simple str_replace() call.
$content = str_replace('$name', $name, $content);
Or you use an if() statement to check if the content is exactly the string "$name".
if ($_POST['command'] == '$name') {
$content = $name;
}

HTML PHP form not working [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I have made a form, which adds some lines inside another file, called data.php.
Here is the code:
<?php
if (isset($_POST['post'])){
// GET EMAIL
$post_text = $_POST["post_text"];
if($post_text == '') $error = "Post content is empty";
$filename = getcwd() . "data.php";
$line_i_am_looking_for = 1;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$line_i_am_looking_for] = $post_text;
file_put_contents( $filename , implode( "\n", $lines ) );
?>
<html>
<head>
</header
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
if ($error) {
?>
<script type="text/javascript">
// close the errordiv in secs
window.setTimeout("close();", 4000);
function close(){
document.getElementById("errordiv").style.display="none";
}
</script>
<?php
}
?>
<div id="errordiv" style="display:block; color:#FF3535">
<b><?php if($error) echo $error; ?></b>
</div>
Email:
<input name="post_text" size="30" type="text">
<input class="button" value="Submit" type="submit" name="post">
</form>
</body>
</html>
When I open index.php, enter some words in the text box and submit the form, I want to write the entered text in the second line of data.php file.
But it's not working.
I was looking into the code and I found the answer my self.
There was a missing } in my code. The edited code is here:
<?php
if (isset($_POST['post'])){
// GET EMAIL
$post_text = $_POST["post_text"];
if($post_text == '') $error = "Post content is empty";
$filename = getcwd() . "/data.php";
$line_i_am_looking_for = 1;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$line_i_am_looking_for] = $post_text;
file_put_contents( $filename , implode( "\n", $lines ) );
}
?>
<html>
<head>
</header
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
if($error){
?>
<script type="text/javascript">
// close the errordiv in secs
window.setTimeout("close();", 4000);
function close(){
document.getElementById("errordiv").style.display="none";
}
</script>
<?php
}
?>
<div id="errordiv" style="display:block; color:#FF3535"><b><?php if($error) echo $error; ?></b></div>
Email:
<input name="post_text" size="30" type="text">
<input class="button" value="Submit" type="submit" name="post">
</form>
</body>
</html>

How to display message in php without using alert or confirm?

I want to show the changes made in current file after submitting form as message without alert and confirm.How can I do this?
I update language with:
$query="update `account_detail` set `prompt_language`= '$language' WHERE `org_id`='".$_SESSION['account_id']."'";
$result = $mysqli->query($query) or die($mysqli->error);
$Msg="updated language to $language";
function logToFile($filename, $msg)
{
$fd = fopen($filename, "a");
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
fwrite($fd, $str . "\n");
fclose($fd);
}
logToFile("change.log", "updated language to $language");
header("location:".SITE_URL."index.php?view=view_service");
I put all cheanges made in file.And also want to show as message.
Something along the lines of:
<?PHP
if(isset($_REQUEST['something']))
{
echo('you made some changes...');
}
else
{ ?>
<form method="POST">
<input name="something" type="text" />
<!-- rest of code here... -->
<button type="submit">
</form>
<?PHP
}
?>
The logic being, if the variable has been set (i.e. the form has been submitted) then echo out a message to the page, othewise display the form.
try something like this:
your view page:
<body>
<div id="message"><?PHP
if(isset($_REQUEST['msg']))
{
echo $_REQUEST['msg'];
}
?>
</div>
<form method="POST" action="submit.php">
<input name="language" type="text" />
<!-- rest of code here... -->
<button type="submit" >SUBMIT</button>
</form>
</body>
your submit.php
<?php
if(isset($_POST['language'])){
$msg=array();
$language=$_POST['language'];
$Msg="updated language to $language";
logToFile("change.log", "updated language to $language");
////yor rest pf the code
header("location:view1.php?view=view_service&msg=".$Msg);
}
function logToFile($filename, $msg)
{
$fd = fopen($filename, "a");
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
fwrite($fd, $str . "\n");
fclose($fd);
}
?>

Problems inserting data into MYSQL database using PHP

I am still a beginner at PHP/MYSQL and I am having difficulties inserting data into my MYSQL database. (I've originally tried using my localhost database but once i moved to an online server, everything seems to stop working.)
Right now, as soon as i submit the data from my index.php page.. it only refreshes the page and doesn't add any data.
However, when I go to submit.php, everything works fine and it adds an empty set of data to my results.php.
My codes are as follows. Any help will be greatly appreciated. Thank you!
Index.php
<html>
<head>
<title>POST variables</title>
<link rel="stylesheet" type="text/css" href="css/style.css" media="all">
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if (!$con) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo '<div class="container">
<form id="profiles">
<div class="header">
<h3>Hello there!</h3>
<p>We want to know more about you! Share a few interesting details about yourself using the form below!</p>
</div>
<div class="sep"></div>
<div class="inputs">
<form action="submit.php" method="post">
<input id="name" name="name" placeholder="Full Name" required="" autofocus="" autocomplete="on" type="text">
<input id="email" name="email" placeholder="Email Address" required="" autofocus="" autocomplete="on" type="text">
<input id="colour" name="colour" placeholder="Favourite Colour" required="" autofocus="" autocomplete="on" type="text">
<input id="music" name="music" placeholder="Favourite Song" required="" autofocus="" autocomplete="on" type="text">
<input id="superpower" name="superpower" placeholder="If you had a superhero ability, what would it be?" required="" autofocus="" autocomplete="on" type="text">
<button id="submit" type="submit"name="submit" value="added">Submit!</button>
</form> </div>
</div>';
?>
</body>
</html>
Submit.php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if(isset($_POST["name"])){
$name = $_POST["name"];
} else {
$name = "";
}
if(isset($_POST["email"])){
$email = $_POST["email"];
} else {
$email = "";
}
if(isset($_POST["colour"])){
$colour = $_POST["colour"];
} else {
$colour = "";
}
if(isset($_POST["music"])){
$music = $_POST["music"];
} else {
$music = "";
}
if(isset($_POST["superpower"])){
$superpower = $_POST["superpower"];
} else {
$superpower = "";
}
$sql = "INSERT INTO profiles (name, email, colour, music, superpower) VALUES ('$name', '$email', '$colour', '$music', '$superpower')";
if(mysqli_query($con, $sql)){
header ('location: results.php'.$query_string);
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);
}
if($name !== "" && $email !== "" && $colour !== "" && $music !== "" && $superpower !== "") {
$query_string = '?name=' . $name.'&email='.$email.'&colour='.$colour.'&music='.$music.'&superpower='.$superpower;
header('HTTP/1.1 303 See Other');
header ('location: results.php'.$query_string);
}
?>
And my results page.
<html>
<head>
<title>POST Success</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if(isset($_GET["name"])){
$name = $_GET["name"];
} else {
$name = "no name";
}
if(isset($_GET["email"])){
$email = $_GET["email"];
} else {
$email = "no email";
}
if(isset($_GET["colour"])){
$colour = $_GET["colour"];
} else {
$colour = "no colour:";
}
if(isset($_GET["music"])){
$music = $_GET["music"];
} else {
$music = "music";
}
if(isset($_GET["superpower"])){
$superpower = $_GET["superpower"];
} else {
$superpower = "superpower";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM profiles");
echo "<div style='border:solid 1px #ccc;padding:10px;float:left;margin-top:10px;'>";
echo "<table border='1'> <tr> <th>Name</th> <th>Email</th> <th>Favourite Colour</th>
<th>Favourite Music</th>
<th>Superhero Ability</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['colour'] . "</td>";
echo "<td>" . $row['music'] . "</td>";
echo "<td>" . $row['superpower'] . "</td>";
echo "</tr>";}
echo "</table>";
echo "</div>";
mysqli_close($con);
?>
</body>
</html>
Your form has no action, so it'll submit the form to the URL you loaded the page from, which will be index.php.
You need this:
<form id="profiles" action="Submit.php" method="POST">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note the method portion as well - with no method, forms default to using GET
Be careful you have two form in your index.php.
<form id="profiles">
and
<form action="submit.php" method="post">
I think the first one is useless.

PHP setcookie is not working

I know there are quite a few threads out there that deals with this question but every question seems unique (or so...)
I'm having trouble setting a cookie so that I can validate the user against it later
A php newbie....what might be the problem here?
I've checked the php.ini file and cookies are allowed.
<?php
$capt_error = "";
$already_made_post = "";
$mismatch = "";
$name = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
session_start();
if (empty($_POST["capt"])) {
$capt_error = "Fältet är obligatoriskt.";
} else {
// validate captcha
if($_POST['capt'] != $_SESSION['rand']) {
$name = $_POST["name"];
$message = $_POST['message'];
$mismatch = "Inmatningen av CAPTHA är fel. Vänligen prova igen.";
}
else {
$ip_address = $_SERVER['REMOTE_ADDR'];
$time_stamp = date('Y-m-d H:i');
$cookie_name = $_POST['name'];
$cookie_value = $ip_address;
// write to file but only if cookie is not set
if(isset($_COOKIE[$cookie_value]) && $_COOKIE[$cookie_value] == $cookie_value) {
$already_made_post = "Du har redan ett inlägg i gästboken!";
}
else {
$data = "\n" . $_POST['name'] . ',' . $_POST['message'] . ',' . $ip_address . ',' . $time_stamp;
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if ($ret == false) {
die('Fel vid skrivning till fil. Skrivrättigheter saknas');
}
// set cookie
setcookie($cookie_name, $cookie_value); // IS NOT SET
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
}
}
}
}
?>
<link rel="stylesheet" href="labb1.css" type="text/css">
<html>
<head>
<title>Labb 1</title>
</head>
<body>
<h1 class="title">Laboration 1 - Gästboken</h1>
<table border="1">
<thead>
<tr>
<th colspan="3" class="table-title">Min Gästbok</th>
</tr>
</thead>
<tbody>
<tr>
<td class="bold">FRÅN</td>
<td class="bold">INLÄGG</td>
<td class="bold">LOGGNING</td>
</tr>
<?php
// open file
$f = fopen("data.txt", "r");
// while not end of file
while (!feof($f)) {
// split values with -
$arr = explode(",", trim(fgets($f), "\r\n"));
print "<tr>";
print "<td>$arr[0]</td>";
print "<td>$arr[1]</td>";
print "<td>IP: $arr[2]<br>TID: $arr[3]</td>";
print "</tr>";
}
?>
</tbody>
</table>
<form action="" method="post">
<div class="border">
<div>
<span>Namn:</span>
<input type="text" name="name" value="<?php echo $name;?>">
</div>
<div>
<span>Meddelande:</span>
<textarea name="message" rows="5"><?php echo $message;?></textarea>
</div>
<div>
<?php
$rand = substr(str_shuffle(str_repeat("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
session_start();
$_SESSION["rand"] = $rand;
print "<span>CAPTCHA skriv detta i rutan nedan: </span> <span class='red bold'>$rand</span>"
?>
<span class="error">* <?php echo $capt_error; ?></span>
<input type="text" name="capt">
<span class="error"><?php echo $mismatch?></span>
</div>
<div>
<input type="submit" value="Skicka">
</div>
<div>
<span class="red">*</span> är ett obligatoriskt fält
</div>
<div>
<span class="error"><?php echo $already_made_post?></span>
</div>
</div>
</form>
</body>
</html>
session_start(); should be at the top of the page for the sessions to work. In your code above it only gets called when the user submits the form. Move it to line 2.
I read your code and now I see this
setcookie($cookie_name, $cookie_value); // IS NOT SET
if(!isset($_COOKIE[$cookie_name])) {
From common pitfalls
Cookies will not become visible until the next loading of a page that
the cookie should be visible for.
You have not set the expire perameter:
Set your cookies like this
$expire=time()+60*60*24*30;
setcookie ("name","value", $expire,"/");
$expire variable holds the value time when our cookies should expire,

Categories