I am using a MVC Framework for my PHP projects and how it works is as follows:
We have the a root that's like http://localhost/myproject.
And it accepts an url like this: http://localhost/myproject/example-controller/example-function/params
So what it does is it goes to the example-controller and executes the function example-function where we have the possibility to add parameters like http://localhost/myproject/example-controller/example-function/1/2/3
So I have a dashboard where I want to be able to apply crud functionality to users and articles so the url becomes as follows:
http://localhost/myproject/dashboard/users, which means that it will execute the function users but let's say I want to create a new user the link then becomes dashboard/users/create but it will see create as a parameter and not as an actual function that needs to be executed.. so I understand I would have to make a UserController and a ArticleController but that means the link will become user/create or article/create in which case it doesn't use the DashboardController anymore.
If anyone understood what I tried to describe could someone come up with a possible explanation on how to solve this issue.
I have found a solution to my problem and rewrote the whole splitUrl() function so it now accepts what I need.
function splitUrl()
{
if (isset($_GET['url'])) {
require(ROOT. 'core/routes.php');
$tmp_url = trim($_GET['url'], "/");
$tmp_url = filter_var($tmp_url, FILTER_SANITIZE_URL);
$tmp_url = explode("/", $tmp_url);
$param = ['params' => [], 'found' => false];
foreach ($routes as $route => $value) {
//echo("We iterate over a new route called <strong>". $route. "</strong><br>");
$tmp_route = explode("/", $route);
// Variables for the length of the arrays;
$route_count = count($tmp_route);
$url_count = count($tmp_url);
//echo("The route count = <strong>". $route_count . "</strong> and the url count = <strong>". $url_count. "</strong><br>");
// Check if the length of the route in our acceptable routes array is equal to the length of the url.
if ($route_count == $url_count) {
$indexCount = null;
for ($i = 0; $i < $route_count; $i++) {
if ($tmp_route[$i] == '{param}') {
$indexCount = $i;
//echo("A parameter has been found at index <strong>" . $indexCount . "</strong><br>");
break;
}
}
if ($indexCount == null) {
$indexCount = count($tmp_route);
//echo("A parameter has NOT been found so the index has been set to <strong>". $indexCount. "</strong><br>");
}
$doContinue = false;
for ($i = 0; $i < $indexCount; $i++) {
//echo("We are comparing value <strong>". $tmp_route[$i] . "</strong> to <strong>". $tmp_url[$i] ."</strong><br>");
if ($tmp_route[$i] == $tmp_url[$i]) {
//echo("Value <strong>". $tmp_route[$i] ."</strong> appears to be valid<br>");
continue;
} else {
//echo("Value <strong>". $tmp_route[$i] ."</strong> appears to be invalid<br><hr>");
$doContinue = true;
break;
}
}
if ($doContinue) continue;
$count = 0;
for ($i = 0; $i < $route_count; $i++) {
if ($tmp_route[$i] == $tmp_url[$count]) {
$count++;
continue;
} else {
array_push($param['params'], $tmp_url[$count]);
$count++;
}
}
} else {
// This means the route that we are iterating over right now can not possibly be the one we are looking for as the length is not equal to the length of the url.
continue;
}
$param['controller'] = explode("#", $value)[0];
$param['action'] = explode("#", $value)[1];
return $param;
}
}
Related
Im trying to get the number of class and methods in a specific directory which contain sub folder and scan through them. So far I can only count the number of files.
$ite=new RecursiveDirectoryIterator("scanME");
//keyword search
$classWords = array('class');
$functionWords = array('function');
//Global Counts
$bytestotal=0;
$nbfiles=0;
$classCount = 0;
$methodCount = 0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
$filesize=$cur->getSize();
$bytestotal+=$filesize;
if(is_file($cur))
{
$nbfiles++;
foreach ($classWords as $classWord) {
$fileContents = file_get_contents($cur);
$place = strpos($fileContents, $classWord);
if (!empty($place)) {
$classCount++;
}
}
foreach($functionWords as $functionWord) {
$fileContents = file_get_contents($cur);
$place = strpos($fileContents, $functionWord);
if (!empty($place)) {
$methodCount++;
}
}
}
}
EDIT: I manage to count the keyword class and function but the problem is it only concatenate for each file. Eg: I have 2 class in one file it will just count 1. How do I count for each keyword in a file?
The only time you define $classContents is at the top where you're attempting to get the contents of the directory:
$classContents = file_get_contents('scanMeDir');
You should be getting the contents of each file while looping through the RecursiveDirectoryIterator results. (You also don't need to create a new iterator instance):
foreach ($ite as $filename => $cur) {
$classContents = file_get_contents($filename);
...
}
using token instead of keyword is the better solution for this
$bytestotal=0;
$nbfiles=0;
$fileToString;
$token;
$pathInfo;
$classCount = 0;
$methodCount = 0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
$filesize=$cur->getSize();
$bytestotal+=$filesize;
if(is_file($cur))
{
$nbfiles++;
$fileToString = file_get_contents($cur);
$token = token_get_all($fileToString);
$tokenCount = count($token);
//Class Count
$pathInfo = pathinfo($cur);
if ($pathInfo['extension'] === 'php') {
for ($i = 2; $i < $tokenCount; $i++) {
if ($token[$i-2][0] === T_CLASS && $token[$i-1][0] === T_WHITESPACE && $token[$i][0] === T_STRING ) {
$classCount++;
}
}
} else {
error_reporting(E_ALL & ~E_NOTICE);
}
//Method Count
for ($i = 2; $i < $tokenCount; $i++) {
if ($token[$i-2][0] === T_FUNCTION && $token[$i-1][0] === T_WHITESPACE && $token[$i][0] === T_STRING) {
$methodCount++;
}
}
}
}
I have any array of data "example.com/imports", "example.com/var", "example.com/js" i want to remove all urls which contain this for sitemap.
Some of my url data is like the following
"example.com/imports/product.html",
"example.com/imports/product1.html",
"example.com/var/cache/5t46fdgdyg7644gfgfdgr",
"example.com/js/scripts.js"
I have this code
for ($i = 0; $i <= count($urls); $i++) {
$url = $urls[$i];
if (in_array($url, $remove_urls)) {
// found remove url
}else{
echo $url;
}
}
However this only removes if the url is exact match such as "example.com/imports" is there a way to check against start
Instead of in_array($url, $remove_urls) try to use strpos:
foreach ($urls as $url) {
$remove = false;
// loop $remove_urls and check if $url starts with any of them
foreach ($remove_urls as $remove_url) {
if (strpos($url, $remove_url) === 0) {
$remove = true;
break;
}
}
if ($remove) {
// remove url
} else {
echo $url;
}
}
You can use preg_grep function like that:
$urls = ['imports', 'var', 'js'];
$url_pattern = '/example.com\/(' . implode('|', $urls) . ')\/.*/';
$removed = preg_grep($url_pattern, $remove_urls);
here an example.
I am building a script thats goal is to check up to 100 URLS for validity (No 404).
The only variable in the URL is the page number, like so:
http://example.com/category/id/products/page/1
http://example.com/category/id/products/page/2
and so on up to 100,
as soon as my code reaches an invalid URL, I want it to stop and echo the number it has reached, this is the code I am trying to no avail:
$url ="http://example.com/category/id/products/page/1";
if (false !== strpos($url, $id)) {
$pageNumber = 2;
$check = true;
do{
$urlIterate = "http://example.com/category/id/products/page/".$pageNumber;
if(false !== strpos($urlIterate, $id)){
$pageNumber++;
}
else{
$check = false;
}
}
while($pageNumber <= 99);
}
else{
$check = false;
echo 'No pages were found at all';
}
echo "There were ". $pageNumber." pages.;
?>
Im not sure if this is what youre looking for, but try this:
<?php
$id_to_search = "90";
for ($i = 1; $i <= 100; $i++) {
$url = "http://example.com/category/id/products/page/" . $i;
$values = parse_url($url);
$paths = explode('/', $values['path']);
$id_from_url = $paths[5];
if ($id_to_search === $id_from_url) {
$headers = get_headers($url);
if ($headers[0] == 'HTTP/1.0 404 Not Found') {
echo "URL Found! URL is invalid(404). URLs searched = " . $i . "<br>";
} else {
echo "URL is valid<br>";
}
} else {
echo "URL was searched but it does not match the ID we are looking for<br>";
}
}
Why are you not using the for loop? It will be better while we know how much iterations will we need.
for($i = 1; $1<=100; $i++){
$urlIterate = "http://example.com/category/id/products/page/".$i; //generate url
$headers = get_headers($urlIterate, 1); //get headers
if($headers[0] != 'HTTP/1.1 200 OK'){ //if we have an error
if($i > 1) //if there was at least one found
echo 'Last found number is ' . ($i-1);
else
echo 'No pages were found at all';
break; //stops the 'for' loop
}
}
Your code is looking for $id in urls - what's the point?
Following is my view I am catching the data from the model and displaying on the view using
flashdata in codeigniter
My Controller cart.php
public function coupon(){
for ($i = 0; $i <= $this->input->post("products_in_cart"); $i++) {
if (!empty($this->input->post("coupn-" . $i))) {
$couponname = $this->input->post("coupn-" . $i);
$products_id = $this->input->post("product_id" . $i);
$data = $this->home_model->getCoupon($couponname, $products_id);
$data1 = 'hello';
$info = array(
"PromotioanlName" => $data->PromotionalName,
);
} else {
$info = 'Thers in no value<br>';
}
}
echo $this->session->set_flashdata('message', $info);
redirect(site_url('cart'));
}
My view cart.php
$message = $this->session->flashdata('message');
print_r($message);
But my problem is that my data is overwritten by the next value
in for loop, you have written if and in if, $info is an array and in else, $info is string!! Thus in loop when condition of if will be true, it'll be worked as an array and it'll be overwritten if condition will be true again in second recurs of loop!! And while condition false, it'll return string that will overwrite your array..
Try by using, $info[] instead of $info.. May be it solved your problem..
public function coupon(){
for ($i = 0; $i <= $this->input->post("products_in_cart"); $i++) {
if (!empty($this->input->post("coupn-" . $i))) {
$couponname = $this->input->post("coupn-" . $i);
$products_id = $this->input->post("product_id" . $i);
$data = $this->home_model->getCoupon($couponname, $products_id);
$data1 = 'hello';
$info[] = array(
"PromotioanlName" => $data->PromotionalName,
);
} else {
$info[] = 'Thers in no value<br>';
}
}
echo $this->session->set_flashdata('message', $info);
redirect(site_url('cart'));
}
I am working on a php site that needs to search a set of files with any combination of search fields.
The possible search fields are
id, year, building, lastname, firstname, birthdate
The folder structure and file names are as such
/year/building/file.pdf
The filenames contain the data to search
id_lastname_firstname_MM_dd_yy.pdf
I have everything working on the site except this part. Originally I only had ID, year, and building and I was able to do if's to check for every possibility of combinations. Now there is way more combinations so it much more complex.
I was thinking nested if and in_array or such, but there has to be a better way. I just learning my way around php.
I would like to be able to search with any combination of fields. I can change the filenames if it helps.
I started with something like this
function search($transcripts, $studentid=null, $year=null, $building=null, $last=null, $first=null, $birthdate=null){
$ext = '.pdf';
date_default_timezone_set('America/Los_Angeles');
$dir_iterator = new RecursiveDirectoryIterator("../transcripts");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
if ($file->isFile()){
$path = explode('\\',$file->getPath());
$fname = explode('_', $file->getBasename($ext));
if($path[1] == $year){
if($path[2] == $building){
if(in_array($last, $fname, true)){
if((in_array($first, $fname, true)){
if((in_array($birthdate
Originally I had seperate functions depending on which fields where filed in.
function bldStuSearch($building, $studentid, $transcripts){
$ext = '.pdf';
date_default_timezone_set('America/Los_Angeles');
$dir_iterator = new RecursiveDirectoryIterator("../transcripts");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
$results = explode('\\',$file->getPath());
//var_dump($results);
if (($file->isFile()) && ($file->getBasename($ext)==$studentid) && ($results[2] == $building)){
//echo substr($file->getPathname(), 27) . ": " . $file->getSize() . " B; modified " . date("Y-m-d", $file->getMTime()) . "\n";
$results = explode('\\',$file->getPath());
//var_dump($results);
//$building = $results[2];
$year = $results[1];
//$studentid = $file->getBasename($ext);
array_push($transcripts, array($year, $building, $studentid));
//var_dump($transcripts);
//$size += $file->getSize();
//echo '<br>';
}
}
//echo "\nTotal file size: ", $size, " bytes\n";
if (empty($transcripts))
{
header('Location: index.php?error=2'); exit();
}
return $transcripts;
}
Now I am trying to have one search function to check for any combination? Any idea that would at least put in the right direction?
Thanks.
So I had an idea about doing a scoring system but then dismissed it. I came back to it and found a way to make it work using a weighted scoring system.
This allows the search to be super flexible and maintain being portable, not requiring a database for the metadata and using the filename as the search data without having to search each PDF. I am using A-Pdf splitter to split the PDF into separate files and add the metadata to the filename.
I hope someone some day finds this useful for other searches. I am really happy the way this turned out.
I will post the entire code when I am done on http://github.com/friedcircuits
One thing I should change is to use named keys for the arrays.
Here is the resulting code. Right now the birthdate has to be entered as m-d-yyyy to match.
function search($transcripts, $studentid=null, $year=null, $building=null, $last=null, $first=null, $birthdate=null){
$ext = '.pdf';
$bldSearch = false;
date_default_timezone_set('America/Los_Angeles');
if (($building == null) AND ($year == null)){ $searchLocation = "../transcripts";}
elseif (($year != null) AND ($building != null)){$searchLocation = "../transcripts/".$year."/".$building;}
elseif ($year != null) {$searchLocation = "../transcripts/".$year;}
elseif ($building != null) {
$searchLocation = "../transcripts/";
$bldSearch = true;
}
else{$searchLocation = "../transcripts";}
$dir_iterator = new RecursiveDirectoryIterator($searchLocation);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
$score = 0;
foreach ($iterator as $file) {
if ($file->isFile()){
//Fix for slashes changing direction depending on search path
$path = str_replace('/','\\', $file->getPath());
$path = explode('\\',$path);
$fname = explode('_', $file->getBasename($ext));
//var_dump($path);
//echo "<br>";
//var_dump($fname);
//echo "<br>";
//fix for different search paths
if($path[1] == "transcripts"){
$pYear = $path[2];
$pbuilding = $path[3];
}
else{
$pYear = $path[1];
$pbuilding = $path[2];
}
if ($bldSearch == true){
if ($building != $pbuilding) {continue;}
}
//$fname[1] = #strtolower($fname[1]);
//$fname[2] = #strtolower($fname[2]);
if($fname[0] == $studentid){
$yearS = $pYear;
$buildingS = $pbuilding;
$studentidS = $fname[0];
$lastS = $fname[1];
$firstS = $fname[2];
$birthdateS = $fname[3];
array_push($transcripts, array($yearS, $buildingS, $studentidS, $lastS, $firstS, $birthdateS));
continue;
}
if($pYear == $year){
$score += 1;
}
if($path[2] == $building){
$score += 1;
}
if(#strpos(#strtolower($fname[1]),$last) !== false){
$score += 3;
}
if(#strpos(strtolower($fname[2]), $first) !== false){
$score += 3;
}
if($fname[3] == $birthdate){
$score += 3;
}
//echo $score." ";
if ($score > 2) {
$yearS = $pYear;
$buildingS = $pbuilding;
$studentidS = $fname[0];
$lastS = $fname[1];
$firstS = $fname[2];
$birthdateS = $fname[3];
array_push($transcripts, array($yearS, $buildingS, $studentidS, $lastS, $firstS, $birthdateS));
//var_dump($transcripts);
}
}
$score = 0;
}
if (empty($transcripts))
{
header('Location: index.php?error=2'); exit();
}
return $transcripts;}