Codeigniter spaces in url - php

I have a method which returns all jobs by category.
The problem it's when i have spaces in the category name. How could I access those results?
for ex if i access http://localhost/management_system/Job/get_jobs_by_cat/Architecture it will return all the jobs from the Architecture category.
But when i try to access the category Information Technology I can't do it while I have spaces into the url, so I've tried with _ - and i didn't get any response.
How I can fix this issue?

You would likely want to use urldecode() to decode the url parameters in the controller function processing this logic. In your controller, do something like this:
$jobCat = urldecode($this->uri->segment(4));
Then, you would pass $jobCat to your model.
Here are some other Stack Overflow links that might help your cause.
How to pass parameters with space to controller from URL in
codeigniter?
Php - Codeigniter url spaces
what is the use of $this->uri->segment(3) in codeigniter
pagination

You need to URL encode Information Technology.
$category = 'Information Technology';
$encodedCategory = rawurlencode($category);
$url = 'http://localhost/management_system/Job/get_jobs_by_cat/' . $encodedCategory;
echo $url;
// http://localhost/management_system/Job/get_jobs_by_cat/Information%20Technology

Related

Avoid URL transform with PHP

I´m having issues with a link that is created in a php controller (Yii Framework). The link must be like this: https://example.com/track/?id=HDkuY0je9d (HDkuY0je9d is a tracking code) but when the view is rendered i get https://example.com/track/?id=h-dku-y0je9d
PHP is adding dash delimited automatically.
$trackcode = $val['tracking'];
$url_tracking = Yii::app()->createUrl("/track/?id=".$trackcode);
$tracking = 'Tracking';
If you are using Yii2 in this, it has helper class for create url and url must have been
$url_tracking = yii\helpers\Url::to(['/track','id'=>$trackcode]);
and for generate link
<?=\yii\helpers\Html::a('Link description',$url_tracking,['target'=>'_blank']) ?>
Thanks, I solved changing the way i get app url. Changed
$url_tracking = Yii::app()->createUrl("/track/?id=".$trackcode);
for
$url_tracking = websiteUrl()."/track/?id=".$trackcode;

Clean URLS in MVC structure using PHP

I am creating a website using the MVC structure. Below is a code I have used to use clean URLS and load the appropriate files. However it only works for the first level.
Say I wanted to visit mywebsite.com/admin it would work, however mywebsite.com/admin/dashboard would not. The problem is in the arrays, how could I get the array to load content after the 2nd level along with the second level.
Would it be best to create an array like this?
Array
- controller
- view
- dashboard
Any help here would be great. Also as a side question. What would be the best way to set up "custom" urls. So if I were to put in mywebsite.com/announcement it would check to see if its got controllers, failing that, check to see if it's got custom content (maybe a file of the same name in "customs" folder, and then if there's nothing execute the 404 page not found stuff) This isn't a priority question though, but loosely associated in how the code works so I thought it best to add.
function hook() {
$params = parse_params();
$url = $_SERVER['REQUEST_URI'];
$url = str_replace('?'.$_SERVER['QUERY_STRING'], '', $url);
$urlArray = array();
$urlArray = explode("/",$url);
var_dump($urlArray);
if (isset($urlArray[2]) & !empty($urlArray[2])) {
$route['controller'] = $urlArray[2];
} else {
$route['controller'] = 'front'; // Default Action
}
if (isset($urlArray[3]) & !empty($urlArray[3])) {
$route['view'] = $urlArray[3];
} else {
$route['view'] = 'index'; // Default Action
}
include(CONTROLLER_PATH.$route['controller'].'.php');
include(VIEW_PATH.$route['controller'].DS.$route['view'].'.php');
var_dump($route['controller']);
var_dump($route['view']);
var_dump($urlArray);
var_dump($params);
// reseting messages
$_SESSION['flash']['notice'] = '';
$_SESSION['flash']['warning'] = '';
}
// Return form array
function parse_params() {
$params = array();
if(!empty($_POST)) {
$params = array_merge($params, $_POST);
}
if(!empty($_GET)) {
$params = array_merge($params, $_GET);
}
return $params;
}
Can you clarify this: "The problem is in the arrays, how could I get the array to load content after the 2nd level along with the second level."
I don't understand how you want this thing to work. I checked your code and it works. Maybe you just need to put $urlArray[1] instead of $urlArray[2] and 2 instead of 3? First element in the array is at index 0.
Usually it's done like this:
Url format:
/controller/action/param1/param2/...
-controller- should be a class. That class has a method/function called -action-.
ex. /shoes/show/121/ --> this will load controller shoes
and execute the method/function show(121)
that will show the shoes that have the id 121 in the
database.
ex. /shoes/list/sport --> this will load controller shoes
and execute function list('sport') that will list all
shoes in the sport category.
As you can see, you only load one controller and from that controller you run only one function and that function will get the rest of the path and use it as parameters.
If you want to have multiple controllers for one URL, then the rest of the controllers will have to be loaded from the main controller. Most MVCs (like CodeIgniter) load only one controller per URL.
Second question:
Best way for pretty urls would be to save them in the db. This means you can have URLs like this:
/I-can-write-anything-here-No-need-to-add-ids-or-controller-names
Then you take this URL and search it in db and get the -controller- and -action- that you need for this URL.
But I have yet to see a popular MVC framework do this. I guess the reason is that the db will get a lot of queries for text matches and that will slow things down.
Popular MVC frameworks use:
/controller/action/param1/param2
This has the benefit that you can directly find the controller/action from the url.
The downside is that you will get urls like:
/shoes/list/sport
//when what you really want is
/shoes/sport
//or just
/sport //if the website only sells shoes
This can be fixed by redirecting /shoes/sport to /shoes/list/sport
If you make your own MVC then you should use OOP because if not, thing will get ugly quick: all actions/functions are in the same namespace.
Personally I would recommend that you use one of the many PHP frameworks that exist as that will take care of the routing for you and let you concentrate on writing your application. CakePHP is one that I've used for a while and it makes my life so much easier.
What I do:
I create a .htaccess file that redirects an url like www.example.com/url/path/or/something to www.example.com/index.php?url=url/path/or/something, so it will be pretty easy to do an explode on your $_GET['url']
Second, it's better because everything a user input, will be redirected to your index.php, so you have FULL control over EVERYTHING.
If you want I can PM you the url to my mvc (bitbucket) so you can have a look on how I do this ;)
(Sorry for the others, but I don't like to put url's to my site in public)
edit:
To be more precise to your particular question; It will solve your problem, because everything goes to index.php and you have full control over the requested url.

