Clean way to write urls instead of concatenation - php

I have been finding myself doing URLs like this:
$link = base_url('post') . '/' . $post_id . '/' . $slug . '/page/' . $page_num;
To form http://example.com/post/10/some-post-name/page/1
Needless to say, it's pretty messy, but I can't think of an alternative? Is there a better way write links with variables in it?
I am using Codeigniter as a framework if there is a solution involving it.

You have a few ways:
First, via sprintf:
sprintf('%s/%s/%s/page/%s', base_url('post'), $post_id, $slug, $page_num);
Or via an array implode:
implode('/', array(base_url('post'), $post_id, $slug, 'page', $page_num));
Or if you put all your values into variables, you can take advantage of string interpolation.
$url = ...;
...
"$url/$post_id/$slug/page/$page_num";
The last one is longer when you take into account the variable assignment block, but it combines succintness with readability.

Use sprintf:
$link = sprintf('%s/%d/%s/page/%d', base_url('post'), $post_id, $slug, $page_num);

You could do something like this:
$link = site_url("post/{$post_id}/{$slug}/page/{$page_num}");
You really should be using site_url() instead of base_url() for CI links. base_url() is meant for non-CI assets, like images and css.
site_url() will point to the correct front controller path, so you can update your configuration at will, and everything using that to build paths will update accordingly.
I revised my answer. Use the curly brace notation and avoid using extra functions. You can pass an array of arguments to the function, like so:
$link = site_url(array('post', $post_id, $slug, 'page', $page_num));
But working with arrays is slower. This can be useful if you need to dynamically build the url, though.

You could do it the old fashioned way with a function!
function buildlink($base_url,$post_id,$slug,$page_num)
{
return $base_url . '/' . $post_id . '/' . $slug . '/page/' . $page_num;
}
call it like this
$link = buildlink(base_url('post') ,$post_id, $slug ,$page_num);
but maybe i'm missing something

Related

PHP syntax -Breaking one-liners of paramaters and returns / echo

Using arrays, I see quit often the following formatting :
$somearray = array( 'one'=>'one_value',
'twokey'=>'two_value',
'some_third_value'=>'some_other_value',
'987654'=>'12340987',
'confused_yet_456789'=> $some_var,
'confused_yet_rt78466'=>'two_value'
);
that is of course instead of the one liner :
$somearray = array( 'one'=>'one_value','twokey'=>'two_value','some_third_value'=>'some_other_value','987654'=>'12340987','confused_yet_456789'=> $some_var,'confused_yet_456789'=>'two_value');
However , I for myself have never encountered or seen it used in a functions $parameters assignment, e.g :
function my_function_3($somevar='some_value_or_other',$title='some_87654_num_value',$cool_stuff='right_or_left',$dashboards='91234765',$menu='some_6374_menu'){
return $cool_stuff;
}
Expanded to :
function my_function_3( $somevar='some_value_or_other',
$title='some_87654_num_value',
$cool_stuff='right_or_left',
$dashboards='91234765',
$menu='some_6374_menu'
){
return $cool_stuff;
}
The same goes for echo or return.
From this :
$output .= '<img src="http://chart.apis.google.com/chart?cht=qr&chs='.$qr_size .'x'.$qr_size .'&chld=L|4&chl=' . $string . '" width="'.$qr_size.'" height="'.$qr_size.'" alt="Some alt to describe QR code" title="QR code for your phone"/>';
to this :
$output .= '<img src="http://chart.apis.google.com/chart?cht=qr&chs='.
$qr_size .'x'.
$qr_size .'&chld=L|4&chl=' .
$string . '" width="'.
$qr_size.'" height="'.
$qr_size.'" alt="Some alt to describe QR code" title="QR code for your phone"/>';
So , my question is :
Can I use this syntax or formatting also in $parameters assignment in a function, as well as echo / return ?
if no - why ? can it fail on certain configs ? is it just wrong ?
..and if yes , what is the correct way to do so (break the line BEFORE or AFTER the comma / dot ) ??
Yes you can use new lines anywhere it PHP. They don't have any syntactic meaning like they do in Javascript (where a new line means terminate the current statement) or Java where new lines can't be used within strings.
In fact all whitespace is trimmed within PHP, not just newlines, but spaces and tabs as well.
what is the correct way to do so
That is a matter of taste but I prefer to have the dot/comma before the new line, as that produces code that is easiest to read.
Slightly more controversially, if the parameters won't fit on a single line easily, I also prefer to have the multi-line parameters use one tab more indentation than the code they're in, rather than aligning with the bracket of the function.
$arg1 = simpleFunction();
$arg2 = simpleFunction2($arg1);
$result = testFunctionWithManyParameters(
$arg1,
$arg2,
$arg3,
$arg4,
$arg5
);
As again, imho, it makes reading the code easier than having them indented massively.
$result = testFunctionWithManyParameters($arg1,
$arg2,
$arg3,
$arg4,
$arg5
);

