URL availability from MySQL Database using Php [duplicate] - php

This question already has answers here:
How do I apply URL normalization rules in PHP?
(1 answer)
Extract hostname name from string
(29 answers)
Closed 8 years ago.
I am trying to create a registration system that allows users to submit their website URLs. Now when a user enters a URL, it checks against the database to see if it already exists, and rejects it if it does.
However, my problem is because of this :
If http://www.example.com is in the database and I enter http://example.com, this counts as a different URL as far as the check is concerned, and it allows the submission.
Is there a proper way to handle this, apart from retrieving all records, removing the www if present, and then comparing? (Which is a terribly inefficient way to do so!)
Note : Adding Laravel tag in case it has any helper functions for this (I am using a laravel-4 installation).
EDIT : This is my current logic for the check :
$exists_url = DB::table("user_urls")
->where('site_url', 'like', $siteurl)
->get();
if($exists_url)
{
return Redirect::to('submiturl')->withErrors('Site already exists!');
}
EDIT 2 : One way is to take the given URL http://www.example.com, and then search the database for http://www.example.com, www.example.com, http://example.com and example.com. However I'm trying to find a more efficient way to do this!

I think before you implement a solution you should abstractly flesh out your policy more thoroughly. There are many parts of a URL which may or may not be equivalent. Do you want to treat protocols as equivalent? https://foo.com vs http://foo.com. Some subdomains might be aliases, some might not. http://www.foo.com vs http://foo.com, or http://site1.foo.com vs http://foo.com. What about the path of the the URL? http://foo.com vs http://foo.com/index.php. I wouldn't waste your time writing a comparison function until you've completely thought through your policy. Good luck!
UPDATE:
Something like this perhaps:
$ignore_subdomains = array('www','web','site');
$domain_parts = explode('.',$siteurl);
$subdomain = strtolower(array_shift($domain_parts));
$siteurl = (in_array($subdomain,$ignore_subdomains)) ? implode('.',$domain_parts) : $siteurl;
//now run your DB comparison query

You can check before sending data to database using PHP. Following is a small example. Obviously you can make it more advanced as per your liking.
<?php
$test = "http://www.google.com";
$testa = "http://google.com";
if (str_replace("www.","",str_replace("http://","",$testa)) == str_replace("www.","",str_replace("http://","",$test))) {
echo "same";
}
else {
echo "different";
}
?>
Following is MySQL Replace example. In this example 'url' is database field.
SELECT * FROM `urls` WHERE REPLACE(url, "http://www","") = "google.com" OR REPLACE(url,"http://","") = "google.com"
Once again this is very basic just for your better understanding.
In case you need any further assistance kindly do let me know

Related

How can I make something on the page change when the url contains #something