PHP Zend_Paginator on mySql query using GET

I am trying to call pages using Zend_Paginate() on a query that loads based on a GET search string the query essentially does the following:
SELECT * FROM table WHERE column LIKE '%searchstring%' OR alt_column LIKE '%searchstring%';
The query works fine when called via search/submit text form and the URL returns something similar to
URLINK.php?search=searchstring
However when trying to move onto the next page the program dumps me back to the paginate alternate URL (used for errors or no page display)-- hope this last line makes sense it is late and am doing my best to type this up with transparency.
What is the best method when using paginate against URL.php?search=searchstring"?
A bit more on the call to the url
//search query
$search = searchQuery('search', 'list_sql_rows.php');
$results - searchTable($dbRead, $search);
search method using the variables above in the order below
if(isset($_POST['submit_search'])) { $searchstring = $_POST['searchstring'];
if($searchstring) { header('Location: results.php?search=' . $searchstring); } }
This bit works well, but when I try to call the results.php?page=2 with paginator the system reverts me to the fall back URL list_sql_rows.php as mentioned above. Any thoughts/comments are appreciated.
Just to clarify a search field/form from the search.php page sends the $searchstring to the results.php page via $_POST && $_GET as fail safe. The get method sends the $searchstring in the URL header so the results of the search DO work on the first page results.php?search=$searchstring. This works just fine. The pagination seems to lose the $searchstring, and I wonder if this is due to a loss of the $_POST/$_GET when paginator begins to 'paginate' it returns URL results.php?page=2 so it seems $_GET may not be the method of choice?
UPDATE
On the write track now paginate works it is my link structure that is broken.
_results_samples.php?search=robert&page=4_ will in fact return page 4 of the paginated results using the word ROBERT
SOLUTION FOUND VIA variant suggestion by ROCKYFORD
variant of recommended method by first persisting $searchstring
change to paginate links as shown below
<a href='" . $_SERVER['PHP_SELF'] . "?search=" . $searchstring . "&page={$page}'>$page</a>
Here is the example of correct using of pagination:
in action-method:
$select = $clients->getAll();
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
$paginator->setCurrentPageNumber($this->_getParam('page'));
$paginator->setItemCountPerPage(20);
$this->view->clients = $paginator;
in a view script:
<?php if (count($this->clients) > 0): ?>
...
<?php echo $this->paginationControl($this->clients, 'Sliding', 'partials/paginator.phtml'); ?>
<?php else: ?>
<h3 class="notice">No registered clients found!</h3>
<?php endif; ?>
But even if you will fail with this variant, you can always try to compose your own component, Zend only aids us in solving some tasks.
you need to make sure you preserve the query strings between requests, use Zend_Session_Namespace or Zend_registry.
Everytime Zend_Paginator loads a page when using the DbTableSelect or DbSelect adapters it has to hit the db with the query, it just changes the limit option.
Or you could just dump the whole query result into a Zend_Paginator_Adapter_Array and it will page through the array.
[edit]
you are going to have to persist the query string between requests someway so you can put it back in the url string, I usually use Zend_Registry, but then I use the whole MVC stack. You don't seem to be using the whole stack so you'll need another method, probably $_SESSION would work. I'm sure there are many other ways to persist this data.
P.S. you didn't mention which adapter you are using so I'm making some assumptions.
[edit]
Personally I always use $_post for this when possible to avoid all this, only seem to have this problem with $_get.

