Form Fix in php - php

I have a website form that collects url of users to store in a database. They should not enter the http:// with their URL however many and the result is that when their url is displayed it looks like this
http;//http://www.foo.com I need the form to strip it or ignore it or what ever you think is the best way to handle it.
thanks

Use this on the url given by the user:
$url=str_replace("http://","",$_POST['url']);
//Where $_POST['url'] is the users input
This function takes an argument and replaces all occurrences of that argument within a string. More on this function here.

You should do two things!
1 - Clean up your database and replace all http://http//example.org entries so that your database is fine with your convention (http://example.org, protocol is included in URL).
// Something like this ...
UPDATE table SET field = REPLACE(field, 'HTTP://HTTP://', 'HTTP://');
2 - After a user submitted his URL, you should check for the string "http://".
$url = trim('http://example.org');
if (0 !== strpos($url, 'http://')) {
$url .= 'http://' . $url;
}

Related

append to url in Laravel

I'm trying to implement a displayPerPage (10, 25, 50, etc.) when displaying a list of results on an index page. However i'm having a hard time how to just append that to the url without replacing the other query strings.
Example:
I have a paginator to switch pages however, if i'm on page 5 for example and select display per page 10 results on my select dropdown, it will load the results but erase the page=5 from the url. How to I just append displayPerPage without erasing where I currently am on the paginator.
Thanks for any help.
I know its possible to do it without creating a custom paginator since I have done it on another project with laravel 4, but that was a while back and I can't seem to figure out how to do it again.
Assuming $objects is the list of the item you're paginating, on your view you can add your paginator like that:
{{$objects->appends(request()->query())->links()}}
and query strings like your requestPerPage will be carried
After battling with this issue, I wrote a url parser helper function in php to to find and replace certain things in url after the ? sign (query part)
//for displayPerPage, orderBy and sortBy parse the url and replace with new values
function urlQueryParse($queryToReplace, $newValue){
// extract query from url
$fullUrl = Request::fullUrl();
if(strpos($fullUrl, '?') !== false){
//find everything after the ? in url
$url = substr($fullUrl, strpos($fullUrl, "?") + 1);
// check url to make sure $queryToReplace exists in the url
if(strpos($url, $queryToReplace) !== false) {
// look through the remaining url query and replace whats given to the function
$newUrL = preg_replace('/('. $queryToReplace. '\=)([^&]+)/', $queryToReplace.'='.$newValue, $url);
return Request::url()."?{$newUrL}";
}
// if the ? exists but the queryToReplace is not in the url, then add it to the query string
return Request::url()."?{$url}&{$queryToReplace}={$newValue}";
}
//if the url doesnt have ? sign then simply insert the new value
return Request::url()."?{$queryToReplace}={$newValue}";
}
Hopefully this helps someone. If you have any ides of how to improve it, I'm open to suggestions.
P.S. I'm working on Laravel 5.2

How would I set up behat to check to see if I am on a route with a dynamic number?

In behat I would like to check to see if the route I am going to is the correct route, the only issue is everytime I visit the route the number changes. How would I set up my behat to look for any number after wards and let it pass. So what I have is:
Then I should be on "/clinic/participant/create/{id}"
That bracket {id} will always be dynamic and if possible I would like to either ignore the last id or put a wildcard of some sort on it to say whatever is passed here works as long as its a number.
This is my work around, but I would still like to know if there is a easier way / cleaner way to do this.
public function iShouldBeOnRoute($url)
{
$urlArray = explode('/', $url);
$urlPath = $this->getSession()->getCurrentUrl();
$urlPathArray = explode('/', $urlPath);
$testedUrl = join('/', $urlArray) . end($urlPathArray);
$this->assertSession()->addressEquals($testedUrl);
}
Assuming that this URL is an existing link that you can actually see, then you could create a custom step that gets the href attribute and then visit that url.
For example:
I am on create participant page
this step should contain:
- find element -> get attribute href, save it in a variable
- use visit with that variable
The css selector used should be:
a[href*='/clinic/participant/create/']
If you have the id and you only need to check that the url contains that id you could just use a strpos !== false and throw exception or an assert.

Making user pages using PHP and MYSQL by getting user_name from URL: user/username

