Remove old parameter in URL (PHP) - php

I'm using PHP to create a pagination for a table.
I'm using the following code to create the pagination link
<a class='page-numbers' href='$href&pagenum=$i'>$i</a>
With $href
$href = $_SERVER['REQUEST_URI'];
It works well, however, it messes with the address bar, adding each time a new pagenum parameter.
So it becomes pagenum=1&pagenum=3&pagenum=4....
How to improve that?

How about this? Went and tested, to be sure :)
<?php
$new_get = $_GET; // clone the GET array
$new_get['pagenum'] = $i; // change the relevant parameter
$new_get_string = http_build_query($new_get); // create the foo=bar&bar=baz string
?>
<a class="page-numbers" href="?<?php echo $new_get_string; ?>">
<?php echo $i ?>
</a>
Also, note that the whole $href bit is unnecessary. If you start your href with ?, the browser will apply the query string to the current path.
I bet you're going to be looping, though, so here's a version optimized for producing 10,000 page number links. My benchmarks put it as being ever so slightly faster at large numbers of links, since you're just doing string concatenation instead of a full HTTP query build, but it might not be enough to be worth worrying about. The difference is only really significant when there five or six GET parameters, but, when there are, this strategy completes in about half the time on my machine.
<?php
$pageless_get = $_GET; // clone the GET array
unset($pageless_get['pagenum']); // remove the pagenum parameter
$pageless_get_string = http_build_query($pageless_get); // create the foo=bar&bar=baz string
for($i = 0; $i < 10000; $i++):
// append the pagenum param to the query string
$page_param = "pagenum=$i";
if($pageless_get_string) {
$pageful_get_string = "$pageless_get_string&$page_param";
} else {
$pageful_get_string = $page_param;
}
?>
<a class="page-numbers" href="?<?php echo $pageful_get_string; ?>">
<?php echo $i ?>
</a>
<?php endfor ?>

