htaccess url rewrite but the ID changes - .htaccess

I wondering if it is possible to rewrite a url that might look something like this
www.example.com/item.php?id=1 to a www.example/item.php without the `?id=1`
Please note that 1 is for the product id so it might change to 2 or any number depending on what product the user choose
My current htaccess
My current .htaccess looks like this:
RewriteEngine on
RewriteBase /
RewriteRule ^item/(.*)$ test/main/pages/account/$1 [L] // **the item.php file is in the item folder**
ErrorDocument 404 /test/main/pages/general/index.php
Options -Indexes
AuthName "main"
I did it like
<?php
include('global.php'); ///database connection
function create_guid()
{
$microTime = microtime();
list($a_dec, $a_sec) = explode(" ", $microTime);
$dec_hex = dechex($a_dec* 1000000);
$sec_hex = dechex($a_sec);
ensure_length($dec_hex, 5);
ensure_length($sec_hex, 6);
$guid = "";
$guid .= $dec_hex;
$guid .= create_guid_section(3);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= $sec_hex;
$guid .= create_guid_section(6);
return $guid;
}
$stmt = $conn->prepare("INSERT INTO `Product (`pid`, `Guid`, `price`) VALUES
(13, '".$guid."', 13)");
$stmt->execute();
?>
also i did it using PDO because am I not a big fan of mysql

Since your main motive here to keep people form guessing the id in url and since as pointed out by lucas william that the way you want it is not possible in .htaccess instead you can store the id of each product in the database as guid format(this format of id storage into database is used by sugarCRM) which is also a proper substitute to satisfy you required and you can use that id to uniquely identify you product table each records:
The functions to create guid is as follows:
function create_guid()
{
$microTime = microtime();
list($a_dec, $a_sec) = explode(" ", $microTime);
$dec_hex = dechex($a_dec* 1000000);
$sec_hex = dechex($a_sec);
ensure_length($dec_hex, 5);
ensure_length($sec_hex, 6);
$guid = "";
$guid .= $dec_hex;
$guid .= create_guid_section(3);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= $sec_hex;
$guid .= create_guid_section(6);
return $guid;
}
function create_guid_section($characters)
{
$return = "";
for($i=0; $i<$characters; $i++)
{
$return .= dechex(mt_rand(0,15));
}
return $return;
}
function ensure_length(&$string, $length)
{
$strlen = strlen($string);
if($strlen < $length)
{
$string = str_pad($string,$length,"0");
}
else if($strlen > $length)
{
$string = substr($string, 0, $length);
}
}
Now using the above function you can generate the id as:
$guid = create_guid(); //guid is of the format 79cb3604-e634-a142-d9cb-5113745b31e2 which you can see is quite impossible to guess.
Also I would sugest that you keep the auto increment field in your product table.
Because it always a good idea to maintain a auto incremented field in a table to uniquely identity the records.
I hope this can be of some help
Edit :
what you need to do is add a field in you database product table named "guid"
so say your current database product table structure has the following fields:
id, name, price //where id is the auto incremented
after adding the field guid it becomes
id, guid, name, price //where id is auto incremented field and guid uniquely identifies each row in the product table
and when you do the insert of the product data in the database product table you generate the guid using the above code and insert it. ie
for example
$sql = "Insert into product_table('guid','product_name',product_price) values('".$guid."','product1','59.00');
so an example data in your product table will look like this:
1, 79cb3604-e634-a142-d9cb-5113745b31e2, product1, 59.00
Now in the product.php page with url say
yoursite.com/product.php?guid=79cb3604-e634-a142-d9cb-5113745b31e2
instead of using the url
yoursite.com/product.php?id=1
you can easily query the data from the database product table in relation to "guid" which of course also uniquely identifies each row in your product table in the database there by elimiting the risk of user guessing your id in url of the webpage.
I hope this gives you an idea of what i am trying to explain.

Using .htaccess, rewrite "www.example.com/item.php?id=1" to "www.example/item.php" is not possible because, how can we know, with an url like "www.example/item.php", if the product id is 1 or 2 ? It's impossible. So, with .htaccess, it's not possible.
However, you can cheat and use, simply, PHP and session variables, to do this rewriting, even if it's not a good solution. So, let your links under their current shape, with the get id parameter, and just add in your item.php file, a condition that will save the id value in a session variable and redirect to item.php if the id parameter is not empty.

Related

Importing images along with other fields (username,subjectname) from excel in laravel

I am using phpspreadsheet. I want to import an excel sheet that have images too, it looks something like this,
I am able to retrieve fields separately and images separately, I want to get them together. Problem I am facing is that Images are being accessed with
$spreadsheet->getActiveSheet()->getDrawingCollection()
and for others field i have to access them like this
$spreadsheet->getRowIterator()
as both of them requires separate loops, should i be merging them into one or what is the right way so that i am able to retrieve both(images and fields) together.
Images retrieve code:
$spreadsheet = IOFactory::load($request->import_file);
$i = 0;
foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $key => $drawing) {
if ($drawing instanceof MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
case MemoryDrawing::MIMETYPE_PNG :
$extension = 'png';
break;
case MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif';
break;
case MemoryDrawing::MIMETYPE_JPEG :
$extension = 'jpg';
break;
}
} else {
$zipReader = fopen($drawing->getPath(), 'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader, 1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
}
$myFileName = time() .++$i. '.' . $extension;
$imagesCollection['answerImages_'.$key] =$myFileName;
file_put_contents('images/products/' . $myFileName, $imageContents);
$a = Answers::create([
'answerImages'=>$myFileName,
'questionId'=>($key <=4)?1:2,
]);
}
I want to store them into my table in database such that in questionImage column of database it has image name like this
and it is storing it currently but as I mentioned earlier i have to store them separtely
This is how i am storing other fields
$spreadsheet = IOFactory::load($the_file->getRealPath());
$sheet = $spreadsheet->getActiveSheet();
$row_limit = $sheet->getHighestDataRow();
$column_limit = $sheet->getHighestDataColumn();
$row_range = range( 1, $row_limit );
$column_range = range( 'F', $column_limit );
$startcount = 2;
$data = array();
foreach ( $row_range as $row ) {
$data[] = [
'courseName' =>$sheet->getCell( 'A' . $row )->getValue(),
'subjectName' => $sheet->getCell( 'B' . $row )->getValue(),
'question' => $sheet->getCell( 'C' . $row )->getValue(),
'questionImage' => $sheet->getCell( 'D' . $row )->getValue(),
];
$startcount++;
}
DB::table('questions')->insert($data);
How to get them together so that i can store them in one table
you should try maatwebsite/excel package. it will save your time.

