I'm new to PHP. Iv created a small php script. Basically I have a form and inside of it I have a function called show_sent:
<form method="post" action="contact.php" class="formstyle">
<h2>Formulaire de contact : </h2>
<p> </p>
<?
function show_sent(){
?>
<p>Sent</p>
<?
} // the function finishes here
?>
.......
I was hoping that it would only show the 'Sent' text when I call that function. How could I do this?
Thanks
contact.php is the same page as the form
You need to clean up your code a bit. Jumping into and out of HTML and PHP is not a good thing.
<?php
function show_sent() {
print "<p>Sent</p>";
}
if ($_POST) {
$errors = false;
/* logic to check data */
if (!$errors)
show_sent();
}
?>
<form>
<input type="text" name="fname" />
</form>
You need to check to see if the form data is posted. You do this by going:
if(isset($_POST['form_element_name']))
{
//call the show_sent function because data has been posted
show_sent();
}
or
function show_sent(){
if(isset($_POST['form_element_name']))
{
}
}
//Call the show_sent function all the time because the code inside the function checks the POST variables.
show_sent();
One way to do it is post the form to its self instead of another file then you can check if the variables have data in them and if they do call your sent function. check out this link for more info on post self.
http://www.webmaster-talk.com/php-forum/51903-php-self-submitting-form.html
Related
I was wondering if someone can help me. I am trying to write some PHP code so that when I click on a button in one page, upload.php, the button click is detected and I am redirected to another page, processing.php. I am following along another tutorial and I have triple checked, I don't see what I have done wrong, but the button click is not being detected as it is in the video.
This is the code for my upload.php file:
<?php include_once('includes/header.php');?>
<?php include_once('includes/classes/VideoDetailsFormProvider.php');?>
<div class="column">
<!-- //calling PHP function to create upload form -->
<?php
//create variable and assign value
$formProvier = new VideoDetailsFormProvider($con);
//call function
echo $formProvier->createUploadForm();
?>
</div>
<?php include_once('includes/footer.php');?>
This is the relevant code from my additional class VideoDetailsFormProvider.php:
class VideoDetailsFormProvider{
private $con;
//create constructor and pass $con variable to it
public function __construct($con){
$this->con = $con;
}
//creating a function to create the upload form
public function createUploadForm(){
$fileInput = $this->createFileInput();
$titleInput = $this->createTitleInput();
$descriptionInput = $this->createDescriptionInput();
$privacyInput = $this->createPrivacyInput();
$categoryInput = $this->createCategoryInput();
$uploadButton = $this->createUploadButton();
return "
<form action='processing.php' method='POST'>
$fileInput
$titleInput
$descriptionInput
$privacyInput
$categoryInput
$uploadButton
</form>
";
}
private function createUploadButton(){
$html = "<button name='uploadButton' class='btn btn-primary'>Upload Video</button>";
return $html;
}
And this is what I have in my processing.php file:
<?php include_once('includes/header.php');
//check for submission of the form or button is pressed
if(!isset($_POST['uploadButton'])){
echo "No form data has been set";
}else{
}
?>
When I click the button object, nothing happens. In the video I am transferred to processing.php and the echo message is not displayed. Or at least I should be, but that doesn't happen. I did try to check here to see if I could find some answers, a few things I tried didn't work out. Does anyone have any ideas about something I might be missing? Thanks in advance
The problem is with your upload button, when you use an html form it has to be submitted to the php processing page, try:-
private function createUploadButton(){
$html = "<button type='submit' name='uploadButton' class='btn btn-primary'>Upload Video</button>";
return $html;
}
My class...
<?php
class SelectionBoxbuilder
{
public function RenderToHTML()
{
$SelectBox = '<select>
<option>"One"</option>
<option>"Two"</option>
</select>';
return $SelectBox;
}
}
My PHP test file that generates the selection box...
<?php
foreach (glob("classes/*.php") as $filename)
{
include $filename;
}
$sb = new SelectionBoxbuilder();
echo $sb->RenderToHTML();
This Works, but I need to know how to capture the event from the Selection box I have generated, not sure if I am in fact approaching this from the wrong angle perhaps I need to do this in an entirely different manner?
I basically want the event to trigger some other PHP code I have not written yet and pass the value of the selection box as a parameter.
Hope this I clear enough if not please let me know any additional information I could add.
So...
When the user changes the item selected on the selection box I would like this to trigger an event, which I will then 'point' to some other PHP code.
I am assuming that you are talking about change events on the select box (i.e. when the user selects a different value).
The main thing you need to understand is that the event is fired on the client side in the browser, while your PHP code is running on the server. It has no way of knowing what's happening on the client.
If you need to do something in PHP when these events are fired, you can add JavaScript code to handle the client-side event and to fire an AJAX request to your server-side PHP script.
In basicly PHP is a server side language.
So after the server side send output to browser you can't use PHP anymore.
To get the selection from user you need to make a new request to server.
You can do it by two methods:
Send the form data to server by regular http request (GET/POST).
Send data with ajax request for UX reasons.
First you need to change your "SelectionBoxbuilder" class to form element.
Like this:
<?php
class SelectionBoxbuilder{
public function RenderToHTML(){
$SelectBox = '
<form method="post">
<select name="selectbox">
<option value="1">"One"</option>
<option value="2">"Two"</option>
</select>
<br/>
<input type="submit" value="Send" />
</form>
';
return $SelectBox;
}
}
Now you have a form in you HTML output.
To get the response we need to add handler for the post request to the test file:
<?php
foreach (glob("classes/*.php") as $filename){
include $filename;
}
$sb = new SelectionBoxbuilder();
// If form submited
if( isset( $_POST['selectbox'] ) ){
echo 'Your selection is: ' . $_POST['selectbox'];
}
echo $sb->RenderToHTML();
You can add new method to your class to take care of the response:
<?php
class SelectionBoxbuilder{
public function RenderToHTML(){
$SelectBox = '
<form method="post">
<select name="selectbox">
<option value="1">"One"</option>
<option value="2">"Two"</option>
</select>
<br/>
<input type="submit" value="Send" />
</form>
';
return $SelectBox;
}
//Check response and return the value if form already submit
public function checkForResponse(){
if( isset( $_POST['selectbox'] ) ){
return 'Your selection is: ' . $_POST['selectbox'];
}
// return false if form not send
return false;
}
}
And now in test file you can do somthing like this:
<?php
foreach (glob("classes/*.php") as $filename){
include $filename;
}
$sb = new SelectionBoxbuilder();
// If form submited
if( $userAnswer = $sb -> checkForResponse() ){
echo 'Your selection is: ' . $userAnswer;
} else {
echo $sb->RenderToHTML();
}
I hope I was helpful to you.
I want to protect my action page so that whenever user or hacker directly hits www.something.com/process.php That should not have any effect .Please help me securing the process.php page when user directly hits from browser address bar .
I have following code in index.html
<form method="post" action="process.php">
Name:<input type="text" name="txtname"><br/>
Age :<input type="text" name="age"><br/>
<input type="submit" value="submit">
</form>
I have following in process.php
<?php
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
?>
Add the following line to the top of process.php
if (empty($_POST)) {
header('HTTP/1.0 403 Forbidden');
die('Restricted');
}
What about making sure that the user opened index.html first before navigating to process.php?
You have two options:
From the process.php make sure that the $_SERVER['HTTP_REFERER'] value matches your index.html page
if($_SERVER['HTTP_REFERER'] == "http://localhost/index.html"){
//do your work here
}
Another solution, you can for example create a random variable in a hidden input in the index.html, store it in the session, then in the process.php page you can check if the variable that you stored in the session matches the variable sent by the form.
this is some basic ways to secure your applications from an attack called CSRF you can read more about it here:
https://en.wikipedia.org/wiki/Cross-site_request_forgery
http://www.gnucitizen.org/blog/csrf-demystified/
preventing csrf in php
You should try something like that
<form method="post" action="process.php">
Name:<input type="text" name="txtname"><br/>
Age :<input type="text" name="age"><br/>
<input type="submit" value="submit" **name="ButtonName"**>
</form>
Add a name of your button. Then change your process.php file to something like this :
<?php
if (!isset($_POST['ButtonName'])) // If the submit button hadn't been hit
{
// Kick the user off the page
echo "<script typer=\"text/javascript\">window.location='index.html';</script>"
}
else
{
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
}
?>
Now if you try to enter into process.php without submitting the form, you will automaticaly be "kicked"
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
What happens is this is not a POST request? Or if it is a POST request, but those two fields are not present? This code is broken. Now, your configuration may ignore that error and treat $_POST['age'] as a blank when it is not set, but that’s not something you should be relying on.
class Request {
public static function value($arr, $field, $default=null) {
return isset($arr[$field]) ? $arr[$field] : $default;
}
public static function get($field, $default=null) {
return self::value($_GET, $field, $default);
}
public static function post($field, $default=null) {
return self::value($_POST, $field, $default);
}
}
That should exist as a useful class you can call when you want it. And then, in this file, you can have
$name = mysql_real_escape_string(Request::post('txtname'));
$age = mysql_real_escape_string(Request::post('age'));
if ($name && $age) {
// Do database stuff here.
}
For a quicker solution, you could just stick
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
exit;
}
at the top of the file.
Incidentally, the mysql_* family of functions have been removed from the latest versions of PHP. You should migrate to the mysqli_* family or to PDO if you want your code to continue to work when you upgrade your PHP installation.
one way would be checking if the form is submitted and binding all the actions inside it as following
<?php
if(isset($_POST['txtname']))
{
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
}
else
{
// form not submitted
}
?>
extra security can be added by binding whole inside another condition if the user has logged in or not as following
<?php
if(checkUserLogin())
{
if(isset($_POST['txtname']))
{
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
}
else
{
// form not submitted
}
}
else
{
// user has not logged in yet. redirect to login-page using header("location:....");
}
?>
where checkUserLogin() can be a function to check user logged in details for example
function checkUserLogin()
{
$return= false;
if($_SESSION['userloggedin']==1)
{
$return=true;
}
return $return;
}
check on the data you sent first like the and make your code ad the followings
<?php
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
if((isset($name) && $name != '') || (isset($age) && $age != '')){
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
}
?>
I have a small form, where user's can Subscribe to my newsletter.
How can i pass the email address from my Layout to my Controller?
My Layout name is Footer.phtml, here's the code:
<div id="subscribe">
<form name="newsletterRegister" method="post" action="">
<span>Subscribe to the Newsletter</span>
<input class="subscribeNewsletter" name="email" type="text">
<input id="subscribe_ok" type="image" src="/www/assets/newImages/footer/Ok.png" value="">
</form>
</div>
I have a controller called NewsletterController.php
I'm kinda lost with Zend Framework, can anyone help me figuring out what i have to do??
Well change this
<form name="newsletterRegister" method="post" action="">
To this
<form name="newsletterRegister" method="post" action="NewsletterController/YOURACTION">
And in your controller just get the data like this
$request = $this->getRequest();
$request->getPost()
If the action of your form is empty, it will post to itself.
But maybe you dont want to check on every page if the newsletter is send.
Try using a Controller Plugin, check the request object for the input field, name it unique like email_newsletter, if is not empty, do your logic.
File: application/plugins/Newsletter.php
class Application_Plugin_Newsletter extends Zend_Controller_Plugin_Abstract {
//before dispatching starts
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$email = $request->getParam('email_newsletter',NULL);
if(!is_null($mail)) {
//check if is valid
if(Zend_Validate::is($email,'')) {
//do your logic
}
else {
//set some error messages
//maybe use helper flashMessenger
}
}
}
}
File: Bootrap.php
protected function _initPlugins() {
$this->bootstrap('frontController');
//Get FrontController Instance
$frontController = $this->getResource('frontController');
$frontController->registerPlugin(new Application_Plugin_Newsletter());
return $frontController;
}
OR
Set a form action like '/newsletter/subscribe'.
Then in controller 'newsletter' action 'subscribe' check the form and redirect to the sending page.
Maybe you should store sth like a last page visited to the session, or add a hidden input to that newsletter form, representing the current page you want to redirect to after the newsletter subscription is done.
I have an HTML form that takes inputted data and sends it via the mail() function. I also have some validation techniques that validate the inputs, and I created an array variable $errors to log all of the errors; for example,
if the name was left empty, $errors[]="Name empty";
If the email was left empty, $errors[]="email empty";
and so on..
I was able to report the errors using the following technique:
print '<div id="formfeedback"><h3>Error!</h3><p>The following error(s) has occurred:<br />';
foreach ($errors as $msg) { //prints each error
print " - $msg<br />\n";
} // end of foreach
However, what I want is the following. I want the page to be redirected back to the original form that was used to input the information (I know the exact link location, so i can use a header() or even a <meta=http-equiv=refresh> to bring me back to the form page.
Also, on the form, I want to be able to post the errors above the form in some div (call it div=errors)
Would I be able to do the following?
<div id="errors">
<?php
print 'The following error(s) has occurred:<br />';
foreach ($_REQUEST[$errors] as $msg) { //prints each error
print " - $msg<br />\n";
} // end of foreach
?>
</div>
Thanks a lot!
Amit
I agree with #Fosco. I want to explain a little bit more-
There may be two cases-
1. You are doing raw php
2. You are coding on any php framework like CI or your own.
and this will help to identify error field and change style to make better user response. Also last input data remain as it was.
You are doing raw php
In this case you can receive the input data in same file/page.
I will do a common example later.
You are coding on any php framework like CI or your own.
In this case you load a view file to show the form page and you can pass data to view page/file when you load it.
For both of above case you can do some coding like-
/*
your input validation and verification goes here. where $error is generated too
In addition add some error status in above section,
you can do it in your $error array too. Also you store received data into $data here. index of $data should be similar as (corresponding) HTML input name.
You can do it like below
*/
$error_stat = array();
//if the input field name is "email" and email input data raises any error then
$error_stat['email'] = true;
// same for name
$error_stat['name'] = true;
// and so on
// now decide whether you will back to the form page or send the email and do other tasks
if(count($error_stat)<= 0){
// send email
// do aditional tasks
}
else{
// load the form again if its aframework or the form is in seperate file
// off course send $error,$data and $error_stat to the form page/file
}
// now here is a code segment of form page
<?php if(isset($error) && count($error)>0):?>
<div id="error-msg">
<?php
//display errors here
?>
</div>
<?php endif;?>
<form .... >
<input type="text" name="email" class="<?php echo (isset($error_stat['email'])?'error':'else'); ?>" value="<?php echo $data['email'];?>" />\
<!-- and so on ... -->
The simplest way to do this is to:
// Start the session
session_start();
// Store the errors in the session
$_SESSION['errors'] = $errors;
// Redirect to correct page
header('HTTP/1.1 303 See Other');
header('Location: http://original/page');
exit;
Then, on the form page:
// Start the session
session_start();
// extract the errors
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : array();
// Display the form with errors
foreach ($errors as $msg) ... ;
Typically I would have the same page process the input and the submission. If the data was valid, the mail would be sent and the page would notify them of that (or redirect them elsewhere)... if the data was not valid, then the form would appear again and the errors could be displayed, without any fancy redirection.
make sure your session is started at the top of your application
include this basic class
class FormErrors
{
var $handler;
function __construct($fname)
{
$this->handler &= isset($_SESSION[$fname]) $_SESSION[$fname] : ($_SESSION[$fname] = array());
}
public function add($name, $value)
{
$this->handler[$name] = $value;
}
public function remove($name)
{
unset($this->handler[$name]);
}
public function getErrors()
{
return $this->handler;
}
}
so when your processing the errors you can go
if(isset($_POST))
{
$FormErrors = new FormErrors("registration");
if(strlen($_POST['username']) == 0)
{
$FormErrors->add('Username','Please enter a valid username');
}
//And for the rest of your checks
}
then within side your html do
foreach($FormErrors ->getErrors() as $name => $error)
{
echo sprintf("<p title=\"%s\">%s</p>",$name,$error);
}
Should work, and if you want to remove all known errors do
$FormErrors = new FormErrors("registration");
unset($FormErrors->handler,$FormErrors);