I am using PHP header redirect to redirect users from account/?id=$id to user/$username
Successfully it takes for instance account/?id=1 to user/samuel as long as the user exists. Now, this page user/samuel is quite empty ( 404 ).
How do I make it return the user data in the user/samuel using something like isset($_GET[]) manual? in addition of course to adding MYSQL query to retrieve data for the user which has username extracted from the URL, and get their data from database table. and I will be placing all the code in user/index.php
As long as I could make account/?id=$id get the $id from URL ( parameter ) and do other db stuff I think it is also possible to get $username from the URL.. even though user/?username could do it but I don't want to include an ? in the URL..
Any thoughts?
This is a pretty broad topic, what you need to do is parse the url - IE break it into parts and then match the url to a set of actions. This is commonly known as routing.
A naive implementation would be a:
$parts = explode($_SERVER['REQUEST_URI'], '/');
if ( $parts[-2] === 'user' && $parts[-1] ) {
$stmt = $pdo->prepare("SELECT * FROM 'users' WHERE username = ? OR id = ?");
$result = $stmt->execute(array($parts[-1], array($parts[-1]));
// ... do something if the user is found or not.
}
But this would fail if the url contains query parameters (?foo=bar) or a hash (#foo).
Instead you can use parse_url to make sure you only use the path.
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$parts = null;
// Match the url with a regular expression.
preg_match(/^\/user\/(\w*)$/, $path, $parts);
if ( count($parts) == 2 ) {
$stmt = $pdo->prepare("SELECT * FROM 'users' WHERE username = ? OR id = ?");
$result = $stmt->execute(array($parts[-1], array($parts[-1]));
// ... do something if the user is found or not.
}
But in the end you might want consider using a micro framework such as Silex, Slim or using the Routing component from Symfony2 so that you can concentrate on building your application rather than reinventing the wheel.
It might be better if you use Url Rewriting (aka friendly urls)
You can see this link which answers this same question, although your case is a little bit different.
Apache friendly urls
Since you can't convert $id to $username (both are different values) I would recommend to change the link to 'user/ID' instead of 'user/USERNAME'.

Issue with & in a string submitted with $_GET

I'm building an "away"-page for my website and when a user posted a link to another website, each visitor clicking that link will be redirected first to the away.php file with an info that I am not responsible for the content of the linked website.
The code in away.php to fetch the incoming browser URI is:
$goto = $_GET['to'];
So far it works, however there's a logical issue with dynamic URIs, in example:
www.mydomain.com/away.php?to=http://example.com
is working, but dynamic URIs like
www.mydomain.com/away.php?to=http://www.youtube.com/watch?feature=fvwp&v=j1p0_R8ZLB0
aren't working since there is a & included in the linked domain, which will cause ending the $_GET['to'] string to early.
The $goto variable contains only the part until the first &:
echo $_GET['to'];
===> "http://www.youtube.com/watch?feature=fvwp"
I understand why, but looking for a solution since I haven't found it yet on the internet.
Try using urlencode:
$link = urlencode("http://www.youtube.com/watch?feature=fvwp&v=j1p0_R8ZLB0") ;
echo $link;
The function will convert url special symbols into appropriate symbols that can carry data.
It will look like this and may be appended to a get parameter:
http%3A%2F%2Fwww.youtube.com%2Fwatch%3Ffeature%3Dfvwp%26v%3Dj1p0_R8ZLB0
To get special characters back (for example to output the link) there is a function urldecode.
Also function htmlentities may be useful.
You can test with this:
$link = urlencode("http://www.youtube.com/watch?feature=fvwp&v=j1p0_R8ZLB0") ;
$redirect = "{$_SERVER['PHP_SELF']}?to={$link}" ;
if (!isset($_GET['to'])){
header("Location: $redirect") ;
} else {
echo $_GET['to'];
}
EDIT:
Ok, I have got a solution for your particular situation.
This solution will work only if:
Parameter to will be last in the query string.
if (preg_match("/to=(.+)/", $redirect, $parts)){ //We got a parameter TO
echo $parts[1]; //Get everything after TO
}
So, $parts[1] will be your link.

PHP GET variables pass along while browsing

My site is organized into topics. Users can switch between topics on any page, at any time. I would like to be able to pass this topic along from page to page. I am guessing this should be done in a php post or get variable. I can grab the topic from the post or get variable and then run the rest of my site. However, this seems like it requires a form on every page to pass along this variable. As of now, the only way I have passed post or get variables was from forms on the previous page. I have never passed along these variables over several pages. Will I need a form on every page to pass these variables? Also, is this the standard way of doing this?
You should probably use GET, because it sounds like you're just trying to display different information, and POST is supposed to be for performing changes or actions.
If you decide to use GET variables, all you have to do is append them to the end of the link's href:
MORE BANANAS
the least overhead method of doing this would be to add some javascript that sets a cookie each time someone navigates to a new topic. This would assume you can select somehow all links that match topics (presumably trough classes)
A better method - because of compatibility,reliability and overhead - but not necessarily feasible, if a large number of links needs changing, is to use GET requests, as another poster suggested
You can create a helper function to generate your anchor tags and just append any existing query string to it, so instead of this:
Foobar
you would do this:
<?php echo anchor('page2.php','Foobar'); ?>
where your function would look like this:
/**
* Function creates an anchor tag and optionally
* appends an existing query string
* #param string $url
* #param string $txt
* #param bool $attach_qs Whether or not to follow a query string
*/
function anchor($url, $txt, $attach_qs = true)
{
$qs = '';
if ($attach_qs === true) {
$qs = (!empty($_SERVER['QUERY_STRING'])) ? '?' . $_SERVER['QUERY_STRING'] : '';
}
return '' . $txt . '';
}
Kolink's suggestion of placing the topic in via a PHP echo statement for every URL would certainly work. There is however, another option that I am surprised hasn't come up yet.
You could use PHPs Session Manager to store the variable. It is similar to using cookies; however, it is only temporary (limited to the session). Where a cookie can be persistent over multiple sessions.
<?php
// use this code before the page is generated, before the topic is decided.
session_start();
if (isset($_GET['topic']) && $_GET['topic'] != $_SESSION['topic']) {
// GET['topic'] is set, session variable does not match
// you may want to sanitize or limit what can be passed via ?topic=
$_SESSION['topic'] = $_GET['topic'];
} else if (isset($_SESSION['topic'])) {
// Session topic is not empty, run code to display appropriate content
} else {
// No topic is set, display default
}
?>
It's by no means the only solution, but it does give you an extra option.

Categories