How to allow text after a url

Im having trouble with my XAMPP website. I want to make a sort of profile like thing where users type (for example) https://howcoolitis.net/profile/useridhere
but that ends up just giving an error.
To be sincere, for the i have tried thing, There is not anything that i have tried apart from google searching similar like items, I don't really know what it is called to be honest, since i have never used it before but I want to use it.
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')
$url = "https";
else
$url = "http";
// Here append the common URL characters.
$url .= "://";
// Append the host(domain name, ip) to the URL.
$url .= $_SERVER['HTTP_HOST'];
// Append the requested resource location to the URL
$url .= $_SERVER['REQUEST_URI'];
// Print the link
$pos = strrpos($url, '/');
$search = $pos === false ? $url : substr($url, $pos + 1);
I was expecting for it to just give me the text after the url but it just gives a 404.

Yesod, howto generate type-safe link from JSON-data in Javascript / Julius

I've a route
/notes/#NoteId NoteR GET
From another page, I want to link to it.
When using "classic" hamlet, it's easy:
<a href=#{NoteR $ entityKey note}>notetitle
I want my page to be more dynamic and get JSON-data which contains the note-information plus note-id. How do I generate correct and typesafe-links?
I've already this code in a .julius file, but it fails to compile because it expects a "NoteId". I should insert obj.id somewhere in the URL interpolation #{..}... Any clues how to do that?
function loadnotes() {
var list = $("#results");
jQuery.getJSON("#{NotesR}",
function(o){
$.each(o, function (i, obj) {
$('<a href=#{NoteR}/>' + obj.title + '</a>').appendTo(list);
})});
}
window.onload = loadnotes;
EDIT:
I have this in Model.hs:
instance ToJSON (Entity Note) where
toJSON (Entity nid (Note title content created_at updated_at userId)) = object
[ "id" .= nid
, "title" .= title
, "content" .= (unTextarea content)
, "created_at" .= created_at
, "updated_at" .= updated_at
, "userId" .= userId ]
I would recommend having the NotesR route return the fully rendered URL instead of just the note ID.
Edit: I've added a cookbook entry to demonstrate this approach: https://github.com/yesodweb/yesod/wiki/Using-type-safe-urls-from-inside-javascript

