using a url, my idea is that any user can post data. For example via
http://myweb.com/index.php?name=Peter&surname=Brown
Using the "jedwards" answer, present here, I am able to create a json and save it to a file.
<?
/* This needs to be at the top of your file, without ANYTHING above it */
session_start();
/* ... */
if(!array_key_exists('entries', $_SESSION))
{
$_SESSION['entries'] = array();
}
$_SESSION['entries'][] = array("name" => $_GET["name"], "surname" => $_GET["surname"]);
$json_string = json_encode($_SESSION['entries']);
My problem is that this is not permanent amongst different session or user. It works only on the same session. On different session the json built start from the beginning.
First of all, don't use GET requests to change the state of the server. GET is only supposed to read (or.. um.. GET) data from the server.
In order to change data, use POST. It's more fitted, slightly more secure, and is great when transferring larger amounts of data.
Now, for the problem at hand. For a more permenant solution, the best option is to enforce user registration, and save the required data on a database, with a reference to the user's ID.
Yes because sessions, as the name imply, are only temporary (and sort of local). When the browser is closed it's gone. Depending on what your demands are you'll have to choose between using a database or textfiles on the server.
Cookies or sessions is not made for this kind of data.
Well if you are looking for a rudimentary solution, see below. If not, use a database as suggested in the other answers.
<?
/* This needs to be at the top of your file, without ANYTHING above it */
session_start();
/* ... */
$file = sys_get_temp_dir() . '/entries.json';
$data = file_get_contents($file);
$entries = (!empty($data)) ? json_decode($data) : array();
$entries[] = array("name" => $_GET["name"], "surname" => $_GET["surname"]);
file_put_contents($file,json_encode($entries),FILE_APPEND);
Related
I wan to use CI session in a external script and I got following data from database.
__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;
I have tried unserialize and unserialize(base64_decode($data)) but I am fail yet.
Please help to extract this data.
I got the solution here
So I have used session decode
session_decode('__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;');
So session decode stored all the encrypted data in normal php session.
Which I can access using: echo $_SESSION['ci_UserID'];
Well guys thanks for the help
If this is a session variable, you can use CodeIgniter's own session library. Consider the following code (in a controller):
$this->load->library('session'); // load the session library
$session_data = $this->session->all_userdata(); // get all session data
print_r($session_data); // print and get the corrresponding variable name, e.g. "item"
$var = $this->session->userdata('item'); // pick one that suits your needs, e.g. item
Sorry, I have read "the external script" only after having posted the code. This obviously only works in the CI framework.
For an external script you may need to have a closer look. The variables are separated by ";" and "|" and then serialized, so this might work (not tested):
$row = explode(';', '__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;'); // load the database row
$userid = explode('|', $row[1]);
$userid = unserialize($userid[1]); // now $userid holds the value "2"
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;
I have a one-to-one key structure of zip codes to user located in a .html that looks like...
...
'80135': 'user1',
'80136': 'user1',
'80137': '',
'80138': '',
'80202': 'user2',
'80203': 'user2',
'80204': '',
'80205': '',
'80206': '',
'80207': '',
...
I would like to take a bulk list zip codes for user3 and fill in or over-write old user. So for example if I have for user3, zip codes (80202,80203,80204) then my previous block of code would change to...
...
'80135': 'user1',
'80136': 'user1',
'80137': '',
'80138': '',
'80202': 'user3',
'80203': 'user3',
'80204': 'user3',
'80205': '',
'80206': '',
'80207': '',
...
The reason for text editor is to complete my set now, but ideally it would be nice to have a client application that our non-programmer team can update and make changes as they please, so a script for this would be nice for future plans.
I am passing the content into my site via...
var list_load = {<?php include_once('list.html'); ?>};
Because I believe some might have an alternate idea on storage of this information, this list is very long, 35,000 lines of code, so any ideas on completely changing my code consider a process to migrate data.
Based on the information you provided I'm going to assume your example code is a subset of a JSON object. I'm also going to assume that you only have a one-to-one relationship of zip-codes to users in your object given that you did not explicitly state otherwise and given that the existing object structure would not allow for one-to-many relationship. Given all these assumptions the solution to your immediate problem is to load the JSON into PHP, make your changes there, and then overwrite the entire file with the updated JSON object.
$json = file_get_contents('list.html');
$array = json_decode($json, true);
$oldUser = 'user2';
$newUser = 'user3';
$listZipCodes = array("80204"); // list of zip codes to update
// Update the JSON based on user ...
foreach ($array as $zipCode => $user) {
if ($user === $oldUser) {
$array[$zipCode] = $newUser;
}
}
// Update the JSON based on zip code ...
foreach (array_keys($array) as $zipCode) {
if (in_array($zipCode, $listZipCodes)) {
$array[$zipCode] = $newUser;
}
}
$json = json_encode($array);
file_put_contents('list.html', $json);
Again, this is all assuming that list.html looks like this...
{
"80135": "user1",
"80136": "user1",
"80137": "",
"80138": "",
"80202": "user2",
"80203": "user2",
"80204": "",
"80205": "",
"80206": "",
"80207": ""
}
Remember it has to be valid a valid JSON object notation in your list.html in order for PHP to be able to parse it correctly. Your existing example is not going to work in PHP because you're using single quotes instead of double quotes, which is a requirement of the JSON spec. So you have to make sure that part is valid in your list.html file.
Beyond that I highly discourage you to take this approach, because it causes a number of serious problems that can't easily be solved. For example, you can not ensure your data won't be corrupted using this approach as anyone two PHP scripts may attempt to overwrite the file at the same time (no data integrity). Also, you can't easily make this scale without it costing you a lot of unnecessary CPU and memory problems if the list gets large enough. Additionally, you have no way to control who may edit the file directly and thus no way to control data flow to the underlying application code that tries to use that data.
A better solution is to use a database and that way you can both control the data and its user privileges, plus you can provide a front-end for non-programmers to edit/modify/read the data through your front-end, via PHP.
Lets say I've got 50 pages, and I want to write a description for about 30 of them.
The description will be about two paragraphs on each page.
Is it more efficient for my server if I save the descriptions in a MySQL database and then query on each page to see if there is a corresponding description, or is it best if I store them in an array in my PHP file and see if the element exists?
Extra Info:
I would edit the array file manually or the db entry through phpMyAdmin which would both take the same amount of time. Also it would only be me editing them so I don't have to worry about making a quick edit file.
Do it like this:
Store them in an array, in a sepparate file data.php, in this form:
<?php
return array(
// here be data
);
In the caller script you use it like this:
$data = require 'data.php';
and then use the $data variable throughout the site, as needed. You could also split the array and use several files based on specific criterias, like "the language", or "article category" or whatever.
If you do it this way, you can always plug in an editor with a web interface to edit that array and store it back with file_put_contents('data.php', '<?php return '. var_export($data));, where $data has got its value after processing a POST form, for instance, which was generated from the old value of $data.
Really elegant, fast, and maintainable!
As a bonus, write helper functions around those serializations, deserializations, etc, such that if you ever change your mind (because your site grows and you end up with hundreds of such arrays), you only have to reimplement those functions to use a database backend, without ever touching the rest of the codebase.
Code reusability and maintanability at its peak! And you get it up and running immediately, without losing the prospect of making it better in the future, if required.
If you don't change those descriptions frequently, you can store them in array. But it'll be better to keep them in separated files, instead of keeping them all in one PHP file.
But your server can easily handle that kind of small rows. So do what is easy for you.
Maybe you can store them in database for adding/editing stuff and do a cache of it to read from your page.
I would store the information in a DB. It is more slowy but more elegant.
If you want to do it with an array:
Class Page
{
// global configuration
private static $config = null;
// individuel configuration
public $title, $content;
// constructor
function __construct($page) {
// get the configuration
$config = self::getConfig();
// cheack weather the page exists
if(!isset($config[$page]))
die('unknown page "'.$page.'"');
// set some stuff
$this->title = $config[$page]['title'];
$this->content = $config[$page]['content'];
}
// get the configuration
private function getConfig() {
if(self::$config === null)
self::$config = include(dirname(__FILE__) . '/config.php');
return self::$config;
}
}
Configuration:
return Array(
'home' => Array(
'title' => 'Welcome!',
'content' => 'Welcome to my site!' /* maybe include some html for complxe stuff */
)
);
Example:
$myPage = new Page('home');
echo $myPage->content;
Here is what I would do in JavaScript. Is there any way to do it in php?
I am working on a project that needs this functionality but cannot use JavaScript.
setInterval ( "checkHistory()", 1000 );
function checkHistory() {
if (oldHistLength != history.length) {
removegateway();
oldHistLength = history.length;
}
}
Sorry to say that it's not possible to do that using PHP. Your only option is to use JavaScript somewhere.
You can however achieve what I believe you're trying to do with another technique - PHP Sessions and Request URIs.
This involves storing the user's accessed URLs into a variable (or you could use MySQL) which can be referenced anywhere on the website within that current session.
Here's an (untested) example:
<?php
session_start();
// Retrieve/create the current list
if( isset($_SESSION['history']) ) {
$history = $_SESSION['history'];
} else {
$history = new array();
}
// Add the current URL to the history array
array_push($history, $_SERVER['REQUEST_URI']);
// Do anything else you want to here
// Store the array again
$_SESSION['history'] = $history;
?>
In your code, you can keep an array containing the values of $_SERVER['php_self'], serialize() it, and store it in a session variable. This may not be sufficient for what you are trying to do though. I'm not sure what removegateway() does, but is this code attempting to prevent the back button from being used?
If you prevent the pages from being cached, you might be able to compare the second to the last value in your array to the current page, and if they match, you detected a back button. This would only be possible if there's no way to go back to the previous page on the front end.
Preventing the back button is generally considered a Bad Thing, so it might be better to reconsider the way you are doing things and come up with a better solution.