Rewrite url with id and title (php) - php

How to rewrite url (what to do) so that instead:
http://www.example.com/article.php?id=123
it says:
http://www.example.com/articles/123/article_title_read_from_database
using php and mysql
Thanks.

When the example article.php well page is accessed with the GET of id=123, the php code to retrieve the number is
$my_id = $_GET['id']
, in this case, that would produce 123.
Then you can redirect the page using
header('Location: http://example.com/articles/$id/other stuff');
I'll leave the MySQL stuff for someone else, but a simple tutorial will give you alot of info on that.

To process request and redirect to new url:
// get id of record from URL
$id = (int) $_GET['id'];
// suppose connection to database is established already
$result = mysql_query("SELECT `title` FROM `articles` WHERE `id` = $id");
if (!$result) {
// there is no such an article
// you can redirect to some other page, or show some error message
} else {
$row = mysql_fetch_assoc($result);
$title = $row['title'];
$urlPart = generateURL($title);
header('location:/articles/$id/$urlPart');
exit;
}
you'll need generateURL function, that take string input and replace all unusable characters with _. (For example if you have title "What's going on?" it will replace ', ? and whitespaces to something like "what_s_going_on"). You can use str_replace or preg_replace to achieve this.
If you want to generate new URL on multiple places, you can insert URL form of title directly into database as another column title_url and then just select it and use it instead of title:
SELECT `title_url` FROM `articles` WHERE `id` = $id
There is no way you can do this kind of rewriting in .htaccess as you can't connect to database server from within this file. (Or at least I don't know such a solution)

Related

$_GET['id'] returning null when passing URL with id