Webforms in excel instead of e-mail

A client of mine asked me if i can find a solution for this problem.
His website (still a WIP) http://welkommagazine.nl/luuk/ has a form. The form obviously uses a sendmail script to send the form to e-mail. From thereon he manually copy/pastes all the submissions to excel.
What he wants is that the forms online automaticcaly are added to an excel document to save him a lot of work.
Now i am not a programmer, but a designer.. I think this can be done, but i have absolutely no clue how. I googled alot for it and the only thing i found was a dreamweaverplugin.
Is there a way to do this, if so, how?
Not a programmer's response, but...
I think an easy solution is to use Google docs. You can set-up a Google Spreadsheet and associate a form to it. Whenever a user fills the form , his data is added to the spreadsheet.
Your client may download that anytime.
There are some other providers on the market, some free, some not. E.g: wufoo.com
Found the answer myself. I wrote a PHP code snippet which actually stores the fields comma seperated in a CSV file and sends an email to a desired adress with the filled in fields.
if(isset($_POST['Submit'])){
$pakket = $_POST['pakket'];
$extragidsen = $_POST['extragidsen'];
$naambedrijf = $_POST['naambedrijf'];
$err = '';
if(trim($pakket)==''){
$err .= '-Please enter a name';
}
if(empty($extragidsen)){
$err .= '-Please enter an email address';
}
if(strlen($naambedrijf)==0){
$err .= '-Please enter a comment';
}
if($err!=''){
echo $err;
}
else{
$filename = 'file.csv';
$somecontent = $pakket . ',' . $extragidsen . ',' . $naambedrijf . "\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
//--------------------------Set these paramaters--------------------------
// Subject of email sent to you.
$subject = 'Inschrijving welkom';
// Your email address. This is where the form information will be sent.
$emailadd = 'luuk#luukratief.com';
// Where to redirect after form is processed.
$url = 'http://www.google.com';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
foreach ($_POST as $key => $value)
{
if ($req == '1')
{
if ($value == '')
{echo "$key is empty";die;}
}
$j = strlen($key);
if ($j >= 20)
{echo "Name of form element $key cannot be longer than 20 characters";die;}
$j = 20 - $j;
for ($i = 1; $i ';
fclose($handle);
} else {
echo "The file $filename is not writable";
}
}
}
Maybe the code aint that clean as it can be, but eh it works.
Feel free to clean up the code if you want to :)
I guessed I would answer this myself for the community...
BTW u need to set "write" rights to "file.csv"
cheers

Drupal views: List of authors of nodes where node.type=abc and node.vocabulary_id=123

In drupal6 using views I want a (block) list of authors (with complete profile fields) of some specific node type AND taxonomy term.id OR vocabulary.id
Summarized query:
Views: type user
Argument: Term ID/Vocabulary ID
Filters: Author of Node type abc
Fields: All Profile/Content Profile Fields
How can I achieve such solution?
I have the same issue. I found that if I filtered by node.type = 'blog' and set fields for the profile fields I was interested in, I could get a list or authors, but there would be duplicates. Setting 'Distinct' to Yes didn't help because it was selecting out distinct nodes, not distinct users.
So I ended up creating a custom block to show this information with some code like this:
<?php
$block['subject'] = t('Bloggers');
// Get a list of blog authors
$result = db_query('SELECT DISTINCT u.uid, u.name FROM {node} n INNER JOIN {users} u ON n.uid = u.uid WHERE n.type = \'blog\'');
$links = array();
while ($blogger = db_fetch_object($result)) {
$link = array();
if (module_exists('profile')) {
profile_load_profile($blogger);
}
if (!empty($blogger->profile_first_name) || !empty($blogger->profile_last_name)) {
$link['title'] = $blogger->profile_first_name . (empty($blogger->profile_first_name) ? '' : ' ') . $blogger->profile_last_name;
}
else {
$link['title'] = $blogger->name;
}
$link['href'] = 'blog/' . $blogger->uid;
$links[] = $link;
}
$block['content'] = theme('links', $links, array('class' => 'flat-links'));
?>
Hope that helps.

Resources