First of all, this is my first question ever on stackoverflow. It's a great place to get answers from other's problems. But this time I couldn't find an answer to mine, so my question below...
I am having exactly the same issue as described in this question:
Simple form not sending data via _POST
It's exactly the same problem: even var_dump($_POST); shows me this: array(0) { } and trying to access the data passed gives me a Notice: Undefined index
I have been scratching my head for the last 2 days.
My code:
<form action="" method="POST" id="test">
<label for="email">Email</label><br>
<input type="text" name="email" id="email" value=""><br>
<input class="btn btn-primary btn-lg btn-block mb-5" type="submit" name="save-company-button" id="save-company-button" value="SAVE">
</form>
This is the simplest form and it still doesn't work. I don't understand why.
Thanks in advance for your help.
EDIT:
Content of the view:
<?php
$siteroot = SITEROOT;
// Metadata
$meta_data_title = "About us";
// Page title
$main_title = "About us";
// Additional CSS to the main CSS (bootstrap.css and custom-style.css)
$other_css = "";
// Javascript
ob_start();
require "viewAboutUs/viewAboutUs-javascript.php";
$javascript = ob_get_clean();
// Breadcrumb
$breadcrumb = "<li class=\"breadcrumb-item\">Home</li>
<li class=\"breadcrumb-item active\" aria-current=\"page\">About us</li>";
// Main content
ob_start();
require "viewAboutUs/viewAboutUs-content.php";
$main_content = ob_get_clean();
// Javascript at the bottom
$javascript_bottom = "";
// Template file
require "template.php"
?>
Content of viewAboutUs-content.php:
<form action="" method="POST" id="test">
<label for="email">Email</label><br>
<input type="text" name="email" id="email" value=""><br><br>
<input class="btn btn-primary btn-lg btn-block mb-5" type="submit" name="save-company-button" id="save-company-button" value="SAVE">
</form>
The file viewAboutUs-javascript.php is empty.
Content of the controller displayAboutUs.php:
<?php
function displayAboutUs() {
var_dump($_POST);
echo "Test: " . $_POST["email"] . "<br>";
if (isset($_POST["save-company-button"])) {
echo "Button clicked ! <br>";
}
require VIEWS_FOLDER . "/pages/viewAboutUs.php";
}
?>
Sorry for the time to provide the code, I am discovering the interface of stackoverflow...
EDIT #1
If I copy-paste the items in a simple php file that I put in my /public/ folder, it works without any problems.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
var_dump($_POST);
echo "Test: " . $_POST["email"] . "<br>";
if (isset($_POST["save-company-button"])) {
echo "Button clicked ! <br>";
}
?>
<form action="" method="POST" id="test">
<label for="email">Email</label><br>
<input type="text" name="email" id="email" value=""><br><br>
<input type="submit" class="btn btn-primary btn-lg btn-block mb-5" name="save-company-button" id="save-company-button" value="SAVE">
</form>
</body>
</html>
The only thing that changes in this case is that I am using bootstrap this time. Otherwise, all my forms would work perfectly the way my code has been organised so far.
EDIT #2
After reviewing my code multiple times, the only conclusion I come to is that the issue must be located at the HTML code of the form itself. Something might be missing in the attributes of the form tag and/or one of the input tags, because the current attributes left are the bare minimum.
If somebody is a HTML5 expert, that might be useful...
EDIT #3
Things seem to indicate that what I write in my EDIT #2 are correct, because if I do a var_dump($_POST); in the main controller (index.php), just before displayAboutUs() is called, the results are the same: no data passed.
So, this form is not sending anything so far the way it is when I click on the submit button, but it does if I copy-paste it in another separate test file.
The question is: why?
After burning my brain and getting close to throwing my computer through the window, I finally got it. So I put the solution here so that other people can learn from my mistake.
The problem was coming from my .htaccess file, which was missing (I had copied-pasted the structure of a previous project as a template for my new one) and, as hidden files were not displayed, I of course missed the .htaccess when manually copying the files...
Here is the missing content that was causing so much trouble:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
So, as a reminder for myself and others, if something even dead simple is desperately not going right, check what you can't see ;-)
Hope this helps! And thanks for those who tried to help.
This question can be closed, but I can't see how to proceed...
Related
I have a php website thats more or less like this. PHP noob here.
Index.php
<?
include('conexion.php');
include('funciones.php');
?>
<head>
</head>
<body>
<?php
if (!empty($_GET["palabra"])) {
function1($conexion);
} elseif (!empty($_GET["letra"])) {
include('letra.php');
} elseif (!empty($_POST["buscar"])) {
include('search.php');
} else {
function3($conexion);
}
?>
</body>
All functions fuctions and database connections are defined in the included files.
Website uses only a single html file, so all the content is included or called by the functions. Is there a good way for the website to identify which "section" or content is the user browsing?
So, for example I want a function to run only when the user is using the search page, should I continue to use the REQUEST to identify what the user is doing? Should I insert a variable like $section and then if($section=search){dosomething()} or maybe using the URL? should I use another approach?
You want something like this?
PHP Page
<?php
switch ($_GET["page"]) {
case 'login':
# code blocks
break;
case 'student_notes':
# code blocks
break;
default:
# code blocks
break;
}
?>
HTML Page
<form id="form1" name="form1" method="post" action="?page=login">
<p>
<label for="studentCount">Kişi Sayısı</label>
<input type="text" name="studentCount" id="studentCount" />
</p>
<p>
<input type="submit" name="button" id="button" value="Send" />
</p>
</form>
<form id="form1" name="form1" method="post" action="?page=student_notes">
<p>
<label for="studentCount">Kişi Sayısı</label>
<input type="text" name="studentCount" id="studentCount" />
</p>
<p>
<input type="submit" name="button" id="button" value="Send" />
</p>
</form>
I believe you are a little bit confuse about what PHP is and what can do.
PHP will execute in the server, meanwhile HTML execute in the client. Who define how to serve and what are you using the language.
For example:
The user click on an item in a menu, each link in the menu would send a URL to the server in a way like this:
<a href="index.php?page=palabra" >PALABRA</a>
<a href="index.php?page=letra" >LETRA<a>
<a href="index.php?page=buscar" >BUSCAR</a>
All those links will open the same page: INDEX.PHP
Is up to yo to define what to do with the $_GET var sent in the URL.
So, in your index.php you can defined:
<?php
switch ($_GET["page"]) {
case 'palabra':
# code blocks - DO SOMETHING
break;
case 'letra':
# code blocks - SHOW SOMETHING
break;
case 'buscar':
# code blocks - SEARCH SOMETHING
break;
}
?>
In that way who control what to show, and when are you.
Any way, PHP have some globals that will point the name of the script or the page being serve:
Check out https://www.php.net/manual/es/reserved.variables.server.php
I will recomend you research a little bit about php and better try to use a framework like cakePHP, Laravel or Simfony for a start. There are many more.
I have couple of identical HTML pages which take user input and with PHP I save the input on text files. As it's always the same I would like to apply the same PHP on every html page. So my question is if there is a way to redirect to the next html page but not through PHP, so that the PHP can be reusable for all the pages?
Because if I add onclick="window.location.href='/main2.html' then the PHP is not fired up or if I change action="main2.html" then again the PHP is not included. Or if I add header("Location: main2.html"); then it cannot really be applied to all the html pages, as it goes main.html -> main2.html -> main3.html etc.
HTML 1:
<form method="post" action="process.php">
<input type="text" name="address" required>
<input type="submit" value="Submit" id="intro">
</form>
HTML 2:
<form method="post" action="process.php">
<input type="text" name="address" required>
<input type="submit" value="Submit" >
</form>
PHP:
<?php
$myfile = fopen("text.txt", "a+");
$address = $_POST['address'].";";
fwrite($myfile, $address);
//header("Location: main2.html");
fclose($myfile);
?>
Thank you in advance!
Although you don't want to use PHP, it can make this pretty simple for you. You can use the session variable in PHP to track the user, the entries he has made and even allow them to go back and forward.
You can read more on it here.
You can redirect the user based on the session counter or the source from where the call is made and direct them accordingly to the next page. This makes your code scalable as well.
So you code will be something like this:
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$newURL = "HTMLPage".$_SESSION['counter']."html";
header('Location: '.$newURL);
The above code will redirect the user to the next page. PS: You will have to handle the case for your last html page.
First time i try to create a simple form using the POST method.Problem is when i click the button nothing gets echoed.
here is my insert.php file :
<?php
if(isset($_POSΤ["newitem"])){
echo $itemnew = $_POSΤ["newitem"];
}
?>
<form action="insert.php" method="POST" >
<input type="text" name="newitem">
<input type="submit" value="Save">
</form>
EDIT: I tried the GET method and it works...Any ideas why that happened? Server configurations?
NEW EDIT: So it turns out i switched method to GET and it worked.Then i switched back to POST (like the code i posted on top) and it works...I have no clue why this happened.Any suggests?
The code you have posted is perfectly valid and should work.
I'm going to guess that you do not have PHP enabled, or it is not working.
<?php ... ?> looks to the browser like a long, malformed HTML tag, and therefore ignores it, making the effect invisible.
Try right-clicking the page and selecting View Source. If you see your PHP there, then the server is indeed not processing it.
The most likely reason for this is probably the same problem I had with my very first bit of PHP code: you're trying to "run" it directly in your browser. This won't work. You need to upload it to a server (or install a server on your computer and call it from there)
Use !empty($_POST['newitem'] instead:
if(!empty($_POSΤ["newitem"])){
echo $itemnew = $_POSΤ["newitem"];
}
empty()
Try the following:
if($_POST) {
if(!empty($_POST['newitem'])) {
$itemnew = $_POSΤ['newitem'];
echo $itemnew;
// or leave it as is: echo $itemnew = $_POSΤ['newitem'];
}
}
?>
<form action="insert.php" method="POST" >
<input type="text" name="newitem">
<input type="submit" value="Save">
</form>
The if($_POST) will make sure the code is only executed on a post. The empty() function will also check if it isset() but also checks if it is empty or not.
Try this :
<?php
if(isset($_POSΤ["newitem"])){
echo $itemnew = $_POSΤ["newitem"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<input type="text" name="newitem">
<input type="submit" value="Save">
</form>
$_SERVER['PHP_SELF']; is pre-defined variable in php.It allows the user to stay on same page after submitting the form.
I have developed a site for a client and he wants to be able to edit a small part of the main page in a backend type of solution. So as a solution, I want to add a very basic editor (domain.com/backend/editor.php) that when you visit it, it will have a textfield with the code and a save button. The code that it will edit will be set to a TXT file.
I would presume that such thing would be easy to code in PHP but google didn't assist me this time so I am hoping that there might be someone here that would point me to the right direction. Note that I have no experience in PHP programming, only HTML and basic javascript so please be thorough in any reply that you provide.
You create a HTML form to edit the text-file's content. In case it get's submitted, you update the text-file (and redirect to the form again to prevent F5/Refresh warnings):
<?php
// configuration
$url = 'http://example.com/backend/editor.php';
$file = '/path/to/txt/file';
// check if form has been submitted
if (isset($_POST['text']))
{
// save the text contents
file_put_contents($file, $_POST['text']);
// redirect to form again
header(sprintf('Location: %s', $url));
printf('Moved.', htmlspecialchars($url));
exit();
}
// read the textfile
$text = file_get_contents($file);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text); ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
To read the file:
<?php
$file = "pages/file.txt";
if(isset($_POST))
{
$postedHTML = $_POST['html']; // You want to make this more secure!
file_put_contents($file, $postedHTML);
}
?>
<form action="" method="post">
<?php
$content = file_get_contents($file);
echo "<textarea name='html'>" . htmlspecialchars($content) . "</textarea>";
?>
<input type="submit" value="Edit page" />
</form>
You're basically looking for a similar concept to that of a contact-form or alike.
Apply the same principles from a tutorial like this one and instead of emailing using mail check out the file functions from PHP.net.
What did you Google on then? php write file gives me a few million hits.
As in the manual for fwrite():
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
But to be honest, you should first pick up a PHP book and start trying. You have posted no single requirement, other than that you want to post a textfield (textarea I mean?) to a TXT file. This will do:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$handle = fopen("home.txt", 'w') or die("Can't open file for writing.");
fwrite($fh, $_POST['textfield']);
fclose($fh);
echo "Content saved.";
}
else
{
// Print the form
?>
<form method="post">
<textarea name="textfield"></textarea>
<input type="submit" />
</form>
<?php
}
Note that this exactly matches your description. It doesn't read the file when printing the form (so every time you want to edit the text, you have to start from scratch), it does not check the input for anything (do you want the user to be able to post HTML?), it has no security check (everyone can access it and alter the file), and in no way it reads the file for display on the page you want.
First thing to do is capture the information, the simplest way to do this would be the use of a HTML Form with a TEXTAREA:
<form method='post' action='save.php'>
<textarea name='myTextArea'></textarea>
<button type='submit'>Go</button>
</form>
On 'save.php' (or wherever) you can easily see the information sent from the form:
<?php
echo $_POST['myTextArea']
?>
To actually create a file, take a look at the fopen/fwrite commands in PHP, another simplistic example:
<?php
$handle = fopen("myFile.txt","w");
fwrite($handle,$_POST['myTextArea'];
fclose($handle);
?>
WARNING: This is an extremely simplistic answer! You will perhaps want to protect your form and your file, or do some different things.... All the above will do is write EXACTLY what was posted in the form to a file. If you want to specify different filenames, overwrite, append, check for bad content/spam etc then you'll need to do more work.
If you have an editor that is publicly accessible and publishes content to a web page then spam protection is a DEFINITE requirement or you will come to regret it!
If you aren't interested in learning PHP then you should think about getting a professional developer to take care of any coding work for you!
I had a similar need so we created a client-friendly solution called stringmanager.com we use on all our projects and places where CMS is not effective.
From your side, you just need to tag string in the code, i.e. from:
echo "Text he wants to edit";
to:
echo _t("S_Texthewantstoedit");
stringmanager.com takes care about the rest. Your client can manage that particular text area in our online application and sync wherever he wants. Almost forgot to mention, it is completely free.
Can use this line of code :
<form action="" method="post">
<textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
<input type="submit" value="submit">
</form>
<?php
$file = "127.0.0.1/test.html";
$test = file_get_contents('1.jpg', 'a');
if (isset($_POST['test'])) {
file_put_contents($file, $_POST["test"]);
};
?>
<form action="" method="post">
<textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
<input type="submit" value="submit">
</form>
Haven't had time to finish it, simplest possible, will add more if wanted.
I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/
The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.
<form method="POST" action="mlml/process.php">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="submit" value="" id="submit"name="submit" >
</form>
You will need AJAX to post the data to your server. The best solution is to implement the regular posting, so that will at least work. Then, you can hook into that using Javascript. That way, posting will work (with a refresh) when someone doesn't have Javascript.
If found a good article on posting forms with AJAX using JQuery .
In addition, you can choose to post the data to the same url. The JQuery library will add the HTTP_X_REQUESTED_WITH header, of which you can check the value in your server side script. That will allow you to post to the same url but return a different value (entire page, or just a specific response, depending on being an AJAX request or not).
So you can actually get the url from your form and won't need to code it in your Javascript too. That allows you to write a more maintanable script, and may even lead to a generic form handling method that you can reuse for all forms you want to post using Ajax.
Quite simple with jQuery:
<form id="mail_subscribe">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="hidden" name="action" value="subscribe" />
<input type="submit" value="" id="submit"name="submit" >
</form>
<p style="display: none;" id="notification">Thank You!</p>
<script>
$('#mail_subscribe').submit(function() {
var post_data = $('#mail_subscribe').serialize();
$.post('mlml/process.php', post_data, function(data) {
$('#notification').show();
});
});
</script>
and in your process.php:
<?php
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'subscribe' :
$email_address = $_POST['address'];
//do some db stuff...
//if you echo out something, it will be available in the data-argument of the
//ajax-post-callback-function and can be displayed on the html-site
break;
}
}
?>
It redirects to a different page because of your action attribute.
Try:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="text" name="address" id="email" maxlength="30" size="23" />
<input type="submit" value="" id="submit" name="submit" />
</form>
<?php if (isset($_POST['submit'])) : ?>
<p>Thank you for subscribing!</p>
<?php endif; ?>
The page will show your "Thank You" message after the user clicks your submit button.
Also, since I don't know the name of the page your code is on, I inserted a superglobal variable that will insert the the filename of the currently executing script, relative to the document root. So, this page will submit to itself.
You have to use AJAX. But that requires JavaScript to be active at the users Brwoser.
In my opinion it's the only way to do without redirect.
to send a form request without redirecting is impossible in php but there is a way you can work around it.
<form method="post" action="http://yoururl.com/recv.php" target="_self">
<input type="text" name="somedata" id="somedata" />
<input type="submit" name="submit" value="Submit!" />
</form>
then for the php page its sending to have it do something but DO NOT echo back a result, instead simply redirect using
header( 'Location: http://yourotherurl.com/formpage' );
if you want it to send back a success message simply do
$success = "true";
header( 'Location: http://yourotherurl.com/formpage?success='.$success);
and on the formpage add
$success = $_GET['success'];
if($success == "true"){ echo 'Your success message'; } else { echo
'Your failure message';
Return and print the contents of another page on the current page.
index.php
<html>
<body>
<p>index.php</p>
<form name="form1" method="post" action="">
Name: <input type="text" name="search">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_POST['search'];
include 'test.php';
}
?>
</body>
</html>
test.php
<?php
echo 'test.php <br/>';
echo 'data posted is: ' . $_POST['search'];
?>
Result:
Just an idea that might work for you assuming you have no control over the page you are posting to:
Create your own "proxy php target" for action and then reply with the message you want. The data that was posted to your php file can then be forwarded with http_post_data (Perform POST request with pre-encoded data). You might need to parse it a bit.
ENGLISH Version
It seems that no one has solved this problem without javascript or ajax
You can also do the following.
Save a php file with the functions and then send them to the index of your page
Example
INDEX.PHP
<div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>
Tools.php (It can be any name, note that it is kept in a folder lame tools)
<?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}
if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>
Use
form onsubmit="takeActions();return false;"
function takeAction(){
var value1 = document.getElementById('name').innerHTML;
// make an AJAX call and send all the values to it
// Once , you are done with AJAX, time to say Thanks :)
document.getElementById('reqDiv').innerHTML = "Thank You for subscribing";
}