PHP and HTML integration - php

I have a php file that contains a HTML form, then PHP logic, then an HTML footer...in that order.
I am trying to get the values from the form into some php validation logic in the botton of the page (but before the footer) using <?php VALIDATION LOGIC HERE ?>.
the problem is when the validation finds an error, the php logic will die() and hence, my HTML footer will not be executed.
is there a way to get my HTML footer to execute despite my php die();? ...or is there a better overall way to integrate my HTML and PHP? Thanks! Anyhelp would be much appreciated.
EDIT:
I actually have die() almost everywhere in my code where I am about to connect to a database. If the user credentials are correct, they connect..if credentials are wrong then it will die()..
Is this good practice and use of die()? it seems the solution to my problem is to use return() INSTEAD OF die()...in order to continue processing the HTML footer.
Also, I have situations such as mysql_connect() or die(). How can i would continue processing the remaining HTML page when die() is executed before the HTML is processed? ..i don't think mysql_connect() or return; is good practice right?
Thanks so much again in advance! The feedback has been very helpful!

As other states, you should have multiple files; header.php, index.php, footer.php, formvalidator.php.
In your index.php file, you should include header.php and footer.php.
In the form tag, action is sett to load formvalidator.php
In the form validator script, you could have something like this:
// All form fields are identified by '[id]_[name]', where 'id' is the
// identifier of the form type.
// The field identifier we want to return is just the name and not the id.
public function getFormData() {
$formData = array();
foreach ($_POST as $key => $value)
{
// Remove [id]_
$name = preg_replace('!.*_!', '', $key);
if (is_array($value)) {
$formData[$name] = implode(',', $value);
} else {
$formData[$name] = $value;
}
}
return $formData;
}
Now you can loop through the array and validate each field.
If you find an error, echo an error message, otherwise process the form.
Update
Answer to your update.
You should "never" use die(). Instead, exit thefunction you are in and return an error message. If you simply die(), you never know what went wrong where.
It is not possible to do server validation of a form unless you click the submit button.
You can put the code I gave you in the same PHP file as the form, and when you submit, you simply reload the same page (just set action="<?= $_SERVER['PHP_SELF'] ?>")
If you want to validate fields before submit, you must to this using javascript, like e.g. jQuery.validate.
Hmm... seem like you need some more knowledge of how to mix PHP with HTML.
Take a look at this beginners guide on how to work with forms in PHP.

I would use an external file for form processing and validation, then redirect back to the form page on error/success, displaying an error/success message.

I just make one header.php and one footer.php file. If there is an error just return instead of die.
This way at the top of your page you can just put:
<?php include('header.php');?>
///put in whatever html there may be
<?php
/// put your form and processing info here
///just return if you need to prevent further processing
?>
///put in whatever html there may be
<?php include('footer.php');?>

there are many better ways to do what you are doing. but to answer your first question, you can create a function called footer that returns a string with html needed to be displayed in the footer and call the die(footer()); but... why do you use die ? can't you just count the errors and display them somewhere in the result ? you should not kill the script that way.
And for the second question. you can use as BenTheDesigner said, a html page with the form action pointing to a php script that validates and either returns to the form if something went wrong or go somewhere else if not. but there too, you should remove the die() function and call something else to redirect you. you can use a template system like smarty to separate your logic from your html presentation. you can write it all in a single file but try to write you're entire logic at the top of the file and all the html at the bottom. and use <?=$var?> to display php stuff, or simple conditionals for diferent html results. but don't use die(). it just complicate things I guess.

Using die() is not a good practice because it will not show a friendly message to the user visiting your site. You should be absolute sure you want to use die. For example, you may use it in procedures when you suspect there is a hacking attempt. Instead try to use if else structure to show or hide things. Here is the possible prototype that you may want to implement:
// if there is a validation error, show it, otherwise not
if ($error == true)
{
// show footer
}
<!-- Your footer goes normally here -->

Related

Trying to load a portion of page with # tag through conroller

