File get content via json - php

I have a file text file in which i am saving user id via file_put_contents
i want to display that user id before sending it to view function
here is my code
i try myself bt not geting result....
$name = $this->session->userdata('name');
$id = $this->session->userdata('id');
file_put_contents($filename,json_encode(array('id'=>$id,'name'=>$name)));
$response = array();
$response = json_decode(file_get_contents($filename));
if ($response->name==1){
echo $this->session->userdata('name');
}
echo json_encode($response);
this dont work that i want to display bt if i remove this if condition then i get my result in view file
if ($response->name==1){
echo $this->session->userdata('name');
}
thanks....

$response->name it will be a string, not an int.
Replace:
if ($response->name==1){
echo $this->session->userdata('name');
}
With:
if ($response->name){
echo $this->session->userdata('name');
}
Update:
You stated somewhere in the comments that you want to check for the user id, but in the code you check username. Also inside the if condition, you should use data from $response and not the one from session. That said:
if ($response->id == 1){
echo $response->name;
}
As a side note, are you sure that id and name exists in the session ?

im not clear why do you have
if ($response->name==1){
but any way try this
if you want to prezerve json object stucture you need the second param to be true
json_decode(file_get_contents($filename) ,true);
and you need some json headers that you can find in the botom
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$name = $this->session->userdata('name');
$id = $this->session->userdata('id');
if(!empty($name)){
if(!is_file($filename)){
touch($filename);
chmod($filename,0777);
}
file_put_contents($filename,json_encode(array('id'=>$id,'name'=>$name),true));
$response = array();
$response = json_decode(file_get_contents($filename) ,true);
if (empty($response->name)){
echo json_encode(array('error'=>'empty response name'),true);
die();
}else{
echo json_encode($response);
}
}else{
json_encode(array('error'=>'no username'),true)
}
there is my messaging system inside my admin its for codeigniter
http://dl.dropbox.com/u/72626795/messaging.zip

Related

how to clear cache using PHP?

how could I clear the cache for the image instantly with my uploader? I'm currently trying this but isn't working. any suggestion? thank you !
ps : settings.php is the current page, and I'm using only one header location
the image is currently uploader some time, but not always, some time it doesn't work without a ctrl + maj + r
uploader code :
<?php
// UPLOAD FICHIER
if (isset($_POST['valider']))
{
if (isset($_FILES['avatar']) AND !empty($_FILES['avatar']['name']))
{
$tailleMax = 1000000;
$extensionsValide = array('jpg', 'png');
if ($_FILES['avatar']['size'] < $tailleMax)
{
$extensionsUpload = strtolower(substr(strrchr($_FILES['avatar']['name'], '.'), 1));
if (in_array($extensionsUpload, $extensionsValide))
{
$chemin = "../images/avatar/" . $_SESSION['id'] . "." . $extensionsUpload;
$resultat = move_uploaded_file($_FILES['avatar']['tmp_name'], $chemin);
$touxiang = $_SESSION['id'] . "." . $extensionsUpload;
$session = $_SESSION['id'];
if ($resultat)
{
$updateAvatar=$dbh->prepare("UPDATE members SET avatar = :avatar WHERE id = :id");
$updateAvatar->bindValue('avatar', $touxiang);
$updateAvatar->bindValue('id', $session);
$updateAvatar->execute();
header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
header('Location: settings');
}
else
{
echo "<p class='review_wrong'>error.</p>";
}
}
else
{
echo "<p class='review_wrong'>wrong format. jpeg png.</p>";
}
}
else
{
echo "<p class='review_wrong'>File too large.</p>";
}
} // ISSET
}
?>
<div id="avatar_send_div">
<input id="upload_header" type="file" name="avatar">
<label for="upload_header" class="btn">Upload</label>
<input id="submit_header" type="submit" name="valider" value="Validate">
</div>
show image :
<?php
if (isset($_SESSION['id']) AND !empty($_SESSION['id']))
{
$id = $_SESSION['id'];
$req = $dbh->prepare('SELECT * FROM members WHERE id = :id');
$req->bindValue('id', $id);
$req->execute();
$userinfo = $req->fetch();
}
?>
<div id="settings_div_img">
<img id="settings_img" src="../images/avatar/<?php echo $userinfo['avatar'];?>">
</div>
db :
As others have stated in the comments, you can't really clear the cache with PHP, certainly not the cached assets (images, CSS files, etc). Assets are almost all the time served directly by the webserver.
The HTTP headers that you are setting with PHP will only affect the document being returned by your PHP script, which in your case is an HTML page. Also, sending headers does not guarantee that the cached document will be cleared (it's the job of the user's browser to do that).
So you are generating an HTML page with URLs pointing to images served by the webserver. To control the cache of these images, you mostly want to configure the webserver itself (Apache, NGINX, etc)
That again won't necessarily work if the user already has a previously cached image.
A common technique to go around that and avoid having to generate new image filenames is to append a version id to the image URL and change it as new versions of the image are uploaded.
So instead of having example.net/john.png you would generate example.net/john.png?v=1 and then when you upload a new image, you generate a new URL example.net/john.png?v=2. You can basically append anything to the query string, the goal is to generate a new URL that the browser hasn't seen before.
You will find more techniques here: Refresh image with a new one at the same url
I hope that helps.

HTML function to download JSON stored in MySQL database

I would like to be able to save a JSON file that is in a database to the user's PC. In summary, I'm storing setup files from a sim racing game, that use a JSON format, in a database, and I'd like the user to be able to upload/download these JSON files (to share with others, etc).
I've got the upload working, using PDO, so there is a column called setup that is a text data type. I'm using a form, with a $FILES() to fetch the uploaded json file, with some checks to ensure it's a valid setup json.
$setup = file_get_contents($_FILES['setupjson']['tmp_name']); //get json from file uploaded
$setupJSON = json_decode($setup); //decode into object
$car = $setupJSON->carName; //carName from object
if ($obj->searchCarName($car) > 0) // if search matches (car exists)
{
if($obj->insertSingleSetup($_POST["name"], $_POST["description"], $_POST["type"], $car, $_POST["track"], $setup) !== false)
{
header('Location: add.php?success');
exit();
}
else
{
header('Location: add.php?error=Error+adding+the+setup');
exit();
}
}
else
{
header('Location: add.php?error=Please+submit+a+valid+setup');
exit();
}
}
The issue i'm having is downloading the file again. I've been able to view the JSON directly
<?php
include('../db.php');
$setup_id = $_POST['setup'];
try {
$connectionString = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
DB::DB_HOST,
DB::DB_NAME);
$pdo = new PDO($connectionString, DB::DB_USER, DB::DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT * FROM setups WHERE setup_id= :setupID';
$query = $pdo->prepare($sql);
$query->bindValue(':setupID', $setup_id);
$result = $query->execute();
$setup = $query->fetch(PDO::FETCH_ASSOC);
processSetup($setup);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
$setupJSON = json_decode($setup);
echo '<pre>';
echo $setup;
echo '</pre>';
}
?>
but I can't work out how to download it. I've researched that it's related to headers, but everytime I try something, it never works. I just want the save file dialog to appear with the json, and preferably, the option to set the filename outputted to a chosen variable.
Just figured it out, on the processSetup function, I changed the code to this
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
header('Content-type: application/json');
header('Content-disposition: attachment; filename=setup.json');
echo $setup;
}
If I add some code to give the JSON it's proper filename, it'll be perfect :D