I am new to PHP and XAMPP mySQL.
I am going through this tutorial and I am trying to return a specific row in my DB based on the primary key - id.
However my $GET call appears to be returning null, and the else command is called returning all rows.
This is my DB, the table is named 'students':
This is my GET call:
//Check connection
if ($conn -> connect_error){
die("Connection failed: " .$conn->connect_error);
}
if ($_SERVER['REQUEST_METHOD'] === 'GET'){
if (isset($_GET['id'])){
//if id not null, id used to fetch single row
$id = $conn->real_escape_string($_GET['id']);
$sql = $conn->query("SELECT * FROM students WHERE id = '$id'");
$data = $sql->fetch_assoc();
}else{
//else fetch all rows
$data = array();
$sql = $conn->query("SELECT * FROM students");
while($d = $sql->fetch_assoc()){
$data[] = $d;
}
}
// Retunr json data
exit(json_encode($data));
}
I am testing the $GET command in postman, the URL points to my php CRUD API in the htdocs directory of XAMMP, with the table (students) and index specified:
http://localhost/crud_api/api/students/1.
The query will a 200-OK response and return all rows in keeping with the else statement.
So my question is why is $GET['id] returning null?
Preamble:
GET (query params) are normally specified like this:
https://example.com/?paramA=1&paramB=2&...paramN=X
As #ProfessorAbronsius correctly notes in a comment, even if the "public facing" URL of a resource does not specify such parameters, these can be specified/mapped on server level, for example by using Apache's RewriteRule directive. (And this is exactly the case in the tutorial linked by the OP.)
The problem in this specific case seems to be that the URL used by the OP is different from the one used in the tutorial:
http://localhost/crud_api/api/app.php/students/1 versus http://localhost/crud_api/api/students/1.
Please see how the tutorial defines the rewrite rules and what the URL looks like when tested in Postman:

What PHP do I need to insert into this mysqli_fetch_array to ensure NULL urls aren't used?

I have a webpage which uses php to pull through data from a MySQL database. The database stores my writing portfolio organised by columns date, url, category, title, publication, description. It pulls through the title and publication and uses the url to turn it into a hyperlink (see code below). So far, so good.
Where I'm stuck: Sometimes there's no url for something I've published (e.g. for a few of the 'Content & Copywriting' items on my site), but it still turns my title and publication into a link: a link to "_blank". When there is a NULL url, I need it to not turn my title into a link at all.
So, I think I need to insert some sort of logic so that if url=NULL, then it doesn't make the text into a link, instead of creating a link to "_blank". But this is completely beyond my capabilities right now - I don't know where to even start !
I hope that all makes sense. Any guidance/pointers in the right direction welcome! And please let me know if anything's not clear.
<?php
$query = mysqli_query($dbconnect, "SELECT * FROM main WHERE category = 'Content & copywriting' ORDER BY date DESC")
or die (mysqli_error($dbconnect));
while ($row = mysqli_fetch_array($query)) {
echo "<a href=$row[url] target='_blank'>$row[publication] - $row[title]</a><br>";
echo "$row[description]<br><br>";
}
?>
try check for empty values
while ($row = mysqli_fetch_array($query)) {
if( !empty( $row['url'])){
echo "<a href=$row[url] target='_blank'>$row[publication] - $row[title]</a><br>";
}
echo "$row[description]<br><br>";
}

Get certain part of url and use a WHERE clause

How do I get a certain part of the url?
Example: bithumor.co/posts/12345
How do I get the "12345" part so it can be put in the WHERE clause of the mysql(i) query and SELECT the post from the database where id = 12345 (when on the webpage: bithumor.co/posts/12345)
Example:
SELECT post_ id FROM post WHERE id = ["12345" part of url]
I already have bithumor.co/posts?id=12345 sorta thing
Firstly you could use a rewrite in your htaccess to form a get request to your PHP script then just access the id as you would any GET parameter.
RewriteRule ^posts/([0-9]+)$ posts.php?id=$1 [NC,L]
Or if you want to do it from pure PHP that is a choice too.
$tokens = explode("/", $_SERVER[REQUEST_URI]);
$number = $tokens[count($tokens) - 1];
$query = 'SELECT post_ id FROM post WHERE id = "' . $number . '"';

Loading a record with the primary key in the url?

is it possible to use GET or something like this to load a record into a form ?.
E.g I have for formA where it has a foreach list of all the clients in the DB , at the end of each row I have a link which is called 'edit' , this link goes to formB.php and is set out like this >>
sitename.com/FormB.php?token=<?php echo $ID ?>
This gives you an url that looks like the following :
http://www.sitename.com/formB.php?token=25
The link above would for example load the record with ID 25 into the second form.
I am not sure how to handle the link in the second form though, can you echo GET ID in the second form, or would it have to be GET token ?.
In PHP, there's the predefined $_GET variable. This is basically an array holding all GET paremeters:
// url = index.php?foo=bar&hello=world
echo $_GET['foo']; // bar
echo $_GET['hello']; // world
So, considering your url and query:
$query = 'SELECT * FROM `table` WHERE `token`=' . $_GET['token'];
To avoid security exploits, we need to use the function mysql_real_escape_string around the user-defined parameter when using strings. When using other types such as numbers you can just parse it to a number.
// if token is a number
$query = 'SELECT * FROM `table` WHERE `token`=' . intval($_GET['token']);
// if token is a string
$query = 'SELECT * FROM `table` WHERE `token`=' . mysql_real_escape_string($_GET['token']);
You can access your GET-Parameter with the $_GET-array. To see whats in there you can use:
print_r($_GET);
In the second case you would have to use $_GET['token'] as the parameter is named token.
Note: If you are passing the parameter into a SQL-Query make sure it is secured. In this case with intval(). SQL-Injections are bad.

How to get url ID in PHP? (for mysql_query UPDATE)

I want to add an edit button for a script called spiral url, but the problem is that I can't get the URL id. This is what I've tried:
/** get url id **/
$id = isset($_GET['id']) ? $_GET['id'] : '';
#mysql_query("UPDATE short_urls SET long_url = 'test' WHERE url_id = '".$id."' LIMIT 1");
What am I doing wrong?
Also I emailed the author and his response:
"I recommend you post on Stackoverflow - https://stackoverflow.com/.
I would love to help you but I don't see what you are doing wrong. I'm still learning PHP as well."
You're wide open to SQL injection attacks.
You're supressing errors with the # operator. NEVER suppress errors
You're not checking the return value of mysql_query(), which returns a boolean FALSE on failure.
Scrap that code and use this:
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$sql = "UPDATE short_urls SET long_url = 'test' WHERE url_id=$id LIMIT 1";
$result = mysql_query($sql);
if ($result === FALSE) {
die("Mysql error: " . mysql_error() . $sql);
}
Note that I'm assuming that the id parameter is numeric. If it's not, then remove the intval() stuff.
Make sure the value of $_GET['id'] actually has a value. Your URL will look something like http://myurl.com/index.phtml?id=yourvalue. You can do this by doing a:
print "id=".$_GET['id'];
Also, whenever doing a query, please be sure to escape any and all variables that can be manipulated by the user. Without doing this, you're opening yourself up to SQL injection attacks.
mysql_real_escape_string - http://php.net/manual/en/function.mysql-real-escape-string.php
#mysql_query("UPDATE short_urls SET long_url = 'test' WHERE url_id = '".mysql_real_escape_string($id)."' LIMIT 1");
If the url is like this: domain.com/something.php?id=65
$_GET['id'] should be equal to 65
if there is no id there then when you try to access $_GET['id'] you will get an error.
Also try removing the # symbol (that suppresses PHP warning).
And you are waaaay open to bobby-tables
Also (side note), get a new developer who knows what they are doing ;-)
Have you checked the url
http://www.somewebsite.com?id=56&other_car=test
specifically for the "?" after the end of the url and also check all the parts are broken up by the ampersand.
failing that you can view all of your available get array variables by
print_r($_GET);

Categories