Symfony 2, passing variable - php

So how can I pass a variable into a script that is not connected with symfony?
For example, I have variable $a, which I render in template a.html.php
How can I use this $a in some example.php script?
More close: I wanna make image uploading with TinyMCE image manager; but each user should have their own directory (which corresponds to user id). So I should pass variable user_id to config.php file of image manager.
So this directory depends on the user's session! How can I make different dirs to upload images for each user? Or can you advise me how to deal with this problem?
Maybe to use another text editor? Which one can I connect with symfony or to use different directories for different users?

You can store information in the session if you want to share it with other scripts. Make a var_dump($_SESSION) in example.php to see what you already have.

$formPath = 'nameBundle:name:name.html.twig';
$session = $controler->getRequest()->getSession();
$session->set('formPath', $formPath);
$session->set('neededVariables', $neededVariables);
return $controler->redirect($controler->generateUrl('show_result'));
I used this to handle data and read data function
public function showResultAction() {
$session = $this->getRequest()->getSession();
$formPath = $session->get('formPath');
$neededVariables = $session->get('neededVariables');
if ($formPath or $neededVariables)
return $this->render($formPath,$neededVariables); else
throw $this->createNotFoundException('The product does not exist');
}

Related

Something wrong with Codeigniter Callback validation

So I am creating a web app, it has this upload form where you can upload android APKs, this part of upload form is specifically for uploading a revised version of the old APK(In others words new version of the application).
So I am doing all this in PHP, using CodeIgniter 2.x
Since user is uploading a new version of old Application, I want the website to make sure the application being uploaded for this old application by user has same package name (Android Package file name) e.g com.example.something
When the file upload is initiated, the file is parsed and the package name is put into the database, and a random generated hash of this file is stored in the session data as 'new_app_hash', the random hash of old file is in hidden input field called 'app_id'.
Now coming to the code:
My controller has this in place to do the callback thing for app_id, and compare its information with 'new_app_hash' which is in the session.
So, this callback is mainly for getting row information where the hash is 'app_id' and 'new_app_hash' in my database table, then compare the package names.
$app_id = $this->input->post('app_id',TRUE);
if($app_id!='0'){ //only if app_id is not 0, else I dont want this to happen
$this->form_validation->set_rules('app_id','New Package','required|callback_packagerevname');
}
Model function used in callback:
public function check_checkpackagerevname($app_id,$sessionhash){
if($app_id!='0'){
$old_package = $this->getPackageInfo($app_id);
$new_package = $this->getPackageInfo($sessionhash);
if($old_package['package_name']==$new_package['package_name']){
///ok fine they are same, return true.
return TRUE;
}else{
return FALSE;
}
}else{
return TRUE;
}
}
GetPackageInfo():
public function getPackageInfo($hash){
$this->db->select('*');
$this->db->from('appstore_packages');
$this->db->where('hash',$hash);
$query = $this->db->get();
return $query->row_array();
}
My callback is as follows:
function callback_packagerevname($app_id){
$sessionAppHash = $this->session->userdata('new_hash_app');
$checking = $this->storeM->check_checkpackagerevname($app_id,$sessionAppHash);
if($checking==TRUE){
return TRUE;
}else{
$this->form_validation->set_message('packagerevname','The uploaded APK must have same package name as the parent app that you are trying to upload.');
return FALSE; ////// new apk doesnt have same package name.
}
}
I have tried checking if the form_validation rule is working, when i add some other sort of rule like greater_than[0] it does show me errors, but the callback doesn't work when form is submitted, though the callback function seems to work fine, when i visit it directly from the URL, with the 'new_app_hash' set in the session and putting app_id in URL, it does return true or false accordingly.
What could be wrong?
P.S If the question is a little confusing please comment, I am working on the project for like past 12 hours continuously, so I am a little you know. :P
Edit: Ok it seems 12 hours really had it on me.
Thanks to praveen, I had named the callback method wrongly,
instead of :
function callback_packagerevname($app_id){
}
It obviously should have been:
function packagerevname($app_id){
}
You dont need callback_functionname as callback event just remove callback_ and will work fine...
function packagerevname()
{
$app_id = $this->input->post('app_id');
//so on....
}
you can use set flash data
/* $this->form_validation->set_message('checkpackagerevname',
'The uploaded APK must have same package name as the parent app that you are trying to upload.'); */
$this->session->set_flashdata('checkpackagerevname',
'The uploaded APK must have same package name as the parent app that you are trying to upload.');
and can print
echo $this->session->flashdata('checkpackagerevname');
for more visit
https://ellislab.com/codeigniter/user-guide/libraries/sessions.html

