PHP - Configuring Symfony To Authenticate To Postgresql Using Peer Authentication
A while back, I was showed how to authenticate to PostgreSQL using peer authentication over a socket for applications where PHP, FPM, and PostgreSQL are all on the same machine. All works. I could use native PHP as shown and it returns results without errors so I know that PHP, FPM, and PostgreSQL is setup correctly to establish a connection using peer authentication without a PostgreSQL username or password. $pdo = new PDO("pgsql:dbname=testing"); $rs = $pdo->query('SELECT * FROM company')->fetchAll(); I could also use Doctrine but not Symfony and get results without errors so I know that Doctrine is capable of establishing a connection using peer authentication without a PostgreSQL username or password. $pdo = EntityManager::create(['driver' => 'pdo_pgsql','dbname' => 'testing'], Setup::createAnnotationMetadataConfiguration([__DIR__."/../src"], true, null, null, false))->getConnection(); $rs = $pdo->query('SELECT * FROM company')->fetchAll(); Now I am trying to do the same but when using Symfony. I expected I could just edit config/packages/doctrine.yaml as follows, however, it results in An exception occurred in driver: SQLSTATE[08006] [7] fe_sendauth: no password supplied doctrine: dbal: driver: pdo_pgsql dbname: testing server_version: 13 Any thoughts how to do this? Thank you Similar TutorialsHello,
I want the user to get authenticated before file download starts
Here is my code:
<?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Your request is cancelled'; exit; } else { //check $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] if (isset ($valid)) { //start download $path = './data/negative_seq_60.txt'; $type = "text/plain"; header("Expires: 0"); header("Pragma: no-cache"); header('Cache-Control: no-store, no-cache, must-revalidate'); header('Cache-Control: pre-check=0, post-check=0, max-age=0'); header("Content-Description: File Transfer"); header("Content-Type: " . $type); header("Content-Length: " .(string)(filesize($path)) ); header('Content-Disposition: attachment; filename="'.basename($path).'"'); header("Content-Transfer-Encoding: binary\n"); readfile($path); // outputs the content of the file exit(); } else { //show error } } ?> But on clicking download link, I am getting the following error : " Undefined variable: valid at line no 9". Please help. This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=313491.0 I have used the XAMPP installer to install php and MySQL locall on my computer. I also succeeded in setting the security for XAMPP pages, the MySQL admin user root and phpMyAdmin login. When I enter phpMyAdmin via the link in the XAMPP initial page I do however receive a red notification: phpMyAdmin configuration storage is not fully configured; some extensions are not activated. To find out click here. I have attached a screenshot showing three items which are not OK, shown in red. I looked up in the documentation, but could not find out. I hope someone can help. I don't even know if it is important to fix this problem. Regards, Erik Attached Files XAMPP2.jpg 41.08KB 0 downloads Hey Guys. I am writing a function that will output to the user if a store is open or not.
I wrote a fucntions named is_store_open() with a variable called $day which will have the current day of the week assigned to it.
Lets say it is Saturday. it finds the case for "Saturday" and checks the opening time and closing time for Saturday.
The problem that I am facing, is when the store is open past midnight on Saturday. It then won't check the case for saturday.
Instead will check the case for Sunday. Which is not what I want, becuase it will show the store as closed when its open still open on "Saturday"
I wrote a function below that checks to see if the previous day closing hours are greater then the current time. If its true then return true and I guess that should fix the problem.
But when I wrote that it would give me an error saying that $saturday_close is undefined. I'm guessing its becuase its in a switch satement, and it does not equal to that day.
I'm a little bit confused on how to set this up. If anyone has a suggestion I would really apprecaite your help. Thanks!
function is_store_open(){ $set_time = strtotime("tomorrow"); // Lets just sat its Sunday for testing purposes $day = date("l", $set_time); $time_now = mktime("00", "00", "00"); // Now lets say the time now is 12:00am switch ($day) { case "Saturday": $open = "11:00"; $saturday_close = "1:00"; break; case "Sunday"; if($saturday_close > $time_now ){//If the $monday_close hours are greater then the current time return false the store is still open return true; } else { $open = "2:00"; $close = "22:00"; } break; } }// End of function if(is_store_open()) { echo "Oh no! There is still a glitch in the system the store needs to remain open"; } else { echo "The store is still open on Saturday"; } I came across this error when trying to learn how to send form data to my email address - Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\Apache\htdocs\websites\php_learn\report.php on line 30 From what I have read so far I think I need to reconfig my php.ini file. So I looked into my php.ini file and found this - [mail function] ; For Win32 only. ; http://php.net/smtp SMTP = localhost ; http://php.net/smtp-port smtp_port = 25 ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = me@example.com I have a 64 bit system so do I need to download another version of php? Also when I do get to the point at where I can config the php.ini file how do I go about it? Any help would be greatly appreciated. Hi, Trying PostgreSQL for the first time but not making much progress. Get peer failure when not including a host and Ident error when including a host. Never heard of Ident authentication until today and don't know for sure if I even have such a server running. Using Centos7, PHP7.4 using remi's repo, and PostgreSQL 12 from their repo. Any thoughts? Thanks
try { //use Unix domain sockets $dbh = new PDO("pgsql:dbname=postgres", 'postgres', 'secret'); } catch(Exception $e){ echo($e->getMessage().PHP_EOL); } try { $dbh = new PDO("pgsql:host=localhost;dbname=postgres", 'postgres', 'secret'); } catch(Exception $e){ echo($e->getMessage().PHP_EOL); } try { $dbh = new PDO("pgsql:host=127.0.0.1;dbname=postgres", 'postgres', 'secret'); } catch(Exception $e){ echo($e->getMessage().PHP_EOL); }
SQLSTATE[08006] [7] FATAL: Peer authentication failed for user "postgres" SQLSTATE[08006] [7] FATAL: Ident authentication failed for user "postgres" SQLSTATE[08006] [7] FATAL: Ident authentication failed for user "postgres"
Hi, You probably know where I am right now: after reading and coding for about an hour, you are happy with the solution you've come up with and that is working 'so-and-so', and then you do some more reading and coding only to find that suddenly everything stops working. At this moment, my db-session-class doesn't do *zilch* anymore. Could someone please look through the code and point me at something probably to stupid to mention? Code: [Select] <?php class Session { /* Required this Postgresql table: * CREATE TABLE session ( sessionid CHAR(32) NOT NULL, expiration INT NOT NULL, value TEXT NOT NULL, CONSTRAINT session_pk PRIMARY KEY(sessionid) ); */ public $sess_id; public $sess_data; public $sess_name; public $sess_life; public $sess_exp; private $_conn; /* open() * Opens a persistent server connection and selects the database. */ function open($sess_path, $sess_name) { if (! session_set_save_handler( array(&$this,'open'), array(&$this,'close'), array(&$this,'read'), array(&$this,'write'), array(&$this,'destroy'), array(&$this,'garbage_collect') )) { die('session_set_save_handler() failed'); } $this->sess_life = 18000; $this->_conn = @ pg_connect("host=localhost dbname=<snip> user=<snip> password=<snip>"); } // end function open() /* close() * Doesn't actually do anything since the server connection is * persistent. Keep in mind that although this function * doesn't do anything in this particular implementation, it * must nonetheless be defined. */ function close() { // Allegedly needed to write everything to db before closing // the object. session_write_close(); // On Debian and Ubuntu, garbage collection is not immediately // handled, so we call it here ourselves, just to make sure. $this->garbage_collect($this->sess_life); //pg_close($this->_conn); return 1; } // end function close() /* read() * Reads the session data from the database */ function read($sess_id) { $query = "SELECT value FROM session WHERE sessionid ='$sess_id' AND expiration > " . time(); $result = pg_query($this->_conn, $query); if (pg_num_rows($result)) { $row = pg_fetch_assoc($result); $value = $row['value']; return $value; } else { return ""; } } // end function select() /* write() * This function writes the session data to the database. * If that sessionid already exists, then the existing data will be updated. */ function write($sess_id, $sess_data) { $expiration = time() + $this->sess_life; $query = "INSERT INTO session VALUES('$sess_id', $expiration, '$sess_data')"; $result = pg_query($this->_conn, $query); if (! $result) { $query = "UPDATE session SET expiration = $expiration, value = '$sess_data' WHERE sessionid = '$sess_id' AND expiration >". time(); $result = pg_query($this->_conn, $query); } } // end function write() /* destroy() * Deletes all session information having input sessionid (only one row) */ function destroy($sess_id) { $query = "DELETE FROM session WHERE sessionid = '$sess_id'"; $result = pg_query($this->_conn, $query); } // end function destroy() /* garbage_collect() * Deletes all sessions that have expired. */ function garbage_collect($lifetime) { $lifetime = $this->sess_life; $old = time() - $lifetime; $query = "DELETE FROM session WHERE expiration < $old"; $result = pg_query($this->_conn, $query); return pg_affected_rows($result); } // end function garbage_collect() } ?> (I have been tinkering with that piece of code for more than 2 hours now, and I don't get any errors. Where at first, I got a row in my db (only the sessionid and expiration-columns were filled, no 'value' whatsoever...), now I don't get anything and NO errors... Anyway: This is how I initialize: Code: [Select] require_once 'classes/cls_session.php'; $S = new Session; session_start(); session_regenerate_id(true); thanks for any insights! Hey guys, I'm new here so please be gentle with me! I have this php command referencing my postgresql db at present: 'Select'=>$this->MyTable->GetAllSQLSelectFieldNames(array('perc'=>'((firstnumber)::float)/((secondnumber)::float) as perc')), It is possible for firstnumber to be greater than secondnumber, but I'd like to limit the array output to 1 - ie to represent that firstnumber is greater than or equal to secondnumber without ever returning a number greater than 1. Can anyone point me in the right direction for this please? While I am impressed with much of Symfony, the needing to know everything the "symfony way" is a little annoying. For an application, I will have several types of users: Admin Users. They can create a project, add new vendors, assign vendors to a given project, add new normal or admin users, etc. Vendors. They can view projects which they are assigned to and upload documents for that project. Normal Users. They will have the ability to view documents related to a given project which are submitted by vendors. Super Users. There will be multiple Accounts where all of the above user's will be assigned to a single, and they can only interact with others assigned to that same account. The super user can create an account and add the initial Admin User to that account.To expose the data, I am using api-platform. Currently, I am just trying to create endpoints to retrieve a list of vendors, normal users, etc. One possible solution I know how to accomplish but don't believe is the correct way is to create an AbstractUser and create VendorUser, NormalUser, etc which extend AbstractUser. Doing so will create routes for each of these user types and meet my immediate needs. Alternatively, I can create only a single User entity, and then assign roles such as ROLE_ADMIN, ROLE_VENDOR, ROLE_USER, or ROLE_SUPER. Ideally, I could then add new routes such as /vendors instead of making it /users?type=vendor. Or maybe I should be doing something totally different. If I was building this from scratch, I can definitely figure something out, however, would like to take advantage of symfony and do it their way. But I am a complete newbie when it comes to symfony, and don't even know where to start, and would appreciate a strategy to go which won't lead me down to bad of wrong path. The following returns strings instead of floats. Am I able to retrieve floats directly from PDO and/or PostgreSQL or must I manually type cast them afterwards using PHP? Thanks $sql='WITH RECURSIVE t AS (bla bla bla) SELECT id, CAST(SUM(slope*value+intercept) AS FLOAT) "value", SUM(slope*prev_value+intercept)::FLOAT "prevValue" FROM t WHERE type=\'physical\' GROUP BY id'; $stmt = $this->pdo->prepare($sql); $stmt->execute($ids); $arr = $stmt->fetchAll(\PDO::FETCH_UNIQUE); //returns [123=>['value'=>'123.456', 'prevValue'=>'122.234'], ...]
Hey again, was making a registration form with php and postgresql and im stuck at making a 'log out' button, i need to make something simple like - press on a link, it redirects u to the index page and if u try to go 'back' it wouldn't let u.. I found something on google like this: <a href="test.php?logout=1">Log out</a> and on test.php: <?php if(isset($_GET['logout'])){ session_unset; session_destroy; } ?> Succesfully logged out, go back to index page: <a href="index.php">Home</a> but i didnt use any sessions at all.. is there something like 'session_destroy' with postgre? i mean smth like 'pg_desroy'? Hello I am using SQL Server 2008 and Xampp server for PHP. I am trying to call SQL Server reports from PHP and I am using the code from https://ssrsphp.code...ussions/577518# I can call the URL which connects to the Reports server from PHP but when I try to click the dropdown and run the reports I get an error. Fatal error: Class 'PReportException' not found in E:\PHP_SRS\ssrsphp\Factory\SSRSTypeFactory.php on line 75 Can someone please tell me how to fix this error ? Thanks Senior PHP / PHP Developer (m/f) – Symfony 2 or Laraval
Software Engineering | Berlin, Germany
The company
We are working with one of the largest venture start-up businesses in the world, they have started some very famous eCommerce businesses in Germany which have also launched worldwide. The company incubate businesses providing them with full technical support to help them create their business in the most efficient way. The scope of work that you get exposure too is actually quite wide, meaning that the projects will be challenging and varied.
About the Job
I am currently looking for multiple experienced Software Engineers to join a highly professional and dynamic IT team currently filled with skilled PHP5 developers from across Europe. You will be tasked with the planning, tracking and executing of software architecture through to responsibility for assigning resources to design and implement work flows which meet budget, quality and time targets. The aim is for you to develop your skills and career using your skilled colleagues and the robust career development plan. You can expect an attractive salary and the chance to work with new technologies in a high- energy team based in the heart of Berlin with a company.
This is a company whose business language is English but they do welcome German natives to the team.
Who we are looking for
We are ideally looking for individuals with over 2 years experience of PHP5 (OOP) and MySQL databases. You will have experience of either Symfony 2 or Laraval frameworks as these are used frequently. We want people who want to learn new technologies and keep themselves up to date with these technologies. Basic knowledge in system administration (Linux, Apache or nginx) and deep interest in scaling high performance web sites, database optimization and web services (REST, SOAP) would be ideal.
The company do not offer relocation assistance, however, they will advise you on the right places to search for accommodation, the cost of living in Berlin and anything else you need to know.
Are you interested?
If so, please send me your application either in German or in English!
Stuart.day@quantica.co.uk
Hello guys, I have purchased a new book for PHP called Professional PHP 6. But the bad news is that the whole book was written for PostgreSQL NOT for MYSQL which I'm familiar with! I have this code, I have tried to do so many things to get it working! but nothing seems to have it working! Long story short, I have failed to convert the code to work with MySQL! Here is my code, in case some one will offer a help, or a reference to go to if some similar case comes up on my way. <?php class Widget { private $id; private $name; private $description; private $hDB; private $needsUpdating = false; public function __construct($widgetID) { //The widgetID parameter is the primary key of a //record in the database containing the information //for this object //Create a connection handle and store it in a private member variable //This code assumes the DB is called "parts" $this->hDB = pg_connect('dbname=parts user=postgres'); if(! is_resource($this->hDB)) { throw new Exception("Unable to connect to the database."); } $sql = "SELECT name, description FROM widget WHERE widgetid = $widgetID"; $rs = pg_query($this->hDB, $sql); if(! is_resource($rs)) { throw new Exception("An error occurred selecting from the database."); } if(! pg_num_rows($rs)) { throw new Exception("The specified widget does not exist!"); } $data = pg_fetch_array($rs); $this->id = $widgetID; } public function getName() { return $this->name; } public function getDescription() { return $this->description; } public function setName($name) { $this->name = $name; $this->needsUpdating = true; } public function setDescription($description) { $this->description = $description; $this->needsUpdating = true; } public function __destruct() { if($this->needsUpdating) { $sql = "UPDATE widget SET "; $sql .= "name = " . pg_escape_string($this->name) . ", "; $sql .= "description = " . pg_escape_string($this->description) . ""; $sql .= "WHERE widgetID = " . $this->id; $rs = pg_query($this->hDB, $sql); } pg_close($this->hDB); } } ?> FYI: I have tried mysql_pconnect ! results => failure! I have tried replacing the prefix "pg" to "mysql" or "mysqli"! results => failure! I have tried switching parameters, say in pg_query($resource, $query) TO mysql_query($query, $resource) results => failure too! Thank you in advance! This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=317833.0 Is it possible to get bittorrent peer list (IP list) via php, udp protocol ? txh! I am a little confused with the difference between Symfony Events and Event Listners and Doctrine Events. The Doctrine events look pretty straight forward and are primary used for entity persistence, and I have outlined my understanding below: Doctrine Lifecycle Callbacks. Single entity and single Doctrine event. Method in class. Good performance. Don't have access to Symfony services (all others do) Doctrine Lifecycle Listeners. All entities and single Doctrine event. Separate class and configured in config.service.yaml. Doctrine Entity Listeners. Single entities and single Doctrine event. Separate class and configured in config.service.yaml. Doctrine Lifecycle Subscribers. All entities and multiple Doctrine event. Must implement EventSubscriber (or probably EventSubscriberInterface) Separate class and configured in config.service.yaml.I am more confused with the Symfony events and my interpretation as listed below is likely incorrect. Symfony Event Listeners. Single Symfony event. Separate class and configured in config.service.yaml. More flexible because bundles can enable or disable each of them conditionally depending on some configuration value. Symfony Event Subscribers. All specified Symfony events. Must implement EventSubscriberInterface Separate class but NOT configured in config.service.yaml but in class. Easier to reuse because the knowledge of the events is kept in the class rather than in the service definition.Are they used for totally different purposes or can one use Symfony events to also deal with entities? Where would one want to use these Symfony events? Is there a reason why Doctrine Lifecycle Subscribers are located in src/EventListener and not src/EventSubscriber Are Doctrine Lifecycle and Entity Listeners really only for a single event as I interpret the documentation states, or is it one method per Doctrine event such as the following? App\EventListener\SearchIndexer: tags: - name: 'doctrine.event_listener' event: 'postPersist' - name: 'doctrine.event_listener' event: 'postUpdate'
This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=347122.0 Doing something wrong, but don't see it. How should one retrieve a POST parameter? My $request->toArray()['html'] works, but I am sure it is not the "right way". <?php namespace App\DataPersister; use ApiPlatform\Core\DataPersister\DataPersisterInterface; use Symfony\Component\HttpFoundation\RequestStack; class ArchivePersister implements DataPersisterInterface { public function __construct(RequestStack $requestStack) { $request = $requestStack->getCurrentRequest(); syslog(LOG_ERR, '$request->getMethod(): '.$request->getMethod()); syslog(LOG_ERR, '$request->getContent(): '.$request->getContent()); syslog(LOG_ERR, '$request->request->get(html): '.$request->request->get('html')); syslog(LOG_ERR, '$request->query->get(html): '.$request->query->get('html')); syslog(LOG_ERR, '$request->get(html): '.$request->get('html')); syslog(LOG_ERR, '$request->toArray(): '.json_encode($request->toArray())); syslog(LOG_ERR, '$request->toArray()[html]: '.$request->toArray()['html']); } } output $request->getMethod(): POST $request->getContent(): {"project":"/projects/1","description":"","html":"<p>{{ project_name }}</p>"} $request->request->get(html): $request->query->get(html): $request->get(html): $request->toArray(): {"project":"\/projects\/1","description":"","html":"<p>{{ project_name }}<\/p>"} $request->toArray()[html]: <p>{{ project_name }}</p> |