Constructing a URL based on existing variables

I'm a bit of a PHP newbie, and I'm trying to do what I believe is quite a complicated operation on a website. So I need your help :)
What I want to do is request a specific page for each client, the only URL variables involved are at the end, as normal.
Basically my variables have been set previously in the script, what I want to say is;
The URL is http://site.com/index.php?image=$clientnumber Somehow.
if you guys could give me some insight on how to do this, that would be great!
You can use the sprintf function to do this:
$url = sprintf('http://site.com/index.php?image=%s', $clientnumber);
PHP String Operators
$new_url = "http://site.com/index.php?image=$clientnumber";
or
$new_url = 'http://site.com/index.php?image=' . $clientnumber;
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data) . "\n";
Results in:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
For your needs:
$data = array('image'=> $clientnumber);
echo 'index.php?' . $data;
Will give you:
index.php?image=878787283

Passing string and int in URL

I think this isnt a very typical question but i am stuck here.
I have to pass a String and an Integer in an URL for my PHP to process it.
I am building the link like...
$link = 'index.php?NAME=' . $name . '&id=' . $id;
but when it occurs in URL, its gets changed to
index.php?NAME=hello&id=10
and now id isnt being recognised by GET.
Use url_encode() for all of your variables. Or, better yet, use http_build_query().
$link = 'index.php?' . http_build_query(array(
'NAME' => $name,
'id' => $id
));
http://php.net/manual/en/function.urlencode.php
http://php.net/manual/en/function.http-build-query.php
Link should work, can you elaborate how you're showing the link?
try this simple solution;
$link = 'index.php?NAME="{$name}&id={$id}"';

define a variable in a query (?)

I have to define two variables:
<?php
$path = 'http://' . $_SERVER['SERVER_NAME'] . '/root/images/folderX/';
$files = scandir('images/folderX/');
?>
In the place of 'folderX' I should use a dynamic value, which comes from a query, like
<?php echo $row_rsQuery["item_name"];?>
How can it be done?
I'm not too familiar with php, and I will perhaps never learn it (..too old..), but I solve most of my problems with Dreamweaver, however the above problem is beyond its (and my) capabilities...
String concatenation (appending one string to another) is done via the . operator:
$files = scandir('images/'.$row_rsQuery["item_name"]);
$path = 'http://' . $_SERVER['SERVER_NAME'] . '/root/images/'.$row_rsQuery["item_name"].'/';
$files = scandir('images/'.$row_rsQuery["item_name"].'/');

Good method to do text with links in gettext?

I'm currently doing internationalization with gettext using PHP. I was wondering if there were any good methods for this example:
By using this website, you accept the Terms of Use.
For en_US, this sentence would follow such a format. However, in another language, the link "Terms of Use" could be at the beginning of the sentence. Is there an elegant way to do this? Thanks for your time.
For simple internationalization, I'll simply create an array per language, include the proper file, and access that array rather than do what you are doing.
en.php:
$text = array(
'footer' => 'By using this website, you accept the Terms of Use.',
'welcome' => 'Welcome to our website!'
);
index.php:
$langdir = '/path/to/languages';
$lang = ( $_GET['lang'] ) ? $langdir . '/' . $_GET['lang'] . '.php' : $langdir . '/en.php';
if( dirname($lang) != $langdir || !require_once( $lang ) )
exit('Language does not exist');
echo '<p class="footer">' . $text['footer'] . '</p>';
The dirname() call is critical; otherwise users get unvetted access to any php file on your filesystem.
Here's how I'd do it. The phrase to be translated would be
By using this website, you accept the <a>Terms of Use</a>.
Then I'd replace the link after the phrase is localised, e.g.
$str = _('By using this website, you accept the <a>Terms of Use</a>.');
$str = preg_replace('#<a>(.*?)</a>#', '$1', $str);
Of course you can replace <a> and </a> with whatever makes sense to you and your translators. Come to think of it, since you have to escape your output to prevent translators from messing up with your HTML (intentionally or not) I'd probably go with something like
$str = htmlspecialchars(_('By using this website, you accept the [tos_link]Terms of Use[/tos_link].'));
$str = preg_replace('#\\[tos_link\\](.*?)\\[/tos_link\\]#', '$1', $str);

Categories