I've searched around and struggled to come up with a solution to this.
I've inherited a project with several thousand php files, each of which has multiple links in the form of:
<a href="_link.php?[RANDOMSTRING]">
Trouble is, I don't have the _link.php file.
I'm assuming its some kind of redirect script, as it is supposed to send the user to
RANDOMSTRING.php
when clicked.
It doesn't do anything nice like use a variable name like
_link.php?url=[RANDOMSTRING]
What code do I need to put into _link.php to just get it working for now. Its a hacky job and I'm planing a major overall and sticking all of this content into a database, but for now I just need the flatfile version running.
Cheers for your help.
Assuming that there are not actual [], then a hack is to create the file _link.php and inside, either redirect:
<?php
header("location: {$_SERVER['QUERY_STRING']}.php");
exit;
Or possibly include if that would work:
<?php
include("{$_SERVER['QUERY_STRING']}.php");
If there are actual [] then just trim them:
trim($_SERVER['QUERY_STRING'], '[]');
I'm from ASP.NET MVC background and this is first time I'm trying to write something in PHP.
In ASP.NET MVC we can develop models for our data and using the actions that we write we can get them or send them to another action. What I mean is that
public ActionResult Login_Action(LoginModel _Model) {
// Authenticating the user
return RedirectToAction(X);
}
when calling this the url that is shown in the address bar (in case of using GET, if it is POST nothing will be shown after the page name) will be:
www.WebsiteX.com/Login?Username=something&Password=something
The problem is that I don't even know how search for this in google (like by typing what exactly) because in Microsoft side, these are handled automatically the way I described.
But in case of PHP, how can I get the values in the address bar? do I have to get the actual address and then break the values down into arrays?
I'd appreciate any help.
First of all, this seems to be invalid for me: www.WebsiteX.com/Login?Username=something?Password=something The first parameter need to be ? and the others should be &.
Second: You can get your values of your parameters by accessing the $_GET global array.
Eg. for the username echo $_GET["Username"];
Are you using any framework? You should. And then, the Framework will give you the way to do that. In ASP.NET you use a Framework so do the same in PHP.
With vanille PHP you can get the GET values with $_GET['Username']. But please, use a framework.
I think that the most popular are Laravel and Symfony right now.
Example:
In laravel you can bind a parameter to a variable so you can do something like:
//Url: mywebsite.com/user/1/
Route::get('user/{id}', function($id)
{
return 'User '.$id;
});
Which is similar with the ASP.NET example.
My question might be little silly but please bear with me. I suppose var_dump should work anywhere in the code which calls its service but unfortunately i can't return anything if i use it in a controller, or model. ya it does work in the view/layout page.
I tried testing the following simple thing in one of my controller function and it returns nothing;
$foo = "bar";
var_dump($foo);
Please enlighten me!
I don't know Joomla, but in an MVC framework, the view expects data to come from the controller in a particular format, perhaps JSON or XML. When you call var_dump(), it will most likely mess up the syntax of this, so the application won't work. When you're debugging with this tool, you'll want to make use of the browser's console (Developer Tools or Firebug) to view what was returned. Go into the Network tab, select the URL of the controller, and then view the response data. There you'll see the output of var_dump().
For show a variable and pause the executing you have 3 options.
echo $variable;
print_r($variable);
var_dump($variable);
and you need to write die() after them to stop code and show your $variable.
Can you put PHP anywhere in a file? Inside tags and quotes? For example, is something like this guaranteed to work (even though it isn't always recognized by an IDE's syntax highlighter):
<tr><tbody <?php if(!$row) echo "style='display: none;'"; ?>>
<!-- stuff that we only want to show if $row exists -->
</tbody></tr>
Or for example:
<a href="http://www.google.com/search?q=<?= echo $searchTerm; ?>"</a>
I know I can test this sort of thing on my machine, but I'm wondering if it is guaranteed/defined behavior and if there are any edge cases that don't work that I've missed.
Also, is there good reason not to do this? Is it dangerous because the next person looking at the code might miss it? Should I put a comment in? Does having to add a comment defeat the purpose of this method - succinctness?
Yes you can put the php tags anywhere in the page (html) there is no stopping you on that.
If we go under the hood, your web server sends the code to the php interpreter via a handler and merges the output with your static html file and sends the merged file as the response.
To add to my answer, developers usually go for MVC based frameworks so that the php code inside html page is restricted to only printing the variables and the business logic is performed in the controllers. I personally prefer CakePHP. Apart from that you might not want to put code that manipulates session or performs redirection between html tags else you will recieve the headers already set error as you have already printed certain html code before modifying the headers.
I'm new to MVC and I'm trying to understand how MVC fits in to what I'm used to.
Let's say I have a simple static website with the pages: Home, About, Contact.
And let's say that I have one xhtml/css "template" which will be the view for the whole site. To keep it simple, in that tag I'll have a variable for the page contents.
So in the controller am I supposed to have an individual function for the content for each page????
For example:.
function home()
{
$data['content'] = "<p>some html home page content</p>";
$this->load->view('myView', $data);
}
function about()
{
$data['content'] = "<p>some html about page content</p>";
$this->load->view('myView', $data);
}
So while I know this is a super-simplified look, is the best practice to create a function for each different page?
But what if you have a site with 100 pages? Doesn't the controller get too big to manage?
But then again, if you had a single controller for each page, that also seems that it would be tough to manage?
I am beginning to understand how the MVC concept is helpful for database connection tasks as well as some CRUD as well. But I remain confused as how to think about "pages" in MVC.
Any advice is much appreciated.
What's the best practice?
You don't have to have a function for each page.
a quick example I've found is:
<?php
//This is an example of a KISSMVC controller
//It is simply a function, which will be called by an URL such as:
//http://example.com/article/show/234
//TIP: Please assign default values to all parameters
function _show($articleid=0) {
//SECTION 1: INPUTS
//Filter, sanitize and store all inputs used by this controller
$articleid=min(0,(int)$articleid); //zero or positive integer
$uid = isset($_SESSION['authuid']) ? $_SESSION['authuid'] : 0;
$someconfig = $GLOBALS['registry']['someconfig'];
//SECTION 2: LOGIC
//Call functions/objects that implement your business logic with the inputs from SECTION 1
//Data returned from your Model should not contain UI specifics (such as html code)
$loggedinuser = new User();
$loggedinuser->retrieve($uid);
$article = new Article();
$article->retrieve($articleid);
//SECTION 3: PRESENTATION
//Call the view templates with the data obtained from SECTION 2
//A change in UI should only affect code in this section
//Sometimes there is no output needed, only a header redirect is returned
if (!$loggedinuser->hasPermission('view_article')) {
$vars['body']='<p class="error">You have no permission to access this page!</p>';
View::do_dump(APP_PATH.'views/mainlayout.php',$vars);
exit;
}
$vars['article']=$article;
//article template is defined in views/layout/view_article.php
$vars['body']=View::do_fetch('layouts/view_article.php',$vars);
View::do_dump(APP_PATH.'views/mainlayout.php',$vars);
}
Taken from http://kissmvc.com/php_mvc_framework/code
Which is a PHP implementation of MVC (its seemed to me like you're working with PHP).
You might want to have a look at their implementation etc. It was just the first one I found. Hope this helps.
The controller in MVC tends to be the biggest part of your code base. So as far as worrying about it getting too big, that's to be expected.
However, when using MVC, you typically want the Model-View-Controller to be a 1 to 1 relationship. If you have an about page, you'll want a controller specifically for that view and the actions associated with what you can do on that page. The response may be to load another view, in which case another controller will respond to events to that. The model can be shared amongst the controller's, but you don't want any parts of your view to know anything about your model or it'll break MVC, the controller being the piece that functions as the glue.
If you are indeed doing something with PHP as dtroy mentioned, that'll probably help out. Unfortunately, I'm coming from experience with MVC on the iPhone. Same concept though all around.
In summary though:
If you keep the controller responsible solely for the actions that can occur on a given view, like button clicks, etc... it should help keep your controller from getting too large and unwieldy.
Edit:
I forgot to mention, in response to your concern which I didn't address. To help with, for instance, "Controller Explosion", you may not necessarily want to create a controller for each page, but one for each type of view. For example, you may have a AboutViewController and a ContentViewController, and maybe a loginViewController. The AboutView and LoginView would be pretty unique, but if you can reuse your contentView. So if someone requested something about "Widgets", your content view would simply display information about widgets that it retrieved from your model, and display it in the appropriate location defined by your view. then when the user requests something about "gears", you can reuse the same ContentViewController to display different different information in the same fashion.
Basically you'll have a Page controller for your Page model. Then each page that you create will have a url like "/Pages/1", which will get routed to the "show" action of your Page controller.
MVC certainly takes a bit of getting used to, but once you get the hang of it, you'll really like it. Also check out resources on REST design, which will really help with problems like this.
When I design websites now, I think in terms of resources (models, more or less). So for instance, you will have many pages or users or questions or recipes or... each of these things is a thing/model. I usually make a separate controller for each one and put 7 actions in that controller:
index - used to show a list of all the Pages (URL like "/Pages")
show - used to show an individual Page (URL like "/Pages/1")
new - used to show a form to create a new Page
edit - used to show an edit form for a Page
create - used to actually create the new Page from the new form
update - used to actually update the Page from the edit form
destroy - used to delete a Page
This isn't for everyone (I don't want to turn this into a REST debate), but it helps me a lot, and I think it makes sense when you're dealing with things that are clearly objects like Pages.
The controllers contain the empty functions if there are no actions on the page. You don't have to pass page content via controller.
Place all the content to 'view' component of current unit.
If you have a site with 100 pages, you would want most of your content to be stored in a database.
your URLs would be altered to look something like this:
http://yoursite.com/showpage?pageid=mvc
http://yoursite.com/showpage?pageid=home
http://yoursite.com/showpage?pageid=whatever
and your controller would look something like this:
function showpage()
{
$post = yourframework.getmodel('post').getPost($_GET['pageid']);
$data['title'] = "<p>" . $post.title . "</p>";
$data['content'] = "<p>" . $post.title . "</p>";
$this->load->view('myView', $data);
}
Not syntactically correct but you get the idea. You need to have only one function which delivers all 100 of your pages. This would work if all your pages have a similar structure.
In other words, mvc works just like vanilla php... (but hopefully looks a bit cleaner)