I have a page in view that has two parts actually which are accessed through # tags, like login#signin and login#signup. When the page loads for the first time it shows login form without having #signin without a problem.
So signin is not causing a problem as it loads at folder/login. But when I try to put folder/login#signup to load directly signup part it gives an error that there is no view login#signup.php. How to cope with this situation?
$this->load->view('workers/login#signup'); is not working.
When I don't put #signup it loads login form that is weird.
I'll expand more on my initial comments for the cause of this error, and how to fix things.
The cause of the issue
As mentioned throughout the comments, you cannot a view using an anchor point. For example, this does not work:
view('workers/login#signup'); // The #signup should not be here.
The documentation states:
Loading a View
To load a particular view file you will use the following method:
$this->load->view('name');
Where name is the name of your view file.
The name is the file is "name", not "name#signup".
Further down,
The .php file extension does not need to be specified unless you use something other than .php.
This implies, that when you use view('name'), CodeIgniter will, by default, load the file name.php. If you include a #signup in it, then CodeIgniter will not be able to find name#signup.php because that file does not exist.
Correct way to handle things
You mentioned you're using the form validation, so we need to ensure no value is lost during the transition process.
Here's a simplified explanation for how to handle it:
function login() {
// Data to be passed to the view (you may or may not already have this)
// More info: https://codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
$data = array();
// Validation has failed...
$this->form_validation->run() == FALSE ) {
// Set variable to redirect to #signup upon page load
$data['redirect_to_signup'] = true;
}
// Load view with $data which contains values to be passed to the view
$this->load->view('workers/login', $data);
}
In your workers/login view file, we just need to check if the redirect_to_signup value exists. If it does exist, then we can use some simple JavaScript to scroll down the #signup form:
<?php if (isset($redirect_to_signup) && $redirect_to_signup === true): ?>
<script>
var top = document.getElementById('signup').offsetTop;
window.scrollTo(0, top);
</script>
<?php endif; ?>
Because your validation object is still valid, you can use the built-in CodeIgniter functions to preload your form elements with the set_value() helper functions. For example:
<input type="text" name="email" value="<?php echo set_value('email'); ?>">
That hopefully explains how to achieve what you're after:
Validate user submitted form; and
If there are errors, reload the form with validation messages; and
Scroll down to the #signup form on the page.
One alternative is using redirect('login#signup'), but I would not recommend this method. You would need to save your form values and validation errors to the session to show them on the next page. You also run into the issue that the user might click the refresh button and all values would be lost then.

Echo two different page view on the same page

In this case, I am going to echo/print two different page view in the same page, which it depends on whether the user has logged-in or not.
If the users are logged in, they can find all the menus in the page. However, if the user are not logged in, there would be some views I want to hide from them.
The method that I am going to use is:
First: check if the user has login or not (with session),
Then: show the page based on the result of the check of session.
And I will use this code:
<?php
session_start();
if(isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])){
?>
YOUR HTML CODE
<?
} else {
?>
YOUR HTML CODE
<?}
?>
My question actually is very simple, I just want to make sure, if I use this method, won't it make the page to load slow?
If this will make the page to load to slow, is there a good method for I to achieve this?
Thanks
It won't make your page slow (any code in the if-else block that isn't processed won't make any difference to the load time).
You might, however, wish to include a separate PHP file with the information you want to display, rather than code it directly into the if-else block. For example;
session_start();
if(isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])){
include 'loggedin.php';
}
else {
include 'notloggedin.php';
}
Hope this helps.
Your page load is really going to depend more on the html then this php switch. I have dealt with pages with 30 switches like this on one page load. While not the best practice anymore you likely wont even notice.

Codeigniter PHP - loading a view at an anchor point

