I'm trying to pass $_POST info as $_SESSION but when it doesn't work, I don't know what is wrong in my code.
<?php
session_start();
$_SESSION['nombre'] = $_POST['nombre'];
$_SESSION['edad'] = $_POST['edad'];
?>
<html>
<form action="accion.php" method="post">
<p>Name: <input type="text" name="nombre" /></p>
<p>Age: <input type="text" name="edad" /></p>
<p><input type="submit" /></p>
</form>
</html>
Second file
<?php
session_start();
if(isset($_SESSION['nombre']) && isset($_SESSION['edad'])) {
$data = $_SESSION['nombre'] . '-' . $_POST['edad'] . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
The following code will solve your problem:
File1.php
<html>
<form action="File2.php" method="post">
<p>Name: <input type="text" name="nombre" /></p>
<p>Age: <input type="text" name="edad" /></p>
<p><input type="submit" /></p>
</form>
</html>
<?php
echo $_GET['msg'];
?>
File2.php
<?php
session_start();
if(isset($_POST['nombre']) && isset($_POST['edad'])) {
$_SESSION['nombre'] = $_POST['nombre'];
$_SESSION['edad'] = $_POST['edad'];
$data = $_SESSION['nombre'] . '-' . $_POST['edad'] . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
header("Location:File1.php?msg=There was an error writing this file");
}
else {
header("Location:File1.php?msg=$ret bytes written to file";
}
}
else {
header("Location:File1.php?msg=no post data to process");
}
?>
When the form is submitted, it is submitted to File2.php
So, your first session being set and taking values as POST from it in File1.php won't work.
The best option is to set the session in the second file and then give back a message to the File1.php as shown above.
Check the code bellow. It is better to start session once at the begining of the file and check if post variable contains value to set in the session.
<?php
session_start();
if(isset($_POST['nombre']) && isset($_POST['edad'])) {
$_SESSION['nombre'] = $_POST['nombre'];
$_SESSION['edad'] = $_POST['edad'];
}
?>
<html>
<form action="accion.php" method="post">
<p>Name: <input type="text" name="nombre" /></p>
<p>Age: <input type="text" name="edad" /></p>
<p><input type="submit" /></p>
</form>
</html>
<?php
if(isset($_SESSION['nombre']) && isset($_SESSION['edad'])) {
$data = $_SESSION['nombre'] . '-' . $_POST['edad'] . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
If you want to send the form in the same page instead using action="action.php" use action=""
Related
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'])
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.
Ok, I have a script called profile.php and I would like the user to interact with profile.php "form input" from a different html page or php script such as user_settings.php.
I would like to have the errors ONLY from profile.php to be displayed/echoed/printed on user_settings.php page. I have tried the following
----profile.php---
<?php ob_start(); require_once ("core/init.php"); ?>
<?php require ("includes/overall/header.php"); ?>
<?php
if(has_access($session_user_id, 1) === true){
$message[] = '<p class="admin"> **Admin**</p>';
}
?>
<div id="mainInfo">
<p class="profile"> Hello <?php echo $user_data['first_name'], '!' .output_message($message) ;?> </p><br /><br />
<?php
if(isset($_FILES['image']) === true)
{
if(empty($_FILES['image']['name']) === true)
{
$errors_image[] = 'Please choose a file';
}
else
{
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['image']['name'];
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['image']['tmp_name'];
if(in_array($file_extn, $allowed) === true)
{
change_profile_image($session_user_id, $file_temp, $file_extn);
header('Location: profile');
exit();
}
else
{
$errors_image[] = 'Incorrect file type. Allow: ';
echo implode(', ', $allowed);
}
}
}
if(empty($user_data['image']) === false)
{
echo '<p class="photo"><image src="', $user_data['image'],'" alt="', $user_data['first_name'], '\'s Profile Image"></p> <br>';
}
?>
<p class="usr_sttngs"> Update Info!</p><br />
</div>
<?php require ("includes/overall/footer.php"); ?>
--------usr_sttngs.php------------
<?php ob_start();
require_once ("core/init.php");
ini_set('display_errors', 'On'); error_reporting(E_ALL);
protect_page(); ?>
<?php
if(empty($_POST) === false)
{
$required_fields = array('current_passwd','passwd', 'passwd_again');
foreach($_POST as $key => $value)
{
if (empty($value) && in_array($key, $required_fields) === true)
{
$errors[] = '<p class="postad_msg">Fields marked with * are required.</p>';
break 1;
}
}
if (sha1($_POST['current_passwd']) === $user_data['passwd'])
{
if(trim($_POST['passwd']) !== trim($_POST['passwd_again']))
{
$errors[] = '<p class="postad_msg">New passwords DO NOT match!</p>';
}
else if (strlen($_POST['passwd']) < 6)
{
$errors[] = '<p class="postad_msg">New passwords must be at least 6 characters.</p>';
}
}
else
{
$errors[] = '<p class="postad_msg">Your current password is incorrect!</p>';
}
}
?>
<?php require ("includes/overall/header.php"); ?>
<div id="mainInfo">
<br /> <br /><p3>Change Password!</p3> <br /> <br />
<?php
if(isset($_GET['success']) && empty($_GET['success']))
{
$message[] = '<p class="postad_msg">Your password has been changed successfully.</p>';
}
if(empty($_POST) === false && empty($errors) === true)
{
change_passwd($session_user_id, $_POST['passwd'] );
//redirect
header('Location: usr_sttngs?success');
//exit
exit();
}
else if(empty($errors) === false)
{
output_errors($errors);
}
?>
<form method="post" action="usr_sttngs">
<fieldset>
<label for="currentpasswd">Current password* </label>
<input placeholder="Type your current password" type="password" name="current_passwd" size="30" maxlength="50" value="<?php echo htmlentities($current_passwd); ?>" /><br /><br />
<label for="last_name">New Password* </label>
<input placeholder="New Password" type="password" name="passwd" size="30" maxlength="50" value="<?php echo htmlentities($new_passwd); ?>" /><br /><br />
<label for="email">New Password Again* </label>
<input placeholder="Retype New Password" type="password" name="passwd_again" size="30" maxlength="50" value="<?php echo htmlentities($new_passwd_again); ?>" />
</fieldset>
<fieldset class="center">
<input class="submit" type="submit" name="submit" value="Change Password" />
<?php echo output_errors($errors); ?>
<?php echo output_message($message);?>
</fieldset>
</form>
<p4>Change profile photo!</p4> <br /> <br />
<form action="profile" method="post" enctype="multipart/form-data">
<fieldset class="center">
<input type="file" name="image"> <input type="submit">
<?php echo output_errors($errors_image);
require_once ('$_SERVER["DOCUMENT_ROOT"]\profile.php');
?>
</fieldset>
</form>
<br /><br /><br /><p4>Upload your resume!</p4> <br />
<form action="profile" method="post" enctype="multipart/form-data">
<fieldset class="center">
<input type="file" name="resume"> <input type="submit">
</fieldset>
</form>
</div>
<?php require ("includes/overall/footer.php"); ?>
I tried something I read on the following post Want to echo a php variable from another page but I did not get the desired results. So I tried to include the required_once 'profile.php' ; at the very top of the user_setting.php file and that just gives me a blank page. Any help would be greatly appreciated. Thank you!
Require or Require_once must be called before any HTML is displayed.
Try placing your require_once at the beginning of the file.
EDITED
Try the following test code to see if you can get it working.
The profile.php should contain the following:
<?php
echo "profile.php is displaying correctly";
?>
The user_settings.php should contain the following:
<?php
require_once("profile.php");
?>
See if you can get this basic code to work. Post your results
I get the bellow page when I try the code above:
So I have a variable well defined in a php page and I'm using it in an HTML page using include.
I am currently building a page where I can change the Var ( because it's a long text, more than one actually, and to change them it will be nice to have a page with a layout just for that) so I'm using a textbox and a submit button just like this:
<?php
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
?>
<form method="post">
Titre: <input name="titre" type="text" id="titre" value="<?php echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
$titre = $_POST['titre'];
echo($titre);
}
?>
The problem is that in the echo it shows the new text but if I do a refresh it will show the old one...
any ideas how can I do this?
EDIT: Added extra fields and data handler. See extra code below original answer.
Here is some code I came up with to write content to a file.
Note: To add to the file with content written one under the other, use the a or a+ switch.
To create and write content to file and overwrite previous content, use the w switch.
This method uses the fwrite() function.
(tested)
Added to OP's code: action="write.php"
FORM
<?php
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
?>
<form method="post" action="write.php">
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
PHP write to file handler (write.php)
This example uses the w switch.
<?php
if (isset($_POST['submit']))
{
$titre = $_POST['titre'];
echo($titre);
}
?>
<?php
$filename = "output.txt"; #Must CHMOD to 666 or 644
$text = $_POST['titre']; # Form must use POST. if it uses GET, use the line below:
// $text = $_GET['titre']; #POST is the preferred method
$fp = fopen ($filename, "w" ); # w = write to the file only, create file if it does not exist, discard existing contents
if ($fp) {
fwrite ($fp, $text. "\n");
fclose ($fp);
echo ("File written");
}
else {
echo ("File was not written");
}
?>
EDIT: Added extra fields and data handler.
Extra fields can be added, and must be followed in the same fashion in the file handler.
NEW FORM with extra fields
File data example: test | email#example.com | 123-456-7890
<?php
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
?>
<form method="post" action="write.php">
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<br>
Email: <input name="email" size="50" maxlength="50">
<br>
Telephone: <input name="telephone" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
$titre = $_POST['titre'];
echo($titre);
}
?>
PHP write to file handler
<?php
$titre = $_POST['titre'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$data = "$titre | $email | $telephone";
$fp = fopen("data.txt", "a"); // a-add append or w-write overwrite
if ($fp) {
fwrite ($fp, $data. "\n");
fclose ($fp);
echo ("File written successfully.");
}
else{
echo "FAILED";
}
?>
<?php
if(!($titre = file_get_contents("filename.txt"))){
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
}
?>
<form method="post">
Titre: <input name="titre" type="text" id="titre" value="<?php echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$titre = $_POST['titre'];
if(#file_put_contents("filename.txt", $titre))){
echo 'Success - var stored.';
} else { echo 'Some error.'; }
echo($titre);
}
?>
Try this :
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
If you need to keep your value for ever, you should store it in a database or save it in a file (could be .txt).
[EDIT]
Here is the code for .txt solution (you first create a file.txt in the same folder):
<?php
$file = 'file.txt';
$lines = file("file.txt");
if (!isset($lines[0])) {$titre='Bienvenido a PARIS EXPERT LIMOUSINE ! ';}
else {$titre=$lines[0];}
?>
<form method="post">
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
echo($_POST['titre']);
$titre = $_POST['titre']."\n".$titre;
file_put_contents($file, $titre);
}
?>
Hope it helps :)
this is normal because you're showing the new content upon form submission. When you refresh the page, unless you tell it to send the POST data again with the refresh (which the browser asks you for confirmation), your form (and hence the input field) will have nothing in.
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