I've made it so when you click on a certain link it changes the url to mywebsite.com/page.php#certainusername
How can I make it so when the url contains someone's certain username, an object containing
data="http://www.twitch.tv/widgets/live_embed_player.swf?channel=certainusername"
will change certain username to the username in #?
Check out the parse_url function. You should be able to get the fragment (hashmark thing) from that.
Not sure what kind of change you are talking about... So here are 3 different types of methods to access the "#certainusername"
CSS
:target {
background: yellow;
}
(Source)
PHP
parse_url($url, PHP_URL_FRAGMENT)
// or
parse_url($url)['fragment']
// then do stuff ...
(Source)
JavaScript
window.location.hash
(Source)
For the question, I assume that you're not working with any framework. Given this, I'll give you a simple answer.
Steps:
1 - Get the username out of the URL.
2 - Generate the view dynamically.
Explanation:
1 - I would recommend using a query string of the following format: mywebsite.com/page.php?username=certainusername (instead of using a #)
Then you can use $_GET to obtain the username (Please, read more about the security implications: http://php.net/manual/en/reserved.variables.get.php).
2 - If you're using PHP to generate the HTML code directly, the only thing that you need to do is:
... HTML in here ...
data="http://www.twitch.tv/widgets/live_embed_player.swf?channel=<?php echo $username; ?>"
... more HTML ...
(Assuming that the variable $username contains the username obtained from the URL).
This is a very simple scenario and there are a lot of other things to consider that are out of the scope of the question.

query string in php url which fetches values from files in directories

for security reasons we need to disable a php/mysql for a non-profit site as it has a lot of vulnerabilities. It's a small site so we want to just rebuild the site without database and bypass the vulnerability of an admin page.
The website just needs to stay alive and remain dormant. We do not need to keep updating the site in future so we're looking for a static-ish design.
Our current URL structure is such that it has query strings in the url which fetches values from the database.
e.g. artist.php?id=2
I'm looking for a easy and quick way change artist.php so instead of fetching values from a database it would just include data from a flat html file so.
artist.php?id=1 = fetch data from /artist/1.html
artist.php?id=2 = fetch data from /artist/2.html
artist.php?id=3 = fetch data from /artist/3.html
artist.php?id=4 = fetch data from /artist/4.html
artist.php?id=5 = fetch data from /artist/5.html
The reason for doing it this way is that we need to preserve the URL structure for SEO purposes. So I do not want to use the html files for the public.
What basic php code would I need to achieve this?
To do it exactly as you ask would be like this:
$id = intval($_GET['id']);
$page = file_get_contents("/artist/$id.html");
In case $id === 0 there was something else besides numbers in the query parameter. You could also have the artist information in an array:
// datafile.php
return array(
1 => "Artist 1 is this and that",
2 => "Artist 2..."
)
And then in your artist.php
$data = include('datafile.php');
if (array_key_exists($_GET['id'], $data)) {
$page = $data[$_GET['id']];
} else {
// 404
}
HTML isn't your best option, but its cousin is THE BEST for static data files.
Let me introduce you to XML! (documentation to PHP parser)
XML is similar to HTML as structure, but it's made to store data rather than webpages.
If instead your html pages are already completed and you just need to serve them, you can use the url rewriting from your webserver (if you're using Apache, see mod_rewrite)
At last, a pure PHP solution (which I don't recommend)
<?php
//protect from displaying unwanted webpages or other vulnerabilities:
//we NEVER trust user input, and we NEVER use it directly without checking it up.
$valid_ids = array(1,2,3,4,5 /*etc*/);
if(in_array($_REQUEST['id'])){
$id = $_REQUEST['id'];
} else {
echo "missing artist!"; die;
}
//read the html file
$html_page = file_get_contents("/artist/$id.html");
//display the html file
echo $html_page;

pass a value from one page to another outside querystring and without javascript?

One solution to automatically building navigation for a site is by scanning a folder for documents like this:
foreach(glob('pages/*.pg.php') as $_SITE_NAV_filePath):
$_SITE_NAV_filePath = explode('.pg',pathinfo($_SITE_NAV_filePath,PATHINFO_FILENAME));
$_SITE_NAV_fileName = $_SITE_NAV_filePath[0];
$_SITE_NAV_qv = preg_replace('/([A-Z])/','-$1',$_SITE_NAV_fileName); $_SITE_NAV_qv = trim($_SITE_NAV_qv,'-');
$_SITE_NAV_name = preg_replace('/([A-Z])/',' $1',$_SITE_NAV_fileName);
?>
<li><?=$_SITE_NAV_name?></li>
<?php
endforeach;
This code will turn "AnAwesomePage.pg.php" into a menu item like this :
<li>An Awesome Page</li>
This might be bad practice (?).
Anyway; I don't use this method very often since most of the time the sites have a database, and with that comes better solutions...
But my question is this:
Is there a way to prefix the filename with a integer followed by and underscore (3_AnAwesomePage.pg.php), for sorting order purposes, and pass it somehow to the destination page outside of the querystring and without any async javascript?
I could just explode the filename once again on "_" to get the sort order and store it somewhere, somehow?
This is the code for handeling the page query request:
$_SITE_PAGE['qv'] = $_GET['page'];
if (empty($_SITE_PAGE['qv'])){ $_SITE_PAGE['qv'] = explode('-','Home'); }
else { $_SITE_PAGE['qv'] = explode('-',$_GET['page']); }
$_SITE_PAGE['file'] = 'pages/'.implode($_SITE_PAGE['qv']).'.pg.php';
This code turns "An-Awesome-Page" back into "AnAwesomePage.pg.php" so it's possible to include it with php.
But with a prefix, it's not so easy.
The probliem is; Now there's no way to know what prefix number there was before since it has been stripped away from the query string. So I need to send it somehow along in the "background".
One very bad solution I came up with was to transform the navigation link into a form button and just _POST the prefix interger along with the form. At fist it sounded like a nice solution, but then I realized that once a user refreshes their page, it didn't look very good. And after all, that's not what forms are for either...
Any good solutions out there?
Or some other and better way for dealing with this?
There are two ways to keep that number saved, you can use cookies or php session variables.
But in this case, if user first enter the url in the browser or in a new browser, then he should be taken to default number.
Like you have:
1_first-page.php
2_first-page.php
3_first-page.php
If user enter the url like: domain.com/?page=first-page, you have to take him to 1_first-page.php to any number which you want to be default.

How to pick up the database name and table name from the URL in PHP?

I am new to PHP.
I need a help regarding the methods of extracting DB name and table name from the given URL name.
For example, let's say, I have an URL like the one below:
/test.php?db=...&table=.../
How to extract the DB name and table name from this URL using PHP and use the result for other query purposes.
If you mean how to parse an existing URL for it's parameters:
parse_url() and parse_str() will help you strip the components of the url. You will primarily be looking at the following
$elements = parse_url($url);
$kvps = $elements->query;
$db = parse_str($kvps['db']);
$table = parse_str($kvps['table']);
But, if you mean how to GET variables from the current page before render:
<?php
$dbname = $_GET['db'];
$tablename = $_GET['table'];
?>
And yea, there are major security risks involved in opening up 'direct' access to your database this way. Best to obfuscate / encapsulate / wrap your functions in tasks like index.php&addUser=tim instead of index.php&insert=tim&db=boofar&table=users&dbuser=root&dbpassword=secure.
If you're just learning, what you're doing is fine, as long as you realize why it's wrong. If you're coding for production, you really need an alternate solution.
There are two ways to pass variables or data to another page.
GET (via the URL)
and
POST (usually a form submission)
You can alway get via
$_GET
http://php.net/manual/en/reserved.variables.get.php
or
$_POST
http://nl.php.net/manual/en/reserved.variables.post.php

Shrink a URL in HTML

So, im making a file hosting site, and am using some form builders to start off with. However, these builders do NOT support PHP. Now, i would like to shrink some URLs, how can i do this in pure HTML, without adding in PHP methods. I am fine with goo[dot]gl, bit.ly, tinyurl.com, or whatever else!
HTML is a Markup Language.
If you want to use some API, or anything more coding-oriented, you have to use a real programming language - you choose : for your purpose PHP would be the best choice.
Now, if you finally decide to use PHP, it's really easy.
Code (for TinyURL) :
<?php
function createTinyUrl($strURL) {
$tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$strURL);
return $tinyurl;
}
?>
Usage :
<?php
$myTinyUrl = createTinyUrl("http://www.yourdomain.com/some-long-url-here");
?>
And that's all! ;-)
If the form builders don't support PHP you need to write it yourself. PHP is very easy to work with.
Here is an example for you. (Assuming you have PHP set up on your web host:)
Save the file with the extension .PHP (or whatever your web host uses - might be .PHP5 for php5) instead of .HTML
You can use the super-global $_GET to accept certain variables from the URL in the address bar ex.:
$short_url = $_GET["q"];
Since i'm getting a variable named 'q', if you access the page with a parameter named 'q' I will have that variable stored ex.:
http://your.site/?q=shorturl # Assumes your index file takes the 'q' variable
Now it is up to you what to do with that variable. The best thing would be to set up a MySQL database so that when you get a value like 'shorturl' you can do a quick SQL query to return the full address ex.:
# Make DB connection
$db = new PDO("mysql:host='X.X.X.X';dbname='mydb'", $user, $secret);
# Function to search database for URL
function getFullURL($short_url) {
$result;
$sql = "SELECT full_url FROM tbl_addresses WHERE short_url='?'";
$query = $db->prepare($sql);
$query->execute(array($short_url));
$rows = $query->rowCount();
if ($rows == 1)
$result = $query->fetchAll();
return $result;
}
There's really not much to it in PHP with MySQL.

Categories