$url = $_SERVER['REQUEST_URI'];
$urlparams = parse_url($url);
if(isset($urlparams['query']){
parse_str($urlparams['query'],$vars);
$vars['pagenum'] = $i;
$urlparams['query'] = http_build_query($vars);
} else {
$urlparams['query'] = 'pagenum='.$i;
}
$url = http_build_url($urlparams);
//http_build_url() is in PECL, you might need to manually rebuild the
//url by looping through it's components:
/*
$url=(isset($urlparams["scheme"])?$urlparams["scheme"]."://":"").
(isset($urlparams["user"])?$urlparams["user"]:"").
(isset($urlparams["pass"])? ":".$urlparams["pass"]:"").
(isset($urlparams["user"])?"#":"").
(isset($urlparams["host"])?$urlparams["host"]:"").
(isset($urlparams["port"])?":".$urlparams["port"]:"").
(isset($urlparams["path"])?$urlparams["path"]:"").
(isset($urlparams["query"])?"?".$urlparams["query"]:"").
(isset($urlparams["fragment"])?"#".$urlparams["fragment"]:"");
*/

Related

how to use "for" loop PHP to make multiple variable in PHP,

i have more then 5 link for image, so i want to make like this,
$p_image1, $p_image2, $p_image3, $p_image4, $p_image5
but i dont understand why my cod is not work...
this is my code for get array data:
$id = mysqli_real_escape_string($koneksi,$_GET['i']);
$query = mysqli_query($koneksi,"SELECT * FROM `tb_produk` WHERE `p_id` = '$id'");
$get = mysqli_fetch_array($query);
this is my code for loop:
if ($j_image > 1) {
for ($i = 1; $i <= $j_image; $i++) {
$p_image[] = $get['p_image'.$i];
if ($i > 4) {
break;
}
?>
<li data-uk-slideshow-item="<?php echo $i ?>">
<img src="<?php echo $get['p_image'.$i]; ?>">
</li>
<?php
}
}
?>
why this is not work, thanks for your help before :)
I think creating dynamic named variables is just a way to make things harder than it is.
Instead I believe fixing the problem is the solution.
Dynamic variables is just harder to work with than arrays and will make bugs in your code some day.
Here I use a foreach on the $get array which means it will loop the items there is and we don't have to count and guess stuff.
Then I removed this new array you created as I don't see the point of it and instead go directly to the output part with my foreach variable $image.
I also keep the code in PHP and echo the html as I find that easier to read, but that is purely opinion and you can do whichever you want.
$i=1;
foreach($get as $image){
if ($i > 4) {
break;
}
echo "<li data-uk-slideshow-item=" . $i .">\n";
echo ' <img src="' . $image . '">' . "\n";
echo "</li>\n";
$i++;
}
Example output:
<li data-uk-slideshow-item=1>
<img src="1">
</li>
<li data-uk-slideshow-item=2>
<img src="2">
</li>
<li data-uk-slideshow-item=3>
<img src="3">
</li>
<li data-uk-slideshow-item=4>
<img src="4">
</li>
Not sure if your code is supposed to output four or five items.
But I just left the if and break as it was in your code.
https://3v4l.org/MrAng
Array is the perfect way to handle multiple similar values. You should really not consider making separate variables for this.
Still, in order to create dynamic variables, you need to use an additional $, and wrap them in curly braces {..}:
for ($i = 1; $i <= $j_image; $i++) {
// Create string for dynamic variable name and put it inside curly braces
// use $ in front to define this as a new variable
${'p_image'.$i} = $get['p_image'.$i];
if ($i > 4) {
break;
}

How to properly paginate a foreach loop

I have a project I am working on, where I scan a directory and pull all of the images from the directory that will display the gallery images. Problem is, some galleries have 300+ images and this is causing a lag. I have looked around, but have not found a proper way of getting my code to paginate. Here is my code snippet of where I am running the foreach loop and getting each image source from the directory:
/** get the model's gallery
===================================================== **/
if(isset($_GET['count'])){
$photo_count = $_GET['count'];
}
if(isset($_GET['model_dir'])){
$model_dir = $_GET['model_dir'];
/** get the higres gallery images
===================================================== **/
$root_directory = $_SERVER['DOCUMENT_ROOT'];
$photo_directory = "{$root_directory}/members/content/model_gallery/{$model_dir}";
$gallery_list = scandir($photo_directory);
$gallery_list = array_diff($gallery_list, array('.', '..'));
foreach($gallery_list as $gallery){
echo "
<a href='{$index_url}join.php'>
<img alt='' src='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
data-image='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
data-description=''>
</a>
";
}
}
Any ideas on how I could go about paginating this code would be greatly appreciated.
I solved the problem myself. For those who had something tangible to respond with, thanks for your help. For others who just wanted to critique code, not knowing what the full purpose of the code is and whether or not it is the final piece of code, should probably keep your input to yourself.
/** get the model's gallery
===================================================== **/
if(isset($_GET['count'])){
$photo_count = mysqli_real_escape_string($_GET['count']);
}
if(isset($_GET['model_dir'])){
$model_dir = mysqli_real_escape_string($_GET['model_dir']);
/** get the higres gallery images
===================================================== **/
$root_directory = $_SERVER['DOCUMENT_ROOT'];
$photo_directory = "{$root_directory}/members/content/model_gallery/{$model_dir}";
$gallery_list = scandir($photo_directory);
$gallery_list = array_diff($gallery_list, array('.', '..'));
$photo_count = $photo_count;
$gallery_limit = 35;
$qty_pages = ceil($photo_count / $gallery_limit);
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }
$start_from = $page * $gallery_limit - $gallery_limit ;
$gallery_list = array_slice($gallery_list,$start_from,$gallery_limit);
echo "<div id='gallery'>";
foreach($gallery_list as $gallery){
echo "
<a href='{$index_url}join.php'>
<img alt='' src='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
data-image='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
data-description=''>
</a>
";
}
echo "</div>";
echo "<div class='contain_pagination'>";
if($photo_count != 0){
echo "<nav class='contain_model_nav'><ul class='pagination'>";
for ($i = 1; $i <= $qty_pages; $i++){
echo "<li><a href='{$index_url}pages.php?id=gallerytour&model_dir={$model_dir}&count={$photo_count}&total={$total_photo_count}&page={$i}'></a>";
echo "</ul></nav>";
}
}
echo "</div>";
}
?>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $photo_count;?>,
itemsOnPage: <?php echo $gallery_limit;?>,
cssStyle: 'light-theme',
currentPage: <?php echo $page;?>,
hrefTextPrefix: '<?php echo $index_url ?>pages.php?id=gallerytour&model_dir=<?php echo $model_dir; ?>&count=<?php echo $photo_count; ?>&total=<?php echo $total_photo_count; ?>&page='
});
});
</script>
That is how I was able to paginate the foreach loop. I used nogad's idea for the array_slice function and then I used this open source for the pagination functionality:
http://flaviusmatis.github.io/simplePagination.js/
From there I made sure I had the $photo_count, which contains the count of all images within the directory and essentially what I would be paginating through.
I then set my $gallery_limit per page, which was 35. From there, I determined the number of pages with $qty_pages and dividing by the total $photo_count / and the set $gallery_limit
Next I check if the page isset if it is, then $page is == to the $_GET[page] else it is $page is == 1.
Next I get the $start_from value by multiplying $page * $gallery_limit and then subtracting by $gallery_limit
Next I make the value for the $gallery_list which is an array = to array_slice($gallery_list,$start_from,$gallery_limit);
So my parameters within the function are the entire array of src images for the $gallery_list, the integer of where to start from, and the integer of the $gallery_limit, in this case I set it to a default of 35.
Next I check if $photo_count is != to 0 and then run my normal for loop. the parameters within the url for the anchor will be dependent obviously on your site. One thing to note, is to simply add the &page={$i} parameter to the end of your url.
Finally you use the pagination plugin to write a small jQuery script for the pagination functionality. You should be able to decipher what I did within the jQuery script. I hope this helps someone out, because I have looked at other answers, and none delivered a satisfied result. They were almost as moronic as people like OlegLoginov replying to your question.

