Base_url() is adding unnecessary segments into my url? - php

My base_url() is adding more bits into the url than it should be. What is wrong with my setup? I have the helper set up in config.php:
$autoload['helper'] = array('url');
My base_url() is set to: index.php/
So the problem is that when I activate this form:
<h1>sometimes haikus don't make sense refrigerator</h1>
<form action="<?php echo base_url(); ?>welcome/login_submit" method="post">
<label>
email:
<input id="email" name="email" />
</label>
<label>
password:
<input type="password" id="password" name="password" />
</label>
<input type="submit" value="Log me in!" />
</form>
The first time I access it, I'll type in: localhost/CIintranet/ and the the base_url() gets added next so it becomes: localhost/CIintranet/index.php/
I'm trying to program a login logout system though. So if the user login is incorrect, I want it to redirect back to the login page. Here's the code from the controller for that part:
public function login_submit() {
$this->load->model('LoginChecker', 'users');
//$this->load->view('login_submit');
$match = $this->users->authenticate_user( $_POST['email'], $_POST['password'] );
if( $match )
{
$this->load->view('login_submit');
echo "User exists in database!";
}
else
{
$this->load->view('login_form');
echo "<h1>Email or password is wrong, bretheren!</h1>";
}
}
But when it reloads the login_form, it adds another part into the url and the url fails. So the progression is like this:
Page loads to this url:
localhost/CIintranet/
First failed attempt (page still loads properly):
localhost/CIintranet/index.php/welcome/login_submit
Second failed attempt (page fails to load):
localhost/CIintranet/index.php/welcome/index.php/welcome/login_submit
I've been doing some research on this for a bit now and I'm noting a lot of people talking about the htaccess file in relation to this problem but nobody seems to mention specifically what fixes it or how to configure the base_url() so that it just takes care of this properly. I tried looking at the documentation but perhaps I missed something. I didn't find what I was looking for.
Any ideas?

Can you try setting the base_url to /index.php/? So it has the forward slash at the front too?
Failing that, please try: http://localhost/CIintranet/index.php/
It's usually the simple things!

if you use ... ?
<?php echo form_open('welcome/login_submit') ?>
...
<?php echo form_close(); ?>
activate helper: form

Related

PHP session not set in some files

I have some trouble with PHP Sessions.
I was searching too much for answers, most had problems at sesson_start() function, that is not the case here I guess.
Index.php, Loginback.php, UserInfo.php all start with:
<?php session_start(); ?>
There is index.php where I have login form with action loginback.php:
<form action="loginback.php" method="POST" id="LoginForm">
<input type="text" name="UserName" placeholder="Username" class="form-control"/>
<input type="password" name="Password" placeholder="Password" class="form-control"/>
<input type="submit" name="submit" value="Login" id="LoginButton" class="btn btn-info, OASButton" />
</form>
at LoginBack.php is validation for user input, if everything is OK I say:
$_SESSION["user"] = "Temo"; //string is for testingpurposes
header("location: http://website.com/mine/index.php");
after redirecting at index.php If session is set I include "statistics.php" and it works just fine, if session is not set I incldue "logreg.php"- also works fine, but when I go to userinfo.php and check for session isset it always says no:
<?php session_start(); ?>
<?php
if(isset($_SESSION['user'])==true){
echo "Logged In!";
} else {
echo "Not Logged in";} ?>
So bottom line, session is recognized at index.php but not recognized at userid.php. Any help?
//sorry for my english.
'K , I have no idea what happened, I have not touched those files but now I am logged in but can't log out, here is logoutback.php where it should happen:
<?php session_start(); ?>
<?php
session_unset();
session_destroy();
header("location: http://website.om/mine/index.php"); ?>
I've found an answer,
for going to userinfo.php I had:
<a href="http://www.website.com/mine/userinfo.php">
and that was the problem,
without www it works fine.
but also what was strange: I created folder SESSION just with session stuff and when I was starting session from there and redirecting through the same url, it was working.
So anyways I't is finally over :)

Is this how AltoRouter GET POST method work?