I have a form at the bottom of a long page, if a user fills out the form but it doesn't validate the page is reloaded in the typical codeigniter fashion:
$this->load->view('template',$data);
however because the form is way down at the bottom of the page I need the page to load down there like you do with HTML anchors. Does anyone know how to do this in codeigniter?
I can't use the codeigniter
redirect();
function because it loses the object and the validation errors are gone. Other frameworks I've used like Yii you can call the redirect function like:
$this->redirect();
which solves the problem because you keep the object. I've tried using:
$this->index()
within the controller which works fine as a redirect but the validation errors are in another method which is where the current page is loaded from:
$this->item($labs)
but when I use this it get stuck in a loop
Any ideas? I've seen this question a lot on the net but no clear answers. I'm researching using codeigniter "flash data" but think it's a bit overkill.
cheers.
I can't personally vouch for this, but according to this thread if you append the anchor to the form's action, it will work.
CodeIgniter helper:
<?php echo form_open('controller/function#anchor'); ?>
Or vanilla HTML:
<form method='post' action='controller/function#anchor'>
If you were open to using Javascript, you could easily detect a $validation_failed variable and appropriately scroll. Or, even better, use AJAX.
Another option is to put the form near the top of the page?
Ok, as far as I understood your problem, it isn't much related to the back end(codeigniter). You want the form at the bottom of the page to be 'what-users-sees-on-page-load' (since you mention anchors).
Now, what you can do is, you can set delimiters for your validation error messages using:
echo validation_errors('<div id="bottom_form_error">', '</div>');
Using jQuery ScrollTo, do:
$( function() { $('#bottom_form_error').ScrollTo(); } );
And, the user will be scrolled to the errors at the bottom of the page. Don't forget to include jQuery too.
Anchor hash fragment click is different - it is scrolling at ∞ speed.
I hope that is what you wanted.
P.S. I am ignoring what you said below this line:
Does anyone know how to do this in codeigniter?
as I felt it is not really relevant to the question.

Problems with cakephp

I have a form with multiple fields. Some file and input.
I was working on it for some time.
Everything was working as it should be until a few hours back suddenly the form is not submitting to the right.
I have no idea what went wrong.
Action to submit the form is the same as the view it generated.
After i submit the form browser does not show anything default template address stays the same as the form submits to same view. But i do have redirect statement if the data is saved correctly..
As the form is submitted browser goes blank, not even the default template is shown ... and to add to my pain no errors ... Things are looking worse as they are..
So would really appreciate any pointers..
Thank You.
A quick thing to check for is if there are any whitespace characters at the end of your models or controllers (actually, any .php file) after the '?>' That can cause the behavior you describe.
<?php
class YourController extends AppController {
/*** your code here ***/
}
?>(whitespace chars here)
Something that I do that helps with this problem is to remove the '?>' on my models and controllers. The php interpreter will consider the EOF as the closing tag.
<?php
class YourController extends AppController {
/*** your code here ***/
}
// END
#webbiedave has good advice too, cake has great debugging, although you may need to add the following to your layout template depending on which version of cake you are using...
<?php echo $this->element('sql_dump'); ?>
I put it right at the end of my default template
Please post the code for the controller method that handles the form view.
Also post the <form action=... code.
If it isn't too long, also post the whole of the form html instead of (2.)
With the code, we can help you debug the problem.
To ensure that you can see any errors generated by PHP, open app/config/core.php in your editor and search for debug. Set the debug level to 2 - Configure::write('debug',2);

php custom forum error

i have a form, and i want to have it be limited at 10 characters minimum. that is no problem, but what i want to do is echo the error at the top of the page, which is being included, so i cant just do:
echo '<div class="error">Error</div>';
i want to have a designated div that is empty (will be on the included header page), but when there is an error it gets filled with the error text to output. anyone know how to do this not using sessions or cookies?
This is a clear use-case for javascript. PHP is strictly a server-side language; that is, the code you write is executed on the server and not the client. Javascript, on the other hand, is run inside the user's browser. So say you create a div like so: <div id="error_msg" />. Then you can write a snippet of javascript code that looks like this:
function display_error () {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = "Error";
}
You would place this code in script tags at the top of your page inside the tags. More information on javascript form validation can be found here: http://www.w3schools.com/js/js_form_validation.asp
Hope this helps.
-tjw
Edit: if this isn't exactly what you're looking for, you might want to tag this post with 'javascript' to get more people who know about js form validation to answer the question.
<div id="error_msg" /></div>
<script>
function display_error (text) {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = text;
}
display error('Error: your text here..');
</script>

Categories