PHP and Concrete 5 count subpages

Making mobile site with Concrete5 and using page list block with custom template. I'm trying to count sub pages using PHP.
<?php foreach ($pages as $page):
// Prepare data for each page being listed...
$title = $th->entities($page->getCollectionName());
$url = $nh->getLinkToCollection($page);
$target = ($page->getCollectionPointerExternalLink() != '' && $page->openCollectionPointerExternalLinkInNewWindow()) ? '_blank' : $page->getAttribute('nav_target');
$target = empty($target) ? '_self' : $target;
$description = $page->getCollectionDescription();
$description = $controller->truncateSummaries ? $th->shorten($description, $controller->truncateChars) : $description;
$description = $th->entities($description);
$mies = 0;
?>
<li class="ui-btn ui-btn-icon-right ui-li-has-arrow ui-li ui-btn-up-c" data-theme="c"><div aria-hidden="true" class="ui-btn-inner ui-li"><div class="ui-btn-text"><a target="<?php echo $target ?>" class="ui-link-inherit" href="<?php echo $url ?>">
<h2 class="ui-li-heading"><?php echo $title ?></h2>
<p class="ui-li-desc"><?php echo $description ?></p>
</a>
</div><span class="ui-icon ui-icon-arrow-r ui-icon-shadow"></span><span class="ul-li-count ui-btn-corner-all ul-count-second"><?php echo count($mies) ?></span></div></li>
<?php endforeach; ?>
So, probably need to use Count function(or length?), I don't know. If I am editing wrong place please advice if you have any experience in Concrete5 cms.
If you want to show the corresponding page number in the span element in your code:
<span class="ul-li-count ui-btn-corner-all ul-count-second"><?php echo $mies; ?></span>
If you want to show the remaining sub-pages, then in the html code snippet above just replace $mies with count($pages) - $mies like:
<span class="ul-li-count ui-btn-corner-all ul-count-second"><?php echo count($pages) -$mies; ?></span>
You would first have to initialise $mies before you start the forloop so it should be something of the form:
<?php
$mies = 0;
foreach ($pages as $page):
//Rest of your code and increment $mies with every iteration
$mies ++; //This ensures that you are counting the corresponding pages
?>
If you want to get the count of total number of sub-pages, you just have to echo out $mies outside the for block may be like:
<?php
endforeach;
echo $mies; //Shows you the total number of pages processed inside the for loop.
//or Just find the length of pages array
echo count($pages);
?>
As far as getting the length of array is concerned you could use count or sizeof. I stumbled upon a SO question about using count or sizeof method for finding the length of an array.
This should get you started in the right direction.
You need the parent ID;
$parentId = Page::getCollectionParentId();
Note that Page::getCollectionParentId() gets the current page's parent ID,so you may want to try;
$parentId = $page->getCollectionParentID();
Then create a new PageList to filter with and filter by the parentId;
Loader::model('page_list');
$pl = new PageList();
$pl->filter(false, '(p1.cParentID IN ' . $parentId . ')');
// Get the total
var_dump($pl->getTotal());
This is untested but the theory makes sense.
This is likely a bit simpler.
$pl->getTotal()
$pl is the PageList object that is set in the controller.
Also, these days you can just use the h() method instead of writing out $th->entities()
Edit: I should clarify that you don't need to do a $pl = new PageList() because $pl is already set to the PageList object in the controller and passed to the view.

Pass links as variable in php and echo it on html