Multiple $_GET through links

I'm doing a website. There's a pagination, you click on links and they take you to the page you need, the links pass $_GET variable ( a href="?pn=2" ) and that works fine.
However when i add the category links (also contain $_GET variable
(a href="?sort=english") on the same page, which kind of sort the content on the page, and click it, the system simply overrides the url and deletes all the previous $_GET's.
For example, I'm on page 2 (http://website.com/index.php?pn=2)
and then I click this sorting link and what I'm expecting to get is this (http://website.com/index.php?pn=2&sort=english), but what I get is this:
(http://website.com/index.php?sort=english). It simply overrides the previous $_GET, instead of adding to it!
A relative URI consisting of just a query string will replace the entire existing query string. There is no way to write a URL that will add to an existing query. You have to write the complete query string that you want.
You can maintain the existing string by adding it explicitly:
href="?foo=<?php echo htmlspecialchars($_GET['foo']); ?>&bar=123"
Try using this:
$_SERVER['REQUEST_URI'];
On this link you can see examples. And on this link I have uploaded test document where you can try it yourself, it just prints out this line from above.
EDIT: Although this can help you get the current parameters in URL, I think it's not solution for you. Like Quentin said, you will have to write full link manually and maintain each parameter.
You could create a function that will iterate through your $_GET array and create a query string. Then all you would have to do is change your $_GET array and generate this query string.
Pseudocode (slash I don't really know PHP but here's a good example you should be able to follow):
function create_query_string($array) {
$kvps = array();
for ($key in $array) {
array_push($kvps, "$key=$array[$key]");
}
return "?" . implode("&", $kvps);
}
Usage:
$_GET["sort"] = "english";
$query_string = create_query_string($_GET);
You need to maintain the query parameters when you create the new links. The links on the page should be something like this:
Sort by English
The HTTP protocol is stateless -- it doesn't remember the past. You have to remind it of what the previous HTTP parameters were via PHP or other methods (cookies, etc). In your case, you need to remind it what the current page number is, as in the example above.

Codeigniter how to grab the original string from url_title()?

I'm trying to learn how to use code ignitor but I've run into a little problem. As with most people when they first use a framework, I too am making a blog. I'm trying to make my view links look like: http://localhost/blog/view/my-blog-post-title and I've gotten that far. But when I get to the actual view method is when I run into problems. Basically I'm my-blog-post-title refers to the 1st record of posts in my database. But the actual title looks like My Blog, Post Title.
So how do I get the id from my-blog-post-title when the original is My Blog, Post Title so I can pull that post from the database? Or should I just use numbers(I don't want to ;_;).
Well, I think the best solution and the easier approach would be to create a column in your posts table, something called "slug", which contains the url_title() output (the moment you create your article, you save that value in this db column as well as the other infos), and query against that instead of using this more complicated method.
So, you grab the last segment of the url, either via $this->uri->segment(3) or just by passing the whole uri to your controllers' method, and query against that column:
class Blog extends CI_Controller {
public function view($slug)
{
$this->load->model('blog_model');
$data['posts'] = $this->blog_model->search_slug($slug);
$this->load->view('myview',$data);
}
}
Model:
function search_slug($slug)
{
$this->db->select('id,title')
->from('posts')
->where('slug',$slug);
$query = $this->db->get();
return $query->row();
}
View 'myview.php':
echo $posts->id;
echo $posts->title;
You should be able to use something like
$parts = explode("/",$_SERVER['REQUEST_URI']);
$title=$parts[(count($parts)-1)];
to turn your url into an array and then grab the title from the last section. string replace the "-" with " " and then do a %like& search in your db for the title. Not sure that's the best approach but should work.
This code can get you as far as extracting the title:
$url_string = "view/my-blog-post-title";
function getOriginal($url_string) {
$url_parts = explode("/",$url_string);
$url_title = $url_parts[1];
$title_parts = array_map("ucfirst",
explode("-",$url_title));
return implode(" ",$title_parts);
}
echo getOriginal($url_string);
Which will output:
My Blog Post Title
The tricky part is where to insert the comma (,). This is tricky because blog post titles may be have more words like my-blog-post-title-some-other-words or my-blog-title-word-word-word. The comma can go anywhere.
If it is always constant that the comma is to be inserted after My Blog (My Blog is constant) then you just do an str_replace after calling getOriginai(..);
echo str_replace("My Blog","My Blog,","My Blog Post Title");

Categories