- Работа с формами
- User Contributed Notes 3 notes
- How to call a php function with html <form> action attribute?
- How to call a php function with html <form> action attribute?
- Form calls 2 php functions
- Call PHP file without using form action
- PHP Form Handling
- PHP — A Simple HTML Form
- Example
- Example
- GET vs. POST
- When to use GET?
- When to use POST?
Работа с формами
Одно из главнейших достоинств PHP — то, как он работает с формами HTML. Здесь основным является то, что каждый элемент формы автоматически становится доступным вашим программам на PHP. Для подробной информации об использовании форм в PHP читайте раздел Переменные из внешних источников. Вот пример формы HTML:
Пример #1 Простейшая форма HTML
В этой форме нет ничего особенного. Это обычная форма HTML без каких-либо специальных тегов. Когда пользователь заполнит форму и нажмёт кнопку отправки, будет вызвана страница action.php . В этом файле может быть что-то вроде:
Пример #2 Выводим данные формы
Пример вывода данной программы:
Здравствуйте, Сергей. Вам 30 лет.
Если не принимать во внимание куски кода с htmlspecialchars() и (int) , принцип работы данного кода должен быть прост и понятен. htmlspecialchars() обеспечивает правильную кодировку «особых» HTML-символов так, чтобы вредоносный HTML или Javascript не был вставлен на вашу страницу. Поле age, о котором нам известно, что оно должно быть число, мы можем просто преобразовать в int , что автоматически избавит нас от нежелательных символов. PHP также может сделать это автоматически с помощью модуля filter. Переменные $_POST[‘name’] и $_POST[‘age’] автоматически установлены для вас средствами PHP. Ранее мы использовали суперглобальную переменную $_SERVER , здесь же мы точно так же используем суперглобальную переменную $_POST , которая содержит все POST-данные. Заметим, что метод отправки (method) нашей формы — POST. Если бы мы использовали метод GET, то информация нашей формы была бы в суперглобальной переменной $_GET . Кроме этого, можно использовать переменную $_REQUEST , если источник данных не имеет значения. Эта переменная содержит смесь данных GET, POST, COOKIE.
В PHP можно также работать и с XForms, хотя вы найдёте работу с обычными HTML-формами довольно комфортной уже через некоторое время. Несмотря на то, что работа с XForms не для новичков, они могут показаться вам интересными. В разделе возможностей PHP у нас также есть короткое введение в обработку данных из XForms.
User Contributed Notes 3 notes
According to the HTTP specification, you should use the POST method when you’re using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click «Reload» or «Refresh» on a page that you reached through a POST, it’s almost always an error — you shouldn’t be posting the same comment twice — which is why these pages aren’t bookmarked or cached.
You should use the GET method when your form is, well, getting something off the server and not actually changing anything. For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.
Also, don’t ever use GET method in a form that capture passwords and other things that are meant to be hidden.
How to call a php function with html <form> action attribute?
So far I used «form action» to call a php file. LozFromOz Solution 1: you can do it with image in your form that call to php file.
How to call a php function with html <form> action attribute?
Hi guys I’m having difficulties with trying to call a function when I use the html action attribute.
$cm = new customer_module(); $rm = new room_module(); $c_array = $cm->getByStatus('CHECKED-IN'); foreach($c_array as $row) < $temp = $row['room_no']; $r_array = $rm->getByRoomNumber($temp); $rray = $r_array[0]; echo( $cm->checkOutCustomer($row['last_name'],$row['first_name']). "". "".$row['room_no']. " ". "".$rray['type']. " ". "".$row['last_name']. " ". "".$row['first_name']. " ". "".$row['phone_no']. " ". "". //"".""." ". " "); >
As you can see, I’m trying to run the code $cm->checkOutCustomer($row[‘last_name’],$row[‘first_name’]) for the action attribute.
The code runs fine for the first line after my echo, but when I pasted it for action it seems there is a syntax problem with $cm .
Please advise me what the problem is and thanks a lot!
If you want that checkOutCustomer method should execute when the form is submitted, then its not the correct way to implement. You need to specify a url in the action attribute. The form will be submitted to this url where you can access the form fields as the elements of $_POST or $_GET super globals (depending upon the method) and then process them.
But in case this method checkOutCustomer returns a url that you want to set as the action attribute of the form, then
"checkOutCustomer($row['last_name'],$row['first_name']);">".
"checkOutCustomer($row['last_name'],$row['first_name']) . ">".
I don’t see why @sdleihssirhc’s answer was voted down when it was right, and the wrong answers got upvotes. PHP is evaluated server side — HTML is processed by the browser. This means your code currently checks out every user as they are listed. Not what you want? Didn’t think so.
The action attribute is NOT for executing server side functions on submits. You want to set it to a php file and have that PHP file do your processing. Try going over the basics of HTML forms again too, because you don’t seem to understand.
Also try to create a Customer class and just add a $customer->checkout() method, and just do a search for active customer records (i.e. not checked out) and display info from those. And then do something like $customer = new Customer($roomNo, $info . ) and then $customer->checkIn()
It just makes more sense to anyone maintaining the system. Anyway, from what I can see, you’re trying to create a hotel management system. PHP isn’t the best suited language for the job at hand and don’t give any of that «only language i know» crap — learn something suited to the task, because lack of knowledge is no excuse for picking a bad language for the job at hand.
I won’t give any working code apart from small things or pointers — you have to learn , rather than have others do and just copy / paste.
PHP is evaluated by the server.
HTML is interpreted by the client.
Never the twain shall meet.
- Move your function to a separate page. Set the form’s action to that page. This would require some redirecting, to send the user back to the page with all of the table rows.
- Move your function to a separate page. Use JavaScript to cancel the form’s submission, and then use AJAX to send the data to that separate page. This kind of sucks, because you’ll have to handle cross-browser events and AJAX, so I’d suggest a library, like jQuery.
"checkOutCustomer($row['last_name'],$row['first_name']);">".
"checkOutCustomer($row['last_name'],$row['first_name']) . ">" .
Looks like a copy and paste error is all.
HTML call PHP function on Submit without leaving the, Normally I would solve this with AJAX and call the php function instead of a php page. Is it possible to call a php function from inside a php script after pressing the submit button (the way it would normally execute in a …
Form calls 2 php functions
I have an html form which uses a PHP file to submit data by email. I want to add some code (which I already have) to generate random numbers for spam protection. Can I call another PHP file within my form?
Here is the code that goes in the form:
I am a real novice with PHP so any help would be appreciated.
you can do it with image in your form that call to php file.
the famous is to use captcha,
a good captcha to insert in php :
There’s no need to have the browser make two http requests for two different urls to the webserver. Your php script go.php can do what ever you want it to do, e.g. include two other scripts and/or calling two functions or .
Html — Call form submit action from php function on, Your form action is ?submitfunc in the query string which implies $_GET[‘submitfunc’] but you are testing for $_POST[‘submitfunc’]. – Michael Berkowski Jun 30, 2013 at 12:49
Call PHP file without using form action
I am new to php. I did a little search but did not find a good solution. So posting the question here.
I have several thumbnail images in my webpage. Something like:
Can you please tell me how to call php file and pass the image id?
![]()
php side: $_GET['id'];
You can post to a script without using a form, here is a simple example
$.post("get_image.php", < thumbId: thumb1 >, function(response) < console.log(response); >);
And in php side $_POST[‘thumbId’]
If you are using jQuery try this:
var get_thumb_details = function(thumb_id) < $.ajax(< type: "POST", url: "process_image.php", data: < thumb_id: thumb_id >>) .done(function( data) < // This is the data received from the server console.log(data); >); >; // Attach onclick event on your images $('img').on('click', function() < var thumb_id = $(this).attr('id'); get_image_details(thumb_id); >);
On the server side you can access the request parameters using the $_POST object.
$input_thumb_id = $_POST['thumb_id']; var_dump($input_thumb_id); // if you want to check the variable value
You can try Angualr Js. In angular js we can the get the form elements attributes without submitting. So you can get the image id’s on clicking using angular js. You can pass the same to get your required php page.
Php — Calling a JavaScript function with argument from, function getConfirmation (value1) The code onclick=\»getConfirmation («.$row1 [‘pop_code’].»);\» will create proper code on integer values for $row1 [‘pop_code’) ie getConfirmation (10), but when the code is text it will be incorrect getConfirmation (test). So you have to add quote the values.
PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP — A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:
Example
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named «welcome.php». The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The «welcome.php» looks like this:
The output could be something like this:
The same result could also be achieved using the HTTP GET method:
Example
and «welcome_get.php» looks like this:
The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.
Think SECURITY when processing PHP forms!
This page does not contain any form validation, it just shows how you can send and retrieve form data.
However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to protect your form from hackers and spammers!
GET vs. POST
Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, . )). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope — and you can access them from any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
Developers prefer POST for sending form data.
Next, lets see how we can process PHP forms the secure way!