i must pass multiple link as variables on php
ex: www.mysite.com/dl.php?link=www.google.com&link2=yahoo.com&link3=youtube.com and so on, there is a variable number of links, and then i want to put them on and html page generated dynamically based on the number of links i inputed, in the example i did, the links was 3, so it must be:
<html><center>
Click to download part 1
Click to download part 2
Click to download part 3
</center></html>
can someone help me with this problem?
Parameters you append on your URL can be accessed through $_GET in php.
Take a look at this page: http://php.net/manual/en/reserved.variables.get.php
Update: If you have a variable number of get parameters and you want to get them all just use a foreach loop:
foreach($_GET as $key => $url) {
echo $url;
}
Instead of using different parameter names for all urls, use an array:
www.mysite.com/dl.php?link[]=www.google.com&link[]=yahoo.com&link[]=youtube.com
Then, in dl.php, $_GET['link'] is an array. You can iterate like this:
for ($i = 0; $i < count($_GET['link']); ++$i) {
echo 'Click to download part ' . ($i + 1) . '';
}
If URL = www.mysite.com/dl.php?link1=www.google.com&link2=yahoo.com&link3=youtube.com
<?php
for($i = 0; $i < count($_GET); $i++)
{
?>
Click to download part <?php echo ($i+1);?>
<?php
}
?>
If the only get value that is the URLs then just loop through...
foreach ($_GET as $url)
{
echo $url
}

PHP dynamically generated hit counter

I am a total PHP novice and am trying to write what I think is a pretty simple script. This is the code I have so far:
HTML / PHP
<?php
$hits = file_get_contents('hits.txt');
++$hits;
file_put_contents('hits.txt', $hits);
echo $hits;
$url = $_GET['w'];
?>
<iframe src="<?php echo $url; ?>"></iframe>
<p>
<?php echo $hits; ?>
</p>
The result is a page with an iframe and a hit counter.
The problem with this script is that if the variable $url changes, the hit counter does not. My goal would be that if I visited http://www.website.com/index.php?w=blue.html I would get a different counter than if I visited http://www.website.com/index.php?w=yellow.html.
EDIT: I should add that this script is designed to accept any URL. I realize this complicates things significantly. My ultimate goal would be that if the counter didn't already exist for that particular URL, it would be generated on the fly.
Your current code saves the hit points for every page to the same file as a simple string.
You have a number of options. Here's one that would work if you prefer to stick with text files instead of databases.
You could take the URL in, hash it, and save the counter for that page in a hash-named text file.
Something like
if( isset($_GET) && !empty($_GET['W']) ){
$url = md5($_GET['w']);
$hits = file_get_contents('/hit_counters/'.$url.'.txt');
$hits++;
file_put_contents('/hit_counters/'.$url.'.txt', $hits);
}
and then later you could echo out the hits under that or pull the hits in on another script and echo like that.
If you need it to create new ones on the fly, you could add something like
if(!is_file('/hit_counters/'.$url.'.txt')){
$fh= fopen('/hit_counters/'.$url.'.txt', 'w');
fwrite($fh, '1');
fclose($fh);
}
NOTE
This could end up creating a ton of tiny text files, though. So be aware. If you are worried about that, you would really need to look into a database or read in a text file line by line to find the same hash.
TO IMPLEMENT
Replace the top part of your code within the <?php ?> with the following:
if( isset($_GET) && !empty($_GET['W']) ){
$url = md5($_GET['w']);
if(!is_file('/hit_counters/'.$url.'.txt')){
$fh= fopen('/hit_counters/'.$url.'.txt', 'w');
fwrite($fh, '1');
fclose($fh);
}else{
$hits = file_get_contents('/hit_counters/'.$url.'.txt');
$hits++;
file_put_contents('/hit_counters/'.$url.'.txt', $hits);
}
}
This will take the page name in, hash it, check to see if /hit_counters/THEHASH.txt exists, and create it if not or add +1 to it otherwise. A hash is sort of like encryption, but not really. It will change your $_get['w'] into a longer random-looking string.
You're writing the same hits.txt file regardless of what $_GET['w'] is set to. Try putting the hits.txt file in a folder like this:
<?php
$url = $_GET['w'];
$dir = str_replace(".html", "", $url);
$hits = file_get_contents($dir.'/hits.txt');
++$hits;
file_put_contents($dir.'/hits.txt', $hits);
echo $hits;
?>
<iframe src="<?php echo $url; ?>"></iframe>
<p>
<?php echo $hits; ?>
</p>

Categories