Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
DimpledChad
May 14, 2002
Rigging elections since '87.
Just a note, the mysql_ functions have been deprecated for a long time. Use mysqli or (better) PDO. See here: http://php.net/manual/en/mysqlinfo.api.choosing.php. I wouldn't trust any tutorial that used the old mysql API, as it's probably years out of date.

Adbot
ADBOT LOVES YOU

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
I am struggling to find any tutorial that includes the adding the filename to the database. They all seem to be either leaving that out or putting the files in the database. For my use that would be stupid. Any good tutorial site I should know about on php and mysql?

down with slavery
Dec 23, 2013
STOP QUOTING MY POSTS SO PEOPLE THAT AREN'T IDIOTS DON'T HAVE TO READ MY FUCKING TERRIBLE OPINIONS THANKS

thegasman2000 posted:

I am struggling to find any tutorial that includes the adding the filename to the database. They all seem to be either leaving that out or putting the files in the database. For my use that would be stupid. Any good tutorial site I should know about on php and mysql?

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers is a decent overview

DimpledChad
May 14, 2002
Rigging elections since '87.
Just save the filename ($_FILES['uploadedfile']['name']) as a varchar column in the db...? Then concatenate it to the end of your config variable with the directory where the files are on the server.

But seriously, there are a couple major problems with this code:

1. Taking form input and concatenating it into a SQL query is the #1 WORST SECURITY ERROR ever. Your site WILL get pwned if you do this. See http://php.net/manual/en/security.database.sql-injection.php. The only way to fully protect against SQL injection is with prepared statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php or http://php.net/manual/en/pdo.prepared-statements.php

2. The deprecated mysql_* APIs. These don't support prepared statements or transactions and so are inherently insecure and not safe for important data.

As far as good sites, I think the official PHP documentation is actually pretty darn good. The W3Schools tutorials are actually not as terrible as you might expect. Whatever you do, don't copy and paste random code from who knows where on a live site without fully understanding what it's doing. It's just asking for security risks.

Ghostlight
Sep 25, 2009

maybe for one second you can pause; try to step into another person's perspective, and understand that a watermelon is cursing me



thegasman2000 posted:

I removed the size check as I am not bothered at this stage. Still it allows the uploading of PHP files, and returns the variable $ok check as 1. So the if statement on $uploaded_type cannot be triggering.
This is because $uploaded_type is defined as NULL at the start and never changed, so of course it never equals "text/php".

Try
code:
//This is our limit file type condition  
$uploaded_type = $_FILES['photo']['type']
if ($uploaded_type =="text/php")  {  
echo "No PHP files<br>";  
$ok=0;  
}
There's some other way to test filetype using finfo, but I thankfully haven't had a lot to do with uploads so I can't help much on that front or regards to securing it properly.

Note that your confirmation message is also missing the name of the file because you're referencing $_FILES['uploadedfile']['name'] rather than $_FILES['photo']['name'] as it is referred to elsewhere.

revmoo
May 25, 2006

#basta

DimpledChad posted:

1. Taking form input and concatenating it into a SQL query is the #1 WORST SECURITY ERROR ever. Your site WILL get pwned if you do this. See http://php.net/manual/en/security.database.sql-injection.php. The only way to fully protect against SQL injection is with prepared statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php or http://php.net/manual/en/pdo.prepared-statements.php


This can't be stressed enough. This security is so poor that it's the equivalent of installing the original Windows XP onto a machine and assigning it a public IP address. It's so bad that it'll most likely get owned automatically by a botnet.

People getting into PHP for the first time really need to learn how to safely interact with the database first. That needs to be either using prepared statements with PDO, or using a framework with an ORM/Query builder. This is literally day one important stuff.

Experto Crede
Aug 19, 2008

Keep on Truckin'
Is there any extra work required to make phpseclib work in apache? If I run a script that just connects to the server using a public_key it works fine, but when I run it through apache I get a failed to login, unless I enable display_errors, then I get a permission denied error. Same result if I use a password too.

EDIT: Never mind. selinux had set httpd_can_network_connect to 0.

Experto Crede fucked around with this message at 16:42 on Dec 6, 2014

Experto Crede
Aug 19, 2008

Keep on Truckin'
Sorry for the double post, but I have a foreach loop that seems to only be running once.