JSON Encode characters in PHP

I am trying to return a value using php and AJAX but I get the following returned when doing so. This part of my code has been functional in previous projects so I am a little stumped as to why it is happening now.
The returned value:
‹������«VÊÏV²2ÔQ*.)V²qjÜ¥5¼���
it should return something like this:
{"ok":1,"status":"ok"}
The PHP I am using:
$response = array('ok' => 0);
if($results)
{
$response['ok'] = 1;
$response['status'] = ($visible == 'visible') ? 'ok' : 'no';
}
ob_clean();
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($response, true);
exit;
Now if I removed the code and put into its own file it works fine. I have all files and database set to UTF-8 also.
You have a duplicate closing parentheses on line 2.
It should be:
$response = array('ok' => 0);
if($results)
{
Fixing that, your code works for me:
{"ok":0}
And if I force $results = true; :
{"ok":1,"status":"no"}
I feel so stupid now, I was running ob_gzhandler within my ob_start();
Apologies to all.

download button - save file to disk instead of opening

I have a download button and when i click on it, instead of saving to disk it opens it in the browser. I tried a bunch of attempts to make it open in the browser but it doesnt seem to do anything
<?php
// make a connection to the database
require_once("connection/connection.php");
//retrieve the ID from the url to fetch the specific details
if ($_GET['id'] != ""){
$item_id = $_GET['id'];
$bad_id = FALSE;
}
else{
$item_id = "";
$bad_id = TRUE;
}
//select the specific item from the database
// run if statement to ensure valid id was passed
if (is_numeric ($_GET['id'])){
$query = "SELECT name FROM repository WHERE item_id = '$item_id'";
$result = mysql_query($query) or die(mysql_error());
// assign the values to an array
$row = mysql_fetch_assoc($result);
//assign the values from the array to variables
$name = $row['name'];
}
// define path to the xml file
$file = "xml/".$hud_name . "_cfg.xml";
// check to make sure the file exists
if(!file_exists($file)){
die('Error: File not found.');
} else{
// Set headers
header("Content-Type: application/xml");
header("Content-Disposition:attachment; filename=".basename($file)."");
readfile($file);
}
?>
That is download.php and it obviously finds the file because it doesnt give the error about it not existing. It also echos back the correct file path
Then on another page i have:
<img src="images/download.png" alt=""/>
Any ideas whats wrong?
Well the solution turned out to be simple in the end but i didnt see any documentation saying the header must be the very first line. If i placed:
header("Content-Type: application/xml");
as the first line and then the coding below it and the other header info at the end it works. Im not sure if that's the solution or a workaround but it fixed it for me

php index.php, add to cart issue

I am having trouble executing this code in my index.php.
It says 'CartAction not set'
I need your help php gurus. I can display any files you need to fix this error.
Here is the code:
// Handle AJAX requests
if (isset ($_GET['AjaxRequest']))
{
// Headers are sent to prevent browsers from caching
header('Expires: Fri, 25 Dec 1980 00:00:00 GMT'); // Time in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: text/html');
if (isset ($_GET['CartAction']))
{
$cart_action = $_GET['CartAction'];
if ($cart_action == ADD_PRODUCT)
{
require_once 'C:/vhosts/phpcs5/presentation/' . 'cart_details.php';
$cart_details = new CartDetails();
$cart_details->init();
$application->display('cart_summary.tpl');
}
else
{
$application->display('cart_details.tpl');
}
}
else
trigger_error('CartAction not set', E_USER_ERROR);
}
else
{
// Display the page
$application->display('store_front.tpl');
}
It's because your code is expecting a parameter named 'CartAction' in the url
Example:
www.yoursite.com/?CartAction=ADD_PRODUCT
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. Source
You check if $_GET['CartAction'] has a value ( from the above url this superglobal variable has the value 'ADD_PRODUCT' )
What #Mackiee (in comments) and your error message are both telling you is that the problem is that there is a query parameter missing. The URL that calls this needs to include either ?CartAction=ADD_PRODUCT or &CartAction=ADD_PRODUCT

Categories