Call PHP function with AJAX? - php

I know I can do this:
//Jquery
$.ajax({type: 'POST', data : {'action' : 'foo'}});
//PHP
if(isset($_POST['action']) && $_POST['action'] == 'foo')
{
function foo()
{
//yeah
}
}
But.. In a project I'm working on with a friend, he has set up the controllers to be able to have specific functions called using custom actions. For instance, say my view is using the controller of thing.php. From my Javascript I can just AJAX to a url like this:
'url' : 'thing'
So in this case, foo() would get called without a need for any ifs or switches (as far as I know)
To me, this is great and ideal but I'm not sure how it was set up. He isn't around for the holidays to ask so I'm asking you guys.
Do you know how this is achieved? We are using a pretty typical MVC architecture. Sorry I am a PHP novice. Thanks!

It looks like your friend is using .htaccess to rewrite URLS to add .php, perhaps with
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
Now if you call a URL like /thing it will actually call the file /thing.php on your server and execute it. Or in your case if your url is just thing without the starting / it will call the thing.php in the same folder your current page is in.
Or perhaps he is rewriting everything to the controller and then adding the variable as command. Something like
RewriteRule ^(.*)$ controller.php?action=$1
Anyway, check your/his .htaccess file for clues

Related

Changing link apperance with .htaccess

I'm trying to do simple trick with .htaccess file, but with without success.
Generally I have PHP script that makes dynamically generated signatures and link looks like this:
example.com/signature/generate.php?name=%SomeUserName%
where %SomeUserName% is simply username e.g. Patison
and I'm trying to get:
example.com/signature/%SomeUserName% or (if necessary)
example.com/signature/generate/%SomeUserName%
Last code that I'm tried with no success:
RewriteEngine On
RewriteRule ^/signature/generate.php?name=(*) /signature/$1 [L,NC]
.htaccess is hard to understand for me.
So I have one more question. When someone use this link on another site he will render an image or it will work only on mine?
This is the sort of approach you need:
RewriteEngine on
RewriteRule ^signature/([^/\.]+)?$ signature/generate.php?name=$1 [L,NC,QSA]
So anybody going to signature/levi will see signature/generate.php?name=levi

htaccess and POST variable issues with Codeigniter

So I am doing a bit of research on this topic, and you would think there would be an answer but there isn't, or maybe I am looking in the wrong area.
Problem
When submitting a form my post variables are empty. I am passing them through properly, the form goes where it needs to go to, and the variables and form data appear properly and with values, in the headers. I have the form helper autoloaded in the config, so everything is how it should be.
my form opener looks like this:
<form action='/Forms/form_processor/' method='post' id='testForm'>
In my Forms controller looks like this:
define('BASEPATH') OR exit('No direct script access allowed');
class Forms extends CI_Controller{
public function form_processor(){
// get variables
$name = $this->input->post('name');
// ... do stuff with variable data
}
}
I would also note that with the use of the htaccess file my config variables are:
$config['base_url'] = 'http://example.com/';
$config['index_page'] = ''; // this is to keep index.php out of the URL
Possible Cause
When using codeigniter and sitting at the home page, you get this URL:
http://example.com
That is fine, until you go to the next page, you get this URL:
http://example.com/index.php/page
It looks ugly, so for aesthetic purposes and to keep uniformity I created an htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /example.com/
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 http://example.com/
</IfModule>
and then by having this htaccess file at the base directory I get the URL to look like this:
http://example.com/page
Temp Fix and Questions Needing Answers
It was pointed out to me that because my $config['index_page'] variable is null that this is where the problems are stemming from. So I added the index.php to the beginning of my url in the form's action and it goes through.
Shouldn't the htaccess re-write handle this issue, and send it to where it is supposed to go where I have the index.php in the form's action URL or not?
Secondly, how would this affect the post variables? Because when I submit the form it still gets to where it needs to go to, it just shows null for all the variables, even though they are properly sent through the headers. This is where I am most confused.
If you need more information please let me know, but we are just trying to figure out why this is happening over here, it's kind of awkward. Thank you in advance!
Your question seems complicated. I think there might be an issue with installation steps. Remove index.php from config, set base url (also in application/config.php), set the encryption key(also there).
Check what are the session settings - did you change something there.
Also simplify htaccess (put it where is your index.php)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Is this local or server issue?
And last - try to use form helper, does it change something, whats inside console? Show more of your controller. You can check post inside one function
class Forms extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function form_processor()
{
//check if $_POST
if ($this->input->post()) {
$name=$this->input->post('name');
//process and redirect
}
$this->load->view('forms/my_form');
}
}
Also if you use xss_filtering or csrf_protection(check that in config.php) you should definitely use form helper.
/forms/form_processor/' method='post' id='testForm'>
Use base URL in form action.
If not work so use index.php after base URL.

URL Routing using RewriteRule