I have been trying out this altorouter for weeks now. This is looks to be good router with not many working example either on the nets or the official site. You need to understand it somehow and get the job done.
I tried the basic GET and POST using the altorouter and do not know whether this is the right way of doing it.
Simple GET method in php
<html>
<head>
</head>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
The way I did it using AltoRouter
Index.php
<?php
require 'library/AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('/AltRouter');
$router->map('GET','/', function() {require __DIR__ . '/catalog/controller/home.php';}, 'home');
$router->map('GET|POST','/aboutus/', function() {require __DIR__ . '/catalog/controller/aboutus.php';}, 'aboutus');
$router->map('GET|POST','/contactus/', function() {require __DIR__ . '/catalog/controller/contactus.php';}, 'contactus');
$router->map('GET|POST','/welcome/', function() {require __DIR__ . '/catalog/controller/welcome.php';}, 'welcome');
$match = $router->match();
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
contactus.php (Get Method)
<html>
<head>
</head>
<body>
<form action="../welcome/" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome.php
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
For some odd reason this works but I feel this isn't right. Reason: Information sent with the GET method is visible to everyone, the variables are displayed in the URL, it is possible to bookmark the page.Where as the URL that I get after submitting the form is this
http://localhost/altrouter/contactus/
No variable displayed after submitting the form in the URL.
Now for the POST method, this one works you need to let me know is this how we are supposed to do it or not.
Index.php
same as the one posted above
aboutus.php (POST method used)
<html>
<head>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["first_name"];
$email = $_POST["email_address"];
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
}
?>
<form action="<?php $_SERVER["PHP_SELF"]?>" method="post">
Name: <input type="text" name="first_name">
<br><br>
E-mail: <input type="text" name="email_address">
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
This works and the data posted is echo'ed out, URL after submitting
http://localhost/altrouter/aboutus/
Please let me know what is right and what is wrong.
I don't think I understand what you are asking... I do have some observations, though:
Information sent with the GET method is visible to everyone, the variables are displayed in the URL
Yes, that happens in HTTP method GET, the ?name=Joe&email=joe#example.com at the end of the url is called "query string". One of its differences with method POST is that the data is part of the url, so it's visible (alhtough don't trust that it is not visible otherwise) and as you say it can be bookmarked.
On GET vs POST, read about the usage of those methods and decide one for each route. I don't think it's good design, let alone easily maintainable, to have several methods mapped to a single controller. Take advantage of the router, map different methods, for instance:
$router->map('GET','/contactus', 'showContactForm');
$router->map('POST','/contactus', 'processContactForm');
Since you tag the question with "MVC", you could separate things further and have your controllers be just controllers which in turn call or generate views. Or, you can just use a full MVC framework, even a light one like Lumen, which manages routing, view templates, database connection, authentication and much more.
<form action="../welcome/" method="post">
From http://localhost/altrouter/contactus/ to http://localhost/altrouter/welcome/ the relative url can be just welcome. The .. means "go up a directory".
the URL that I get after submitting the form is this
http://localhost/altrouter/contactus/
I don't get why, if the form submitted successfully as you say, you should be in http://localhost/altrouter/welcome/
Avoid $_SERVER["PHP_SELF"]. It brings insecurities. A form with no action attribute will just submit to the same url. With method POST, you can, for the same url, handle both actions separately as I said earlier.

CodeIgniter URL repetition

I just started CodeIgnitor, that's the first time I use MVC structure though, and I have a problem that I've never seen before... It's mainly in the "form" part, but also in the database display.Also I use Xampp.
I've got a form to create an item to insert in the database, but whenever i click the submit button, things gets wrong in the url section.
My base URL is : localhost/CodeIgniter-3.1.1/ (CodeIgniter-3.1.1 is the directory that contain every php folder).
So the form page URL is : localhost/CodeIgniter-3.1.1/index.php/news/create
And when i submit, it is : localhost/CodeIgniter-3.1.1/index.php/news/localhost/CodeIgniter-3.1.1/index.php/news/create
It just repeat the entire URL after the controller (news).
I don't think it has to be with config.php, my base URL seems good, I just don't know.
Make your base url http://localhost/Codeigniter-3.1.1/index.php/ then in your <form> tag set the url like this <form method="post" action="<?= base_url('news/create') ?>">
In /application/config/config.php set $config['base_url'] like this
$config['base_url'] = http://localhost/Codeigniter-3.1.1/
In your view do either one of the following to create the <form> tag
<form method="post" action="<?= base_url('news/create'); ?>">
of if you have loaded the "Form Helper" (documented here) use this line in the view
<?php echo form_open('news/create'); ?>
It's handle by the framework, as so:
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
Also, the problem occure when I put a link to a view, like :
<a href="<?php echo 'news/'.$news_item['slug']; ?>">
Instead of building the right URL it copy itself along the bar.

Codeigniter form on same page as results

