I'm trying to validate a form that's being submitted through a PHP router.
All my traffic is sent to index.php via htaccess. to index.php:
RewriteEngine On
RewriteBase /router
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /divbase/index.php?/$1 [L]
index.php then provides the appropriate content:
<?php
Router::get('/form', function() {
include 'content/form.php';
});
?>
so when you go to example.com/form, the form page is loaded:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
However, when I try to submit the form on that page it 404s. After doing some troubleshooting, it looks like the PHP thinks that the form is being submitted to index.php rather than form.php.
I've tried to set the form action to:
<?php "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>
But it still 404s. Does anyone have any suggestions for this?
You need to add another route for POST, for example...
Router::get('/form', function() {
include 'content/form.php';
});
Router::post('/form', function() {
echo 'Hello world';
});
Your form is using method="post" so you need to add a POST route
Related
I have a HTML form containing a textbox and a submit button. When I submit the form, I want textbox value appending to the URL.
For example, if my domain is http://www.example.com/ and form lies on index.php. Suppose textbox value is "test" then when the form is submitted the URL should change to http://www.example.com/test. How can we achieve it?
HTML Code:
<form method="post" action="">
<input type="text" name="txtname" value="<?php echo $name; ?>" />
<input type="submit" name="btnsubmit" value="Submit" />
</form>
PHP Code:
<?php
$name = NULL;
if(isset($_POST['btnsubmit']))
{
$name = $_POST["txtname"];
}
?>
.htaccess Code:
# .htaccess mod_rewrite
# example.com
#Enable mod rewrite
Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
How about a jQuery solution? Something like...
$(document).ready(function(){
var txtname = $('#txtname').val();
var url = window.location.href;
var new_url = url + "/" + txtname;
$('#formid').on('submit', function(e){
e.preventDefault();
// Do what you need to do here.
console.log(new_url);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formid" method="post" action="">
<input id="txtname" type="text" name="txtname" value="testname" />
<input type="submit" name="btnsubmit" value="Submit" />
</form>
You could use header:
$name = $_POST['txtname'];
header('Location: http://www.example.com/$name');
If you want to get the value without the error you can set the variable to empty like this:
$name = isset($_POST['txtname']) ? $_POST['txtname'] : '';
Place that after your opening php tag.
When I try to send my form with the base_url() method (so I click on the submit button), instead of the result of my request, I have a 403 error on the other page (forbidden acces), on the page generated by my controller.
I use a Wampp Server, the version 3.1.8 of CodeIgniter. I've also add url in the autoload file.
I have .htacess file with that :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
View page :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="<? echo base_url();?>form_validation">
<label> Name </label>
<input type="text" name="name" />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Can you help me ? Thanks a lot
Hope this will help you :
NOTE : Assuming that default controller is welcome in route.php if not replace welcome with yours
In controller : you have method form_validation and you give in form action only validation :
public function form_validation()
{
echo 'OK';
}
Your form view is just like this :
REPLACE :
/* note missing php error in action*/
<form method="post" action="<? echo base_url();?>form_validation">
With :
/*add controller name also in action,
assuming your default controller is Welcome*/
<form method="post" action="<?php echo base_url('welcome/form_validation');?>">
View should be like this :
<form method="post" action="<?php echo base_url('welcome/form_validation');?>">
<label> Name </label>
<input type="text" name="name" />
<input type="submit" name="submit" value="submit" />
</form>
route.php should be like this :
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
NOTE ALSO : .htaccess should be in project folder , in your case CI folder
I want "nice urls" for my website. I'm looking at using .htaccess and I have tried many versions.
Now I have this:
IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
# !IMPORTANT! Set your RewriteBase here and don't forget trailing and leading
# slashes.
# If your page resides at
# http://www.example.com/mypage/test1
# then use
# RewriteBase /mysite
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
So this removes index.php from the URL. At first it was ok, but
Here is my config.php:
$config['base_url'] = 'localhost/mysite/';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
And my .htaccess file is in my app root.
folder img
I need a login for admin page, so localhost/mysite/admin is the my url for admin site.
public function index()
{
// $this->session->unset_userdata('logged_in'); session_destroy();
$data['sitename']="Varkocs Old Pub";
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('admin/home_view', $data);
}
else
{
//If no session, redirect to login page
//redirect('login', 'refresh');
$this->load->helper(array('form', 'url'));
$this->load->view('admin/login',$data);
}
}
public function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('', 'refresh');
}
This is my admin controller. I try here if logged in I load home_view, else the login view.
<div id="" class="container-fluid ">
<div id="" class="row">
<div id="" class="col-md-4 text-center admin_container">
<h2><?php echo $sitename;?><h4>belépés az admin felületre</h4></h2>
<?php echo validation_errors('<p class="bg-danger">','</p>');?>
<form action="verifylogin" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="username">Username:</label>
<input class="form-control" placeholder="" type="text" size="20" id="username" name="username"/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input class="form-control" placeholder="password" type="password" size="20" id="passowrd" name="password"/>
</div>
<input class="btn btn-warning btn-lg btn-block" type="submit" value="Login"/>
</form>
</div>
</div>
This is the login view. I can't use here:
echo form_open('verifylogin');
Because it's returning the wrong URL.
So I write HTML:
<form action="verifylogin" method="post" accept-charset="utf-8">
The form validation with CodeIgniter is working. But the redirect afterwards doesn't work.
$this->load->helper(array('form', 'url'));
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$data['sitename']="Varkocs Old Pub";
$this->load->view('admin/login',$data);
}
else
{
//Go to private area
redirect('admin', 'refresh');
}
I have tried many ways to fix this, but I failed.
The Codeigniter documentation says the following about the redirect function:
In order for this function to work it must be used before anything is outputted to the
browser since it utilizes server headers.
This rule can be tricky to follow. A space or line end before the opening PHP tag will already break it.
I have PHP code for shortening a URL. I want to integrate it with CodeIgniter. How can I do this?
I have 3 pages: index.php, page.php and a .htaccess file and one database backup file.
index.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$url=$_GET['url'];
$url_details=mysql_fetch_array(mysql_query("select * from tinyurls where shorturl like ('".$url."')"));
if(!empty($url_details)){
header("location: ".$url_details['actualurl']);
}else{
echo '<h2 style="color:red">Error 404: Page not found</h2>';
}
?>
page.php
<?php
if(isset($_POST['url'])){
mysql_connect("localhost","root","");
mysql_select_db("test");
$exist=mysql_fetch_array(mysql_query("select * from tinyurls where actualurl='".$_POST['url']."'"));
if(empty($exist))
{
function get_random_word($length=6){
$chars='abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$word="";
for($i=0;$i<$length;$i++){
$word.=substr($chars,rand(1,strlen($chars)),1);
}
$isexist=mysql_fetch_array(mysql_query("select id from tinyurls where shorturl like ('".$word."')"));
if(empty($isexist)){
return $word;
}else{
return "";
}
}
$tiny_word="";
while($tiny_word==""){
$tiny_word=get_random_word();
}
mysql_query("insert into tinyurls set shorturl='".$tiny_word."', actualurl='".$_POST['url']."'");
}else{
$tiny_word=$exist['shorturl'];
}
echo "TinyURL: http://".$_SERVER['SERVER_NAME']."/tinyurl/".$tiny_word."<br/><br/>";
}
?>
<html>
<head><title>Shorten URL</title></head>
<body>
<form method="post" action="">
Enter the URL:<br/>
<input type="text" name="url" style="padding:5px;width:500px"/><br/><br/>
<input type="submit" style="padding:5px" value="Shorten URL">
</form>
</body>
</html>
.htaccess file
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^p\/(.*)$ page.php?q=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
How can I integrate it with CodeIgniter?
when iam integrating this with codeigniter the controller goes to the home page of my site not to the original url
In your code you're just echoing the URL instead of redirecting it:
header('Location: http://' . $_SERVER['SERVER_NAME'] . '/tinyurl/' . $tiny_word);
How to track the page views and ip address of the short url this code is creating. thanks in advance.
PHP Code
<?php
//include database connection details
include('db.php');
//redirect to real link if URL is set
if (!empty($_GET['url'])) {
$redirect = mysql_fetch_assoc(mysql_query("SELECT url_link FROM urls WHERE url_short = '".addslashes($_GET['url'])."'"));
$redirect = "http://".str_replace("http://","",$redirect[url_link]);
header('HTTP/1.1 301 Moved Permanently');
header("Location: ".$redirect);
}
//
//insert new url
if ($_POST['url'] && $_POST['url'] != 'http://') {
//get random string for URL and add http:// if not already there
$short = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 5);
mysql_query("INSERT INTO urls (url_link, url_short, url_ip, url_date) VALUES
(
'".addslashes($_POST['url'])."',
'".$short."',
'".$_SERVER['REMOTE_ADDR']."',
'".time()."'
)
");
$redirect = "?s=$short";
header('Location: '.$redirect); die;
}
<h1> URL to shrink: </h1>
<form id="form1" name="form1" method="post" action="">
<input name="url" type="text" id="url" value="http://" size="75" />
<input type="submit" name="Submit" value="Go" />
</form>
<!--if form was just posted-->
<?php if (!empty($_GET['s'])) { ?>
<br />
<h2>Here's the short URL: <?php echo $server_name; ?><?php echo $_GET['s']; ?></h2>
<?php } ?>
.htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?url=$1 [L,QSA]
You'll need to create a separate table for keeping a count of the hits and IP's your shortened URL's are getting. Create a table (let's call it "hits") containing url_id and ip_address as it's columns.
Inside your if (!empty($_GET['url'])) condition, make an insert into the hits table with the ID of the URL it has requested and the IP address the request came from.
How to track the page views and ip address of the short url this code is creating.
Enable logging in your webserver and then use a log file analyzer that will give you that information (most common logfile analyzers do have the info you're looking for).