How to store a permanent boolean flag?

I have created a web app that has 2 control panels. One for the admin and one for the users. I want the users to be able to perform one specific action from their panel only if the admin sets this action "on" (from his panel) and not being able when he sets it "off".
My app also uses a MySql database.
How can I implement it? Is an extra table with only one field a viable solution? Can I do it by reading a file (maybe JSON)?
EDIT: I want the admin to be able to toggle the "on/off" status with a click of a button, so constants are not a solution.
A database query could be used every time the action is used but if it is more general and you are going to be using this a lot, I would look into PHP constants. You could set it in a configuration file like:
Config.php
define('USER_CAN_MODIFY', true);
Other.php
if ((defined('USER_CAN_MODIFY') and USER_CAN_MODIFY === true) { }
Constants have a global scope and cannot be changed once set.
Since you want to store a single value you don't need to use DB. You may simply store this flag in a file as serialized value.
Below is simplified example.
define('PERM_FLAG_FILE', 'perm_flag.dat');
$PERM_FLAG = false;
function loadFlag() {
global $PERM_FLAG;
return file_exists(PERM_FLAG_FILE)? unserialize(file_get_contents($PERM_FLAG)) : false;
}
function saveFlag() {
global $PERM_FLAG;
file_put_contents(PERM_FLAG_FILE, serialize($PERM_FLAG));
}
function setFlag($v) {
global $PERM_FLAG;
$PERM_FLAG = (bool)$v;
}

How to validate a directory name before calling mkdir with PHP?

I would like to create a function that will create a directory to store photos in the file system. Suppose there is a directory called "albums" in the root directory. There is a form on the page that allows the user to create a new album, which will create a subdirectory under "albums".
Also I want the ability to have nested photo albums. When creating a new album, the admin can provide the album name with the forward slash (/) separators to recursively create this folder structure.
I am using directories because I want the ability to manage the photo albums via direct FTP access to the server for dealing with massive photo albums. Each photo directory can have an optional album.properties file to have any meta data associated with the album itself (such as a thumbnail to use for the album).
if (!is_admin()) die();
$album_name = $_GET['album_name'];
if ($album_name) {
$directory = "/albums/" . $album_name;
// TODO: How can I validate $album_name?
if (file_exists($directory)) {
echo "Album already exists, please choose a different name.";
} else if (mkdir($album_name), 0777, true) { // Recursive is true
echo "Album successfully created.";
} else {
// TODO: Is there a way to output a more detailed explanation?
echo "The album could not be created.";
}
}
See the TODO markers in the PHP code. Also if you have any advice regarding my approach so far, that would be useful.
Note that it was only recently that I decided to use directories and property files instead of database tables to store meta data associated with the albums/photos because I only recently found out that the client wished to use FTP.
I will still need to have database tables, though, to allow the admin to assign privileges to already existing albums. For example, the admin can share a particular album with the public or other non-admin users. The /albums directory will not be directly accessible, instead another .php will allow download of photos or read meta data, but only to permissioned users.
Edit:
Adding more clarification on what I want:
To validate that the $album_name is a valid directory name, if it is not valid I want to output an error message. Also I would like to explain to the user how to choose a valid directory name.
I want to output a more detailed message if mkdir fails, to tell the user what he/she can do to correct the problem.
You can use a regex or just check to see if the mkdir was successful.
See the answers on this questions for reference:
Check a string for a valid directory name
Edit 1:
To check if the mkdir function will succeed you can first use php functions such as is_writable to check if you have permission to write in that location. If not you can let your user know (but if thats the case you should probably be considering why they are trying to write somewhere they dont have permission). Otherwise if the mk_dir function fails you will be able to log the failure and check the issue later. Other than that you probably shouldnt tell the user much without first investigating the problem

Jquery File Upload change session id

I've been trying to solve this problem for days without success.
I am using blueimp Jquery File Upload and everything works fine but I need to save my pictures in different folders depending on a parameter send by url like /index.php?customer=160
<input type="hidden" name="customer" value="<?php print $_GET["id_cliente"];?>">
I created the hidden field in the form and got it in the uploadhanndler.php.
/files/'.$_POST['customer'].'
, here everything goes ok, the file is saved on the folder I wanted, but the next time I open the window /index.php?customer=160, the files listed are the files/ folder not the files/160/ folder or the number I want to list.
I realized I could use the PHP user directories, and the files are beeing saved in a folder like this 6afa0f7338b14aeed39eb7656f364b4e that comes from the session_id(), I tried then to change the session_id() with the number of the folder I want this way at the begining of the /index.php?customer=160
session_start();
session_id($_GET['customer']);
but the files are still beeing saved in folder 6afa0f7338b14aeed39eb7656f364b4e, and when I print the session_id() is 160.
PHP user directories is a good method to achieve what I want? what I am doing wrong?
Thanks in advance and excuse my poor english.
The code below will show you how to save a session ID called customer_id and then use it as a folder name. Please let me know if you need any more help.
// start (or restart) the session
session_start();
// set the customer id session var
$_SESSION['customer_id'] = // set this variable something that you've retrieved from the DB
// create a folder if it doesn't already exist
$dir = '/httpdocs/mySite/customers/' . $_SESSION['customer_id'];
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
even it has been a while since a last answer has been given to this question, I'd like to give a small update on that issue. Since version 5.17 of the jquery-file-upload library ther is a support for user-directories.
Within the UploadHandler.php you will find the option 'user_dirs' => false. Just set it to 'true' and you will have user-directories based on session-id.
If you want to have your own user-directories not based on session-ids, but e.g. based on user-id (your own defined Session key) you can proceed in the following way:
within the index.php file (as stated in the Demo of the jquery-file-upload library) you place following
right after "require('UploadHandler.php');"
class CustomUploadHandler extends UploadHandler {
protected function get_user_id() {
#session_start();
return $_SESSION[*<your own user id session key>*];
}
}
followed by:
$upload_handler = new CustomUploadHandler(array(
'user_dirs' => true
));
...and thats it...now you have your own user-directories for your uploaded files

Route URI to a specific folder in CakePHP

Introduction :
I have this path in my CakePHP : app/webroot/storage/5/C/_demo/omar.txt , this one will be redirected to http://localhost/storage/5/C/_demo/omar.txt
My problem :
I want this path http://localhost/storage/5/C/_demo/omar.txt to be something like this http://localhost/storage/uehKDj44/C/_demo/omar.txt , where uehKDj44 is number 5 , the reason why I'm doing like that is I don't want anyone to change number 5 to any number so they can't access otherwise they login first , let's say if 5 belongs to a user will be open , but if not won't be open , is there any better way to secure it better than that ?
Thanks
Storing restricted data as plain files inside of the htdocs folder (or webroot for CakePHP), where they can be requested without further authorization is always a risky business and should be avoided.
I cannot determine what kind of data you store in the .txt file, but I assume it is not fetched from the database and then saved. My understanding is that the link to the file is displayed to a logged in (authorized) user.
Proposal of a more secure solution:
Move the files outside of the webroot folder and create a constant with the absolute path to that folder (USERDATA_PATH). Remember to set read permission for web server user (www-data for Apache)
Create a model, e.g. UserData with an underlying database table storing a relation between a user and a magic hash (e.g. 1 => 'uehKDj44', 2 => 'ds83skf' etc.). You can also store file names to make it a bit less complicated.
Create a controller UserDataController with an action serveFile which will take the secret key as a parameter, match it with the file and output the file to the user.
public function serveFile($hash= null) {
try
{
$data = $this->UserData->findByHash($hash);
if (!$data) {
throw new Exception('No match found');
}
// Load the data from file
$this->set('output', file_get_contents(USERDATA_PATH.DS.$data['UserData']['filename']));
}
catch (Exception $ex)
{
// No match found - display error message / log
}
}
Then in view:
header('Content-type: text/plain');
echo $output;
This should do the trick.

Categories