I have a form input that its value was generated by server.
$getLastID = Model::select('id')->orderBy('id', 'desc')->first();
// echo $getLastID;
$get_id=substr($getLastID, -2);
// echo $no_urut;
$prefix = date('Ym');
$ordered_number = str_pad($get_id+1, 3,'0', STR_PAD_LEFT);
// $no_urut++;
$no_admin = $prefix.$ordered_number.'-01';
Which will generate 202006001-01 at first entry. Then, there is a problem. When the ID has reached 10++, it generate same value like first entry. It should be 202006010-01, 202006011-01 and so on.
My question is, how to generate value like that in PHP?
Related
I am building an installer script in my application. I am declaring some constants in one file for example
define(DB, '');
define(USER, '');
define(PASS, '');
define(HOST, '');
Now I want to access this DB variable first and update the value of DB and so on.
I have tried so far is this
define(DB, '%dbname');
define(USER, '%dbuser');
define(PASS, '%dbpass');
define(HOST, '%dbhost');
$file_path = "constant.php";
$dbname = $_POST['dbname'];
$value = "%dbname";
$replace_with = $value;
$content = file_get_contents($file_path);
$content_chunks = explode($string_to_replace, $content);
$content = implode($replace_with, $content_chunks);
file_put_contents($file_path, $content);
This script works fine. But the only issue is that once its update the value it can't update the value again. The value cannot be updated twice because the script was checking this value %dbname. Now since it has been changed to some value. I can't be able to update the value again. I want to do something like detect the variable DB then update the value in front of it.
I was just wondering if it is possible to remove a value from an external .txt file once it is randomly chosen.
// Opens file with key values
$randomkeys = file('keys.txt');
// Takes keys from file and puts it into an array
$random_keys = array_rand($randomkeys, 2);
// Outputs the random key chosen
echo "Your code is: ";
echo $randomkeys[$random_keys[0]];
This is the code I am currently using and it works by reading the file that includes all the keys and then it is put into an array that would later be shown to the user that is using the site.
What I want to add to this is that when the user views the site that the key shown to them will be removed from the list so no one else can get that same key.
Simply best solution is to use RDBMS.
But if You insist on solution with .txt file:
unset($randomkeys[$random_keys[0]]);
array_values($randomkeys);
file_put_contents('keys.txt', implode("\n", $randomkeys));
but keep in mind that in situation of asynchronous access it can keep the key that was used (because of parallel write) - so it's better to use DB.
Or just have another file: used_keys.txt and append used key to the bottom.
so solution:
$keys = file('keys.txt'); // reads keys file
$used_keys = file('used_keys.txt'); // reads used keys file
$keys = array_values(array_diff($keys, $used_keys)); // returns array of unused keys
$key = $keys[mt_rand(0, sizeof($keys)-1)]; // picks random key
// outputs random key
echo "Your code is: ";
echo $key;
// appends used random key to the end of used keys file
file_put_contents('used_keys.txt', $key, FILE_APPEND);
You could use file_get_contents to pull the data in the file, str_replace to remove the line and file_put_contents to put the data back. As suggested in this answer:
How to delete a line from the file with php?
Although this might not be the most efficient way of doing that, you could end up reading from and writing from the disk a lot depending on your application. Ideally you'd use a database like MySQL or SQLite.
Edit 9/25/2016
Here's a simple implementation of a database that might work for you. As of PHP 5.3 SQLite3 is enabled by default. This method generates a new code when you need instead of pre generating a list. Of course you could pre generate a list using this method as well if you wanted to.
PHP Docs:
http://php.net/manual/en/book.sqlite3.php
You only need a few concepts to get going:
SQLite3::open [Create or Open a database file]
SQLite3::query [For Selects]
SQLite3::querySingle [For Selects]
SQLite3::exec [For Insert, create, delete, update]
Note: My method for generating the "Code" is not cryptographically secure. If security is a big concern See: PHP: How to generate a random, unique, alphanumeric string?
Setup.php
Run this file once to create your database, you can delete it after if you like
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mysqlitedb.db');
}
}
$db = new MyDB();
$db->exec('CREATE TABLE codes (code_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,code varchar(50) NOT NULL)');
$db->close();
CodeManager.php
Include this file anywhere you want to generate or delete a code
<?php
class CodeManager extends SQLite3
{
function __construct()
{
// You can change this to the file location of the code list.
$this->open('mysqlitedb.db');
}
function getRandomCode()
{
do {
// If users have a unique identifier, you can use it instead of rand()
// This should guarrantee a unique value that doesn't have to be checked first.
// You can also replace md5(...) with any method you prefer to generate the code
$code = md5(uniqid(rand(), true));
$code_check = $this->querySingle('SELECT code FROM codes WHERE code="'.$code.'"');
} while(!is_null($code_check)); // Need this loop as long as we are using rand()
// Try to add the code to the list of used codes
if($this->exec('INSERT INTO codes (code) VALUES ("'.$code.'")'))
return $code;
return false;
}
function deleteCode($to_delete)
{
// Try to delete the record
if($this->exec('DELETE FROM codes WHERE code="'.$to_delete.'"'))
return true;
// If we couldn't delete the record
return false;
}
function getAllCodes()
{
$all_codes = array();
$results = $this->query("SELECT * FROM codes");
while ($row = $results->fetchArray()) {
$all_codes[] = $row['code'];
}
return $all_codes;
}
}
App.php
Example of how to use CodeManager.php
<?php
include('CodeManager.php');
$cm = new CodeManager();
// Get a single new code
$new_code = $cm->getRandomCode();
echo $new_code."\r\n";
// Get a list of all codes generated so far
$all = $cm->getAllCodes();
// Display them one by one
foreach($all as $single){
echo $single . "\r\n";
}
?>
I have two variables:
$getSkill = $_GET['skill'];
$avg = avg;
I have an 'averages.php' file included that has all of the necessary averages preloaded but this current PHP file is defined by $_GET['skill'], each average in there is loaded as $skillnameAvg and I am trying to echo the relevant $skillnameAvg to each dynamic page correctly.
I've tried $getSkillAvg = $.$getSkill.$avg; and a few others and I can't seem to find a solution.
This can be done using Variables variables in PHP
$getSkill = $_GET['skill'];
$avg = $getSkill . 'avg';
echo $$avg;
Example
$chippyavg = '20%'; // create a testing value eg your included file
$getSkill = 'chippy'
$avg = $getSkill . 'avg';
echo $$avg;
Result
20%
This is not a big deal, but for you I can share some information. First of all you need to concatenate two variable $_GET['skill'] and $avg, and make them also another variable by using a $sign prefix of the resultant value.
Now use echo $getSkillAvg = ${$getSkill.$avg};, what it shows? If you don't define the variable that is generated here then E_NOTICE : type 8 -- Undefined variable: skillavg -- at line 8. Or if defined then the value will be display.
Now what you are trying to do make that value a variable, so do that you need to use another $ sign before the resultant value. Then the result says undefined variable, so you need to make that variable as string to show as output as i do in below code.
$skillavg = 'Smith'; //assignment for work
$_GET['skill'] = 'skill';//assignment for work
$getSkill = $_GET['skill'];
$avg = "avg";
echo $getSkillAvg = "$${$getSkill.$avg}"; //$Smith
I was trying to do one X + X that I got the data from twice different "file get contents" I read that I need to convert it to an "int value" but still not working.
Heres the code
$users1 = file_get_contents('firstone/usersOnline');
$users1 = file_get_contents('secondone/usersOnline');
$total = intval($users1 + $users1);
You are using same variable name for both values it will overwrite the value . you need to use other name for second value.
$users1 = file_get_contents('firstone/usersOnline');
$users2 = file_get_contents('secondone/usersOnline');
$total = intval($users1 + $users2);
I have a number of url's with different query strings such as
view.php?id=5
view.php?id=6
view.php?id=7
on another php page Im using file_get_contents as below:
$page = file_get_contents('view.php?id=5');
$file = 'temp/form.html';
file_put_contents($page, $file);
This of course only writes the first id '5', so how can i retrieve the 'id' variable on this page and write it in my file_get_contents line so I dont have to write out all the id's in seperate lines
thanks
rifki
If I understand correctly, in the situation you demonstrate you could use a for loop or something like that. But that only works if the IDs are numeric and follow each other up.
Example:
for($i = 5; $i <=7; $i++) {
$page = file_get_contents('view.php?id='.$i);
$file = 'temp/form.html';
file_put_contents($page, $file);
}
Updated:
If your ID comes from database you could select all IDs and loop through that.
Eg.
$sql = 'SELECT id FROM tablename;';
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
$page = file_get_contents('view.php?id='.$row['id']);
$file = 'temp/form.html';
file_put_contents($page, $file);
}
If those urls are used to browse some pages you can use the $_GET array (Official PHP Manual for the $_GET method).
It simply gets the value of a variable passed via the get method (i.e. page.php?var1=1&var2=2) so, if you need to get the id value for your page the code should be something like this:
$id = $_GET['id'];
$request = 'view.php?id='.$id;
$page = file_get_contents($request);
$file = 'temp/form.html';
file_put_contents($page, $file);
The first line gets the id passed via url, then the second creates the request string to pass to your file_get_contents function, then the other are like your code.
This is the case if you request the data from inside of such pages, if, for example, you know all of the pages needed then you can use a for clause to solve this problem.
One of the solutions might be:
$first_page = 5;
$last_page = 7;
for ($i = $first_page; $i <= $last_page; $i++) {
$request = 'view.php?id='.$i;
$page = file_get_contents($request);
$file = 'temp/form.html';
file_put_contents($page, $file);
}
With this you simply set the first and the last page you want to request, then you use these values to cycle through the pages and then call your function to do your... "stuff" :D
This is a good approach because then you can set in runtime the values for the for statement so you won't have to change that file every time.
However I think that using an identification different from Integers for your pages would be better, like id=home, or something like that.
If you get the id in your query string I mean url, you should write something like this:
$page = file_get_contents('view.php?id='.$_GET['id']);
$file = 'temp/form_'.$_GET['id'].'.html';
file_put_contents($page, $file);
To retrive the variable from a query string use
$_GET['variable_name']
By default, whenever you make a request to the server it is GET method which is called unless you explicitly specify that the form method to be POST.
//variable_name is the name of the variable in the query string