I am trying to create my own PHP MVC framework for learning purpose. I have the following directory structure:
localhost/mvc:
.htaccess
index.php
application
controller
model
view
config/
routes.php
error/
error.php
Inside application/config/routes.php I have the following code:
$route['default_controller'] = "MyController";
Now what I am trying to achieve is when any user visits my root directory using browser I want to get the value of $route['default_controller'] from route.php file and load the php class inside the folder controller that matches with the value .
And also if any user tries to visit my application using an url like this: localhost/mvc/cars, I want to search the class name cars inside my controller folder and load it. In case there is no class called cars then I want to take the user to error/error.php
I guess to achieve the above targets I have to work with the .htaccess file in the root directory. Could you please tell me what to code there? If there is any other way to achieve this please suggest me.
I have tried to use the .htaccess codes from here, but its not working for me
It all sounds well and good from a buzzword standpoint, but to me this is all a little confusing because I see PHP's model as an MVC model already. It's providing the API for you to program with and deliver your content to your web server Apache and your database (something like MySQL). It translates the code(model) for you into HTML(view) ... provided that's what you intend, and you're supplying code as the user input (control). Getting too wrapped up in the terminologies gets a little distracting and can lead to chaos when you bring someone in to collaborate who isn't familiar with your conventions. (This should probably never be used in a production environment for a paying gig.)
I can tell you that on the page that you referenced they guy's .htaccess file needs a little work. The [L] flag tells mod_rewrite that this is the last command to process when the rule returns true. So you would either need to do this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
Or the following... but he was using a passthru flag which means that he is implying there are other things that could be processed prior to the last rule (eg. might be rewrite_base or alias), but that's not actually the case with his .htaccess file since it's a little bare. So this code would work similar to the code above but not exactly the same. They can't be used together though, and really there would be no need to:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?url=$1
</IfModule>
The difference is the in the way it's processed. On the first .htaccess example you're passing any file to index.php regardless of whether it exists or not. You can [accidentally] rewrite a path that has a real file so that the real file is never accessed using this method. An example might be you have a file called site.css that can't be accessed because it's being redirected back to index.php.
On the second ruleset he's at least checking to see if the server doesn't have a file or a directory by the name being requested, then they're forwarding it to index.php as a $_GET variable (which seems a little pointless).
The way I typically write these (since I know mod_rewrite is already loaded in the config) is to to this:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^mydomain.com
RewriteRule (.*) http://www.mydomain.com/$1 [R=301,L]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule .* index.php
In my PHP code I pull the $_SERVER['REQUEST_URI'] and match it against a list of URIs from the database. If there's a match then I know it's a real page (or at least a record existed at some point in time). If there's not a match, then I explode the request_uri and force it through the database using a FULLTEXT search to see what potentially might match on the site.
Note: if you blindly trust the request_uri and query the database directly without cleaning it you run the risk of SQL injection. You do not want to be pwnd.
<?php
$intended_path = $_SERVER['REQUEST_URI'];
if(in_array($intended_path,$uris_from_database)){
//show the page.
} else {
$search_phrase = preg_replace('!/!',' ',$intended_path);
$search_phrase = mysqli_real_escape_string($search_phrase);
$sql = "SELECT * FROM pages WHERE MATCH (title,content) AGAINST ('$search_phrase');"
}
Sorry if this sounds a bit pedantic, but I've had experience managing a couple of million dollar (scratch) website builds that have had their hurdles with people not sticking to a standard convention (or at least the agreed upon team consensus).

Pretty URLs from DB

I am working on creating page links from DB like the following example.
Current page:
www.example.com/page.php?pid=7
In the DB it is saved as title "contact-us" under category "Company Info"
I want it to be like:
www.example.com/company-info/contact-us.html
I have tried different solution and answers but did not got any luck. I am not sure, where will be the PHP part and which rules to write for .htaccess files.
In apache (or .hataccess) do something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /proxy.php?_url=$1 [QSA,L]
So in a nutshell, if the resource being requested doens't exist, redirect it to a proxy.php file. From there $_REQUEST['_url'] will be the url the user was requesting.
Then create proxy.php in your home directory and add whatever logic you'd like to load the correct content.
If you use this from .htaccess, then you may need to add RewriteBase / to your config.
If you want to find this page by url, you will probably do this through php and .htaccess. Make a .htaccess that calls page.php for each and every request. You don't need the pid=7, because, well, how should the .htaccess know it is 7, right? :)
In page.php, you take the original url and split it on the slashes, so you get the category (company-info) and the page itself (contact-us.html). Then, you can look these up in the database. This is in a nutshell how many software works, including Wikipedia (MediaWiki) and CodeIgnitor.
Mind that 'company-info' isn't the same as 'Company Info'. You'll have to specify the url-version in the database to be able to use it for look-up.

How do I remove a variable name from a URL using htaccess?

So basically I want users to be able to go to my website with a URL of something like /45678, instead of having to use /?p=45678, so really I just want to remove the variable name. I've tried using mod_rewrite, but it seems that is only for removing the name when the page is visited.
Here is the current code:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^p=([0-9]+=$
RewriteRule ^/$ /%1 [R]
Simply change all of your links to /45678 rather than ?p=45678. Or did I misunderstand you completely? Because what I got from your post is that it works properly, unless you manually access the ?p=45678 where as it stays as ?p=45678.
EDIT:
This is what I am using for http://www.madphp.org/dev/, give it a go, works like a charm for me (it also removes the index.php part). To access your now cleaner URL you would simply explode the $_SERVER['PATH_INFO'] variable to get all of the required parameters within your PHP script.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Have you set up mod_rewrite correctly? If so, you can use variables like simple $_GET variables, in this case you must access $_GET['p'] in PHP.
I did this without using .htaccess, but it does query a database. I wrote this a while ago so it uses PEAR DB, adjust to your database/connection method. I'll just copy my code and let you figure out what changes you need.
$db=connect_db();
$name=substr($_SERVER['PHP_SELF'], 20);
$name=strtolower($name);
$id=$db->getone("select id from user where login='{$name}'");
header("Location: /dragonart/profile?user=" . $id);
If you store your information in a database this may be a nice alternative. The downside is that the the URL is not rewritten and the user is ultimately sent to a page with ending in a $_GET variable.
edit:
Just realized that using my method a simpler method can be used for the answer. Since my solution was used to find the id of a user using their username and then send someone to their profile (which requires the id) a better solution would be something like:
$var=substr($_SERVER['PHP_SELF'], $length);
header("Location: /path/to/page?p=".$var);
where $length is the usual length of the URL without the variable at the end.

Categories