I am using codeigniter and the tutorial from here. I have made a basic blog tool which works fine. However as it stands to add a new post you have to go to a separate page 'create.php' to get to the form. I would like to try and put the form on the same page as the page that will be updated i.e. 'index.php'. If I try to do this at the moment the form simply refreshes and does submit the data.
model
function insert_post($data){
$this->db->insert('posts', $data);
return;
}
Current View (admin/create.php)
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
View I would like the form to be on (index.php)
<?php
echo '<p>Welcome '.$username.'! All posts available for edit or deletion is listed below.</p><br/>';
echo anchor('admin/create','Create New Post');
$count = count($post['id']);
for ($i=0;$i<$count;$i++)
{
echo '<div class="postDiv">';
echo '<h4>'.$post['title'][$i];
echo '<p>'.$post['summary'][$i].'</p>';
echo '<p>'.$post['content'][$i].'</p>';
//echo anchor('blog/view/'.$post['id'][$i],' [view]');
echo anchor('admin/edit/'.$post['id'][$i],' [edit]');
echo anchor('admin/delete/'.$post['id'][$i],' [delete]</h4>');
echo '</div>';
}
?>
Controller
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $_POST;
$this->posts->insert_post($data);
redirect('admin');
}
}
This was straight forward when I used normal php but with codeigniter I am getting lost with the MVC stuff. I know this is probably a fairly basic question so please either explain your answer or give me a link to something which will explain what I need to do as I want to learn from this. I have read the codeigniter docs on validation but I dont think thats my problem?
What you are trying to do is called embedding a view. I will try to explain how but you should also check some links which might prove to be more in depth:
http://net.tutsplus.com/tutorials/php/an-introduction-to-views-templating-in-codeigniter/
Codeigniter: Best way to structure partial views
The crux of what you need to do is change the link on index.php from:
echo anchor('admin/create','Create New Post');
to
$this->load->view('admin/create');
Now this should work, but to help you on the MVC front, it helps to explain why doing it this way is wrong. The idea of MVC is to seperate the functions in your application into their distinct roles. Most people will frown at putting business logic into views unless it is very minimal. The way that we could improve upon your code is to load the view in the controller, and set it to variable.
At the bottom of the codeigniter docs for views it shows how to load into a variable:
http://ellislab.com/codeigniter/user-guide/general/views.html
if the third parameter of load->view is set to true then the function will return your view as a string instead of outputting it to the browser
$data['input_form'] = $this->load->view('admin/create', $data, true);
then in the view that you want to load that form all you need to do is echo input_form
<?php echo $input_form;?>
So that should solve your problem but there are also a few more things you can do in your view file that will improve the readability of your code.
Instead of using a count() and for loop you can use foreach which makes everything much easier
<?php foreach ($post as $post_item):?>
<div>
<h4><?php echo $post_item['title'];?></h4>
</div>
<?php endforeach;?>
It also helps to break your view files up and have more tags. It might seems like it is extra bloat, but when you have larger view files it will be very cumbersome to continue using as many echo's as you have
just add one method uri_string() in your form action, uri_string will take same url of page put in action you can submit form to same page
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="<?=uri_string()?>" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
in controller little chagnes
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $this->input->post();
$this->posts->insert_post($data);
redirect('admin');
}
}
Use session library
check this another stackoverflow thread to know how to use session
In order to use session library, u need to configure encryption_key in config.php
To do that, check this out

url issues with codeigniter

I have an example at the following url, which sends the user to a basic form.
The code for the form is the following;
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
If I understand correctly, once the user presses "submit", it should go back to the controller named "form". But it does not work as expected.
I would want it to submit to index.php/form, and instead it goes to /index.php/index.php/form
Feel free to test out website at url above and see the issue by yourself.
I just looked at your source code and noticed this:
<form action="http://helios.hud.ac.uk/u0862025/CodeIgniter/index.php/index.php/form" method="post" accept-charset="utf-8">
Which displays two "index.php"s. This likely means you have "index.php" set in your base url AND index page configuration. You should remove the "index.php" from one of those sources, preferably from your base_url.
Check your base_url() in config file. If it is correclty, than you can write the form like this:
<?php echo validation_errors(); ?>
<?php echo form_open('controller_name/function_name');
// controller name write your name of controller
// and function name write your function
?>
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
<?php echo form_close(); // don't forget to close correct ?>
I have faced this situation once and the problem was i have included index.php in my base_url in ./application/config/config.php file please check and remove if present. You can also solve your problem by removing index.php from index_page key but it is not a good practice to include index.php in your base_url.

Categories