I have an array which is raw data pulled from the work PBX which looks like this

I'm wanting to loop through this and remove the wasted space to get the two figures I need (inbound number and the extension taking it.

The loop is this:

code:
$data = array("Number" => "", "Ext" => "");
foreach($new as $i){
        preg_match('/[0-9]{4}/', end($i), $ext);
        $numbers = key(preg_grep("/,/", $i));
        $result = array_merge($data, array("Number"=> $i[$numbers+1], "Ext" => $ext[0]));
}
Which is basically pulling the extension (four digits) from the last line, and the phone from the value after the brand, one (as the number format will often be different, or just say Unknown, etc. It works fine on the first time, but if there's multiple calls it will only pull the first call into an array.

I'm sure missing something obvious, but I can't spot it.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

Experto Crede posted:

Sorry for the double post, but I have a foreach loop that seems to only be running once.

I have an array which is raw data pulled from the work PBX which looks like this

I'm wanting to loop through this and remove the wasted space to get the two figures I need (inbound number and the extension taking it.

The loop is this:

code:
$data = array("Number" => "", "Ext" => "");
foreach($new as $i){
        preg_match('/[0-9]{4}/', end($i), $ext);
        $numbers = key(preg_grep("/,/", $i));
        $result = array_merge($data, array("Number"=> $i[$numbers+1], "Ext" => $ext[0]));
}
Which is basically pulling the extension (four digits) from the last line, and the phone from the value after the brand, one (as the number format will often be different, or just say Unknown, etc. It works fine on the first time, but if there's multiple calls it will only pull the first call into an array.

I'm sure missing something obvious, but I can't spot it.

What would correct output look like? Are you just trying to iterate over an array and remove the empty values? The code you have really looks like overkill.

Experto Crede
Aug 19, 2008

Keep on Truckin'

musclecoder posted:

What would correct output look like? Are you just trying to iterate over an array and remove the empty values? The code you have really looks like overkill.

The output should be a new array with only the phone number and four digit extension taking the call. Basically like the old one but with only two values and headings for them as well.

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
So I have a login script but I cant seem to check if the user is logged in before displaying other pages.

the checklogin script is
code:
<?php
$username = "";
$password = "";
$db_name = "";
$host="localhost"; 
$tbl_name="Users"; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword'];

// Encrypt Password
$encrypted_mypassword=md5($mypassword);

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$encrypted_mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword"); 
header("location:login_success.php");
}
else {
echo "Wrong Username or Password <br><br>";
echo '<a href="http://www.moneyspiderdesign.com/BMC/main_login.php">Try Again</a>';
}
?>

This is the login_success.php
code:
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>

<html>
<body>
You are logged in!
</body>
</html>
The script at the top of the 'restricted' page is
code:
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
I am sure I am missing something... Should there be a step in login_succes.php where I set session as registered?

-JS-
Jun 1, 2004

Find a new script (maybe something from here) - that one is horrible:
  • session_is_registered() is deprecated and removed in PHP 5.4, so your code won't work on an up to date server.
  • mysql_ functions are deprecated - use PDO
  • Use parameterised queries - PDO
  • Passwords should be salted and hashed (not with md5) - see here

-JS- fucked around with this message at 13:51 on Dec 7, 2014

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:

-JS- posted:

that one is horrible

This is the problem I am having. I want to learn from tutorials but all the ones I find are outdated or 'horrible' and I dont know as I am learning...

Any good tutorial resources for learning this stuff?

Reading up on that list though so thanks!

Experto Crede
Aug 19, 2008

Keep on Truckin'

musclecoder posted:

What would correct output look like? Are you just trying to iterate over an array and remove the empty values? The code you have really looks like overkill.

Looking at it again, I end up with an output like this:

code:
Array
(
    [Number] => 01234567890
    [Ext] => 3019
)
But what I want is this:

code:
Array
(
        [Number] => Array
        (
                [0] => 01234567890
                [1] => 09876543210
        )
        [Ext] => Array
        (
                [0] => 3019
                [1] => 3001
        )
)
I've updated my loop to be this:

code:
foreach($new as $k => $i){
        preg_match('/[0-9]{4}/', end($i), $ext);
        $numbers = key(preg_grep("/,/", $i));
        $data = array("Number"=> $i[$numbers+1], "Ext" => $ext[0]);
}
But still no joy. If there's more than one entry in $new it only has the last one, which is making me think it is looping correctly, but overwriting the array contents?

EDIT: For gently caress's sake, I was missing something obvious. Changed the $data line to start with $data[] and it works.

Experto Crede fucked around with this message at 17:54 on Dec 7, 2014

o.m. 94
Nov 23, 2009

thegasman2000 posted:

This is the problem I am having. I want to learn from tutorials but all the ones I find are outdated or 'horrible' and I dont know as I am learning...

Any good tutorial resources for learning this stuff?

Reading up on that list though so thanks!

This is a good start,

http://www.phptherightway.com/#databases

I'm going to assume the code you're doing is just for learning, because currently, your entire database can be dropped with a simple POST variable... it's worth trying to do best practices, even if it takes longer. Eventually you'll end up using a framework that handles all this for you, anyway.

o.m. 94 fucked around with this message at 14:45 on Dec 11, 2014

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I'm getting back into PHP after a seven year break and I'm curious to know what is everyone's favorite PHP IDE? After some cursory googling I think I've narrowed down my choices to Blumentals Webuilder (my preferred IDE back in the day :corsair:), PHP Tools for VS 2012, and maybe Sublime. I don't have any practical experience with those last two, though, so I'm hoping I can narrow down my choices (or pick up some new ones) based on your guys' experiences.

And thanks for linking to this. The last PHP version I coded for was 5.2 and needless to say I'm surprised at how far PHP has come since then. I'll definitely be giving this a read-through just to make sure I don't do anything stupid (like use the familiar but now deprecated mysql_ functions :v:).

IAmKale fucked around with this message at 19:05 on Dec 18, 2014

spiritual bypass
Feb 19, 2008

Grimey Drawer
There is no tool but PHPStorm/IntelliJ.

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

rt4 posted:

There is no tool but PHPStorm/IntelliJ.

Agreed, I exclusively use IntelliJ now and love it.

down with slavery
Dec 23, 2013
STOP QUOTING MY POSTS SO PEOPLE THAT AREN'T IDIOTS DON'T HAVE TO READ MY FUCKING TERRIBLE OPINIONS THANKS

rt4 posted:

There is no tool but PHPStorm/IntelliJ.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

rt4 posted:

There is no tool but PHPStorm/IntelliJ.

Yeah, let me quote this again. It even runs well on a mac which is surprising to me since pretty much every other java app I try is total poo poo. The config is a little convoluted for certain things, but otherwise its awesome.

Sublime is always handy though, not for direct coding preset, but its so drat nice to be able to take a bunch of text, create a vertical cursor 100 lines tall, then add a comma to the end of each line with a single keypress.

revmoo
May 25, 2006

#basta
I really liked Zend IDE after using it for a while. Now it seems like everyone's on PHPStorm. TBH though I run Vim and have for a number of years since. Nothing beats the keyboard shortcuts, except maybe an IDE with Vim mode, but the thing I really like about it is the fact that I can fullscreen Vim on my vertical monitor and get 155 lines of text with no borders, menus, scrollbars, or other distractions.

spiritual bypass
Feb 19, 2008

Grimey Drawer

Begby posted:

Sublime is always handy though, not for direct coding preset, but its so drat nice to be able to take a bunch of text, create a vertical cursor 100 lines tall, then add a comma to the end of each line with a single keypress.

Woe to the unbeliever

http://blog.jetbrains.com/idea/2014/03/intellij-idea-13-1-rc-introduces-sublime-text-style-multiple-selections/

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

thegasman2000 posted:

This is the problem I am having. I want to learn from tutorials but all the ones I find are outdated or 'horrible' and I dont know as I am learning...

Any good tutorial resources for learning this stuff?

Reading up on that list though so thanks!

PDO really isn't that hard. There are some good libraries that use PDO as well. I am a fan of the Zend_DB_Adapter_Pdo_Mysql library (although I am sure a lot of people will vocally disagree with me about the usability of anything in the Zend framework, and there are a lot of good reasons for that).

I usually extend the adapter with a new class for a repository, but you could use it directly like his
php:
<?

$config = array ( .. login stuff.....)
$db = new Zend_Db_Adapter_Pdo_Mysql($config);

// simple grab some records
$idValue = 3;
$sql = "SELECT someFields FROM myTable WHERE tableId = ?";

// here $idValue gets stuck in the question mark above
$results = $db->fetchAll($sql, $idValue);

// next, let's start a transaction, do an insert, then commit it

// This is an array of values, the key is the field name in the database
$bind= array(
 'Name' => 'Begby',
 'Description' => 'Awesome',
 'Age' => 93
);

$db->beginTransaction();
try
{
    $db->insert('someTable', $bind);
     $newId = $db->LastInsertId();
    $db->commit();
}
catch (Exception $e)
{
     $db->rollBack();
    throw new MyException("OMG!", $e);
}
?>
Hopefully thats not too hard to follow. Its certain more readable than the old mysql functions.

That being said, you should really learn PDO by itself without using a library such as the above first. Its really helpful to know how it works first hand so you aren't just relying on someone else library to do everything.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

rt4 posted:

There is no tool but PHPStorm/IntelliJ.
Based on the almost unanimous praise I'll bump PHPStorm to the top of the list. I'm a little worried that it's based on IntelliJ though - Android Studio is as well and holy poo poo can that thing gobble up RAM. When I'm doing Android Development it's not uncommon for AS to take up over 1.5GB of RAM - does PHPStorm act the same way? It's not usually a problem with 8GB of RAM but when you throw a dozen Chrome tabs into the mix I start to worry that things will drag once paging occurs.

My next question is, is there a PHP framework with decent multilanguage support, particularly when outputting front-end stuff? By that I mean I'd like to be able to easily manage two languages' worth of UI strings and switch between them with ease. I'll be developing applications for use in linguistically disparate countries for the foreseeable future so I'd like to start with that in mind rather than try to shoe-horn in multiple language support later on down the line.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

Karthe posted:

My next question is, is there a PHP framework with decent multilanguage support, particularly when outputting front-end stuff? By that I mean I'd like to be able to easily manage two languages' worth of UI strings and switch between them with ease. I'll be developing applications for use in linguistically disparate countries for the foreseeable future so I'd like to start with that in mind rather than try to shoe-horn in multiple language support later on down the line.

I can't recommend an IDE - I prefer vim for everything.

Symfony has particularly good i18n support - http://symfony.com/doc/current/book/translation.html

PHP itself has improved dramatically over basic gettext integration with the Internationalization library - http://php.net/intl

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

Karthe posted:

Based on the almost unanimous praise I'll bump PHPStorm to the top of the list. I'm a little worried that it's based on IntelliJ though - Android Studio is as well and holy poo poo can that thing gobble up RAM. When I'm doing Android Development it's not uncommon for AS to take up over 1.5GB of RAM - does PHPStorm act the same way? It's not usually a problem with 8GB of RAM but when you throw a dozen Chrome tabs into the mix I start to worry that things will drag once paging occurs.

PHPStorm and IntelliJ use up quite a bit of memory. I've got 8 gigs of ram on my laptop (Lenovo w520) and I usually have 2 or 3 vagrant instances running and 2 to 4 IntelliJ projects open and never really have any performance issues with Windows 7 64-bit.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
RAM is so cheap. Between running VMs and IDEs I wouldn't take anything less than 16GB on my dev machine.

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

fletcher posted:

RAM is so cheap. Between running VMs and IDEs I wouldn't take anything less than 16GB on my dev machine.

Too true. Turns out I have 16gb and didn't know it ;)


2x IntelliJ Idea
14x Chrome tabs
github
sourcetree
mirc
itunes
outlook
3x putty
3x vagrant vms

DarkLotus fucked around with this message at 21:26 on Dec 19, 2014

0zzyRocks
Jul 10, 2001

Lord of the broken bong
Echoing the PHPStorm praise. I've been using it for about a month and a half and aside from the memory-hog, it's a solid IDE that makes many tasks much easier. Lets you focus on getting the work done rather than little poo poo like finding a class definition and opening that file.

Mortanis
Dec 28, 2005

It's your father's lightsaber. This is the weapon of a Jedi Knight.
College Slice
This is a Laravel specific question, so I hope I can get some help here.

I'm using Laravel 5 and pushing files to Amazon S3 using the new integrated alternative filesystems that can be optionally added in. I'm using it for a pet project to upload files to the server (authed members only) and then push them to S3, making sure that only authed members can retrieve them. It actually works great for the most part, except as far as I can tell the Put() method just saves the string contents directly. Fine for small files, but I'm moving PDFs and larger images, which now involves uploading them to the server, opening them for read, reading to end of file, dumping the contents into a variable and streaming that into Put(). On a 1GB Digital Ocean VM, PHP immediately goes out of memory if the file is over 75MB. I can see this in the Laravel log files and watching top - I've updated all the PHP file max file upload size and nginx restrictions. PHP just gobbles up nearly a gig of memory uploading the file to the server and streaming it into memory and then streaming it to S3.

It's clunky and hasn't been refactored out of the Controller yet while I test it, but here it is:

http://pastebin.com/TPCKSALH

It's this package here: https://github.com/aws/aws-sdk-php-laravel based on what I found using Laracasts here: https://laracasts.com/series/whats-new-in-laravel-5/episodes/6

It DOES work, it just chews through memory and it doesn't seem like I can push whole files to Amazon S3 via the package. If I could just opt to Move() to the S3 bucket instead it would be great, but I'm not seeing a method that looks viable here.

Mortanis fucked around with this message at 05:50 on Dec 31, 2014

Depressing Box
Jun 27, 2010

Half-price sideshow.
To avoid loading everything into memory you'll want to use streams instead of read/put. Check the docs for your filesystem library of choice and look for code using fopen/fclose.

I don't know about streaming directly from a browser to S3, though. At that point maybe you want to look into multipart file upload.

spacebard
Jan 1, 2007

Football~

Depressing Box posted:

To avoid loading everything into memory you'll want to use streams instead of read/put. Check the docs for your filesystem library of choice and look for code using fopen/fclose.

I don't know about streaming directly from a browser to S3, though. At that point maybe you want to look into multipart file upload.

It looks like the Laravel library uses aws/aws-sdk-php. The steam wrapper used file_get_contents but the docs at https://github.com/aws/aws-sdk-php/blob/master/docs/service-s3.rst recommend to use multipart file upload for large files. Not sure if the Laravel library supports that though.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
I got a new job! And they actually know what they're doing! I've inherited a project written pretty well using the Zend Framework, and they want to document it. They want a UML diagram of it. What's the best program to do this that might be "Zend aware"? I guess I mean, I don't want it to include every tiny piece of Zend, because that's not needed, just the pieces that we actually work on.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

Golbez posted:

I got a new job! And they actually know what they're doing! I've inherited a project written pretty well using the Zend Framework, and they want to document it. They want a UML diagram of it. What's the best program to do this that might be "Zend aware"? I guess I mean, I don't want it to include every tiny piece of Zend, because that's not needed, just the pieces that we actually work on.

If you want a basic class hierarchy and some UML-ish diagrams, you might want to look into Doxygen.

stoops
Jun 11, 2001
I'm not sure the easiest way to do this. Any help is appreciated.

I have an array of dates and targets, sorted by date. As you can see, there may be more than one target with the same name. I'm looking to create the array again, but with only one of the target names listed by the earliest date shown.

So this,

code:
array(
	(int) 0 => array(
		(int) 0 => array(
			'yyyymmdd' => '1999-10-05'
		),
		'Catalog' => array(
			'TargetName' => 'Dallas'
		)
	),
	(int) 1 => array(
		(int) 0 => array(
			'yyyymmdd' => '2012-11-08'
		),
		'Catalog' => array(
			'TargetName' => 'Austin'
		)
	),
	(int) 2 => array(
		(int) 0 => array(
			'yyyymmdd' => '2012-11-09'
		),
		'Catalog' => array(
			'TargetName' => 'Austin'
		)
	),
	(int) 3 => array(
		(int) 0 => array(
			'yyyymmdd' => '2012-12-30'
		),
		'Catalog' => array(
			'TargetName' => 'Austin'
		)
	),
	(int) 4 => array(
		(int) 0 => array(
			'yyyymmdd' => '2012-12-31'
		),
		'Catalog' => array(
			'TargetName' => 'San Antonio'
		)
	),
	(int) 5 => array(
		(int) 0 => array(
			'yyyymmdd' => '2014-01-22'
		),
		'Catalog' => array(
			'TargetName' => 'San Antonio'
		)
	)
)
becomes this:

code:
array(
	(int) 0 => array(
		(int) 0 => array(
			'yyyymmdd' => '1999-10-05'
		),
		'Catalog' => array(
			'TargetName' => 'Dallas'
		)
	),
	(int) 1 => array(
		(int) 0 => array(
			'yyyymmdd' => '2012-11-08'
		),
		'Catalog' => array(
			'TargetName' => 'Austin'
		)
	),
	(int) 2 => array(
		(int) 0 => array(
			'yyyymmdd' => '2012-12-31'
		),
		'Catalog' => array(
			'TargetName' => 'San Antonio'
		)
	)
)

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

Iterate through the array and keep track of the earliest element for each name? If you don't care about the original order of entries, this does that:
PHP code:
$nameToEarliestElement = array();
foreach ($allElements as $element) {
    $myName = $element['Catalog']['TargetName'];
    $myDate = $element[0]['yyyymmdd'];
    if (isset($nameToEarliestElement[$myName])) {
        $itsDate = $nameToEarliestElement[$myName][0]['yyyymmdd']
        if (strtotime($myDate) < strtotime($itsDate)) {
            $nameToEarliestElement[$myName] = $element;
        }
    } else {
        $nameToEarliestElement[$myName] = $element;
    }
}

$earliestElementsWithUniqueNames = array_values($nameToEarliestElement);

o.m. 94
Nov 23, 2009

When faced with an algorithm, just try playing it out as if you were manually tasked with the problem. This is assuming I interpreted the problem correctly...

You'd start stepping through each array entry.
You'd also have a list of arrays you had encountered, which would be empty at first.
Every time you stepped to an array, you'd check if the name part was on your list.
If it wasn't, you add it to your list and move to the next entry.
If it was, you'd check if the one on your list was more recent.
If it was, you'd move on to the next entry.
If it wasn't, you'd replace the one on your list with the new one and move on to the next entry.

Writing it out like this is a good way to understand the problem, and it makes implementing it much easier. This isn't optimal, but it's a start.

o.m. 94 fucked around with this message at 19:05 on Jan 15, 2015

stoops
Jun 11, 2001

The Laplace Demon posted:

Iterate through the array and keep track of the earliest element for each name? If you don't care about the original order of entries, this does that:


o.m. 94 posted:


Writing it out like this is a good way to understand the problem, and it makes implementing it much easier. This isn't optimal, but it's a start.


I appreciate guys. The code worked and thanks for the advice o.m. Your pseudocode (is that what it's called) makes alot of sense.

revmoo
May 25, 2006

#basta

stoops posted:

I appreciate guys. The code worked and thanks for the advice o.m. Your pseudocode (is that what it's called) makes alot of sense.

Yep. Very useful. One thing I often do is write out the logic line by line as comments and then work my way though writing lines of code and deleting the comments as I go.

Adbot
ADBOT LOVES YOU

DholmbladRU
May 4, 2006
Ive accomplished this with Spring framework, however now I am tasked with this same functionality but in Kohana PHP. Looking to protect a site by implementing some authentication and session. When the user accesses this system they will pass a token with the request through the URL. This token will be read and it will make a web service call to ensure its valid. If its valid they will be redirected to the application. If not it will direct them to error page.

Can anyone direct me to samples for this type of functionality? I looked at the AUTH module for kohana, but I dont think thats what I am looking for.

Okay so maybe I get some token from the url and store it in a session parameter, and the protect each request by checking the token. Would go further by validating the token against the web service first.

If this even close to the right approach? ?

php:
<?
    public function before(){
             parent::before();
        session_start();

        if(!isset($_SESSION['token'])){
             $_token = $_SESSION['token'] = $this->request->query('token'); 
             //maybe validate the token here
          }

      


       if(isset($_SESSION['token'])){
          $view = View::factory('home/index');
          $this->template->content = $view;
          $this->_post = $this->request->post();
       } else {
        echo 'inside else';
           header('HTTP/1.0 403 Forbidden');
           $this->request->headers['HTTP/1.1'] = '403';
           die('You are not allowed to access this file.');     
      }
        

       }
?>

DholmbladRU fucked around with this message at 06:59 on Jan 17, 2015

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply