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
Masked Pumpkin
May 10, 2008
I working on storing information in a text file rather than a database, and reading it into an array with file(). The information looks something like this (it's a very small array used to create a dropdown menu):
code:
ID - MenuLinkID - Name - Position - URL
0    1            Test   1          [url]http://someurl.com[/url]
1    1            Test2  2          [url]http://anotherurl.com[/url]
2    2            Test3  1          [url]http://goatse.cx[/url]
I'm sure there's a better way to do this, but I've effectively copied my code from the database driven one already done and fudged it together to do much the same with text files instead.

The problem is that if I want to change the position of the rows for a given MenuLinkID, a simple foreach loop will change the values, but file() will still read it in the order it gets fed, and I need to change that (hell, possibly doing away with the position field altogether). A glance at sorting options in PHP reveal a number of options, but I don't see any clear way to do an associative sort of the array by a given index, and ensuring that that sort only applies to rows with the same MenuLinkID

Of course I could use the same foreach loop mentioned earlier to just swap the values of the rows in question, which does the trick but seems unnecessarily wasteful - for such a small array it's probably not a huge concern, but I'd rather do it the right™ way - any ideas?

Adbot
ADBOT LOVES YOU

Masked Pumpkin
May 10, 2008

Hammerite posted:

I don't understand why you need to do this with a text file rather than a database, but suppose for the sake of the problem there is a good reason.

What is the ID "column" for? Is it used for anything? If you got rid of it and stored the rows in the form
code:
MenuLinkID - Position - Name - URL
instead, that would mean they'd already be stored in a sensible order, right? This is just the image in the new problem domain of making (MenuLinkID, Position) the primary key of your database table of list entries, in place of an artificial ID column.

Alternatively, why don't you comma-separate the columns in the text file (or separate them using some delimiter you will never put into the names or URLs), then you can go through and explode() the entries in the array returned by file(), and sort() them more or less easily.

Sadly I had the database system up and running, and due to some other random stuff I was doing working with files, I set it for myself as a cool little project to learn about an aspect of PHP I've never really used before.

Because the whole thing here is web based, handled with a combination of GET and POST requests for different options (like changing the position of an item), having an ID for each item is necessary so that I know which item I'm actually meant to be changing.

The code I gave you was just a representation of the array, the file itself has all the values separated by '||' and with a new line for each new row. file() and explode() then return the values in an array that I can work with.

Hammerite posted:

Do you need to ensure that? If you sort() by position then yes, within position-groups there will be a jumble of rows with different MenuLinkIDs, but I assume that at some point you have a loop that builds up the drop-down list, or echoes it item-by-item or something. You could just add an if statement to the loop to make sure only the appropriate rows are treated.

This is a drat good idea - I hadn't thought of that at all. The question then is how I can sort by the position field instead of the normal index - I'm not seeing anything standing out in the documentation.

Masked Pumpkin
May 10, 2008
Of course, now I understand how that sort works - the manual and examples given left me a bit confused. Thank you, kind sir!

I'm still a much bigger fan of databases - they're there exactly so I don't have to fiddle through text files, and ORDER BY clears up sorting problems, but I can see myself finding this useful at some point, I guess.

Masked Pumpkin
May 10, 2008

rt4 posted:

It looks like you already have a working solution in place, but I suggest you take a look at
[*]SQLite

There is not a big enough :doh: to describe this - it's enabled by default in PHP, so it's pretty much available on any server I might have to work on! I considered a small single file database, since I've used it before with great success, but I couldn't remember the name, and thought it might have been tinydb (it wasn't) but this... :doh:

I've still learned a lot about file management, which was the goal, and XML does seem like a great idea for the next step, so I'll do that, thanks.

Still... :doh: :doh: :doh:!

Masked Pumpkin
May 10, 2008

ODC posted:

It was working fine until last night when all of a sudden it started sending multiple duplicate e-mails. Has anyone seen this?

My guess could be either, as gwar3k1 said, a user refreshing the page too quickly, or possibly some problem on the mail side with that server.

However, it seems as though that your mail function so far seems to be trying to send two messages - one ($send) with To, Subject, Body and Headers, and then another ($send2) with From, Subject, Autoreply and Headers. Mail should always at least have a From specified, though this can be set by default in php.ini, and so it's possible that the mail is being sent twice, albeit with slightly different information in each message.

I'd recommend something like the following:
php:
<?
if(!filter_var($from, FILTER_VALIDATE_EMAIL)) {
    print "You have not entered a valid email address, please go back and try again";
} 
else 
{ 
    $headers = "From: ".$from."\r\nReply-To: ".$autoreply;
    //I'm not sure if you have extra header information to insert here
    $send = mail($to, $subject, $body, $headers); 
    if($send) {
        header( "Location: [url]http://www.[/url]" );
    } 
     else {
        print "We encountered an error sending your mail, please notify membership@_______.com";
    } 

}
?>
I've also had great success with GETs on the redirected page, so you could enter the page to go to on success as index.php?email=1 for success or index.php?email=0 for failure, and have the page check for the existence of $_GET['email'] and echo an 'email sent' or 'email failed' as appropriate.

Of course, if you're going down that route, since you're getting the important information (perhaps just the email address), or whatever else POSTed to you anyway, you could redirect them back to the page with the email form on failure, and fill in the information they have already tried to submit to save them the hassle of doing it again.

Edited to fix a missing bracket

Masked Pumpkin fucked around with this message at 15:02 on May 16, 2010

Masked Pumpkin
May 10, 2008

wins32767 posted:

I have an issue where on one machine a require_once works fine, but on another it can't find the file. php.ini has one include_path, but the error message has a different one. As far as I can tell it's not being set in .htaccess files, so I'm at a bit of a loss. Any ideas as to where to look?

It's an outside guess without seeing any code, but have you checked the permissions for the files on the server? If you just drop the file in the same directory as the script (and change the path appropriately), can you see it then?

Masked Pumpkin
May 10, 2008
It probably doesn't even need to be said, but I assume you're validating your inputs, right? $var = htmlentities($var, ENT_QUOTES) works pretty well for me, but if there are better options available, I'd be interested in hearing them.

Masked Pumpkin
May 10, 2008

DholmbladRU posted:

Okay, I got the seperate forms all worked out. Now what I am doing is echo infromation from the database into a table on the same page which a user can update his profile.

Is there a way to make it so the page does not have to be manually refreshed, and will update the table.


"to display the webpage again internet explorer needs to resend the information you've previouslly submitted"

This message pops up when I manually refresh the page.

Your best bet would be to look into ajax if you don't want to refresh the page, though that can be quite daunting at first glance. For such a simple task, this might help.

Masked Pumpkin
May 10, 2008
It's not exactly a php question per se, but I'm trying to find the best way to address this in PHP:

I'm doing up a program to handle scheduling for a setup managing adverts. This means that an entire day has to be broken up into 10 second segments, with long, feature length items and then some short adverts - with the option to move these around if necessary. At first I considered setting up the appropriate table with an entry for each 10 second gap (longer features could span multiple rows), but discarded this a it led to massive tables and slow db access times. I then considered simply using a text field, writing the times and items to play into there, and processing the information accordingly when it came in or out.

I then ran into the problem of displaying this information nicely on the scheduling page - pretty much any way I do it, that many segments ends up scrolling across the page, even at a high resolution. I'd use GD to generate a nice image representing the data, but then moving items around becomes problematic.

Ultimately, I can make it all work with tables and forms, but I can't help but feel I'm missing some better way of doing this, and am at a loss. Any ideas?

Masked Pumpkin
May 10, 2008

N.Z.'s Champion posted:

Well if you're displaying one day then 10 second segments could be 6*60*24=8640 rows so how do you expect to present that in a user interface? It's almost like you want to deal with groups of information at different resolutions of detail.

As far as storing events (timestamp+duration) in a database then I've used Postgres 8.4 with timestamps and intervals. You can then select an event and join its timestamp against a dynamically generated table of dates at an arbitrary resolution by using generate_series().

I don't know if this is the most efficient way of doing it but it's fast enough for me.

Those are some great points - Breaking down the times into smaller sections (and hell, using GD to give birds eye view of larger segments of data) would work well as although it might require more page refreshes, these could at least be done reasonably quickly.

I'm using MySQL, but it appears that it also allows date calculations as you've described, which would be more sensible than trying to run the same processes through PHP - though I will have to study up on it, as it's not something I've ever considered doing with a database before.

Thank you for your help!

Masked Pumpkin
May 10, 2008

Iron Squid posted:

I'm working on a small script for a website. Its my first PHP project, and I need some advice.

I have a sign-up form that the user can enter some information. I'd like to spread this info out over several pages. Basically, the user enters a small bit of info, clicks next, and enters more info. Repeat until all info is collected.

Should I have one php script do this, or should each page have its own php script?

You could do it all in one page, and I'd say that's probably the simplest option code-maintenance wise - I'd say have the <form> action equal to './thispage.php?Page=2', and read in that $_GET value to determine what to ask the user next. The method of the form would still be POST, and you can drop all of that info into their $_SESSION, which you'll need to session_start() before you send any output to the browser.

The most obvious caveat is to sanitise ALL of the $_POST or $_GET variables you get from the client, especially before putting them into the database.

Masked Pumpkin
May 10, 2008
So I'm working on a database project which involves multiple calls to a database to fetch (reasonably small) amounts of data at a time. Since a lot of these calls can become repetitive, is it not faster to load the data into arrays in PHP and then query those arrays before reverting back to the database for additional information? In addition, what is the best way to time the speed of execution for PHP? It'd be useful to see for myself where I might be able to make things tick a little faster.

Masked Pumpkin
May 10, 2008
So I'm thinking that there must be a better way to approach a problem.

I have a number of remote systems uploading (zipped) log files by ftp. I'm setting up a cron job on my server to check the log directory every minute to check every file in it, unzip and insert into the db. I'm doing sanitisation and discarding invalid zip files - since the files get uploaded over temperamental connections, incomplete uploads are not uncommon and not a big problem - but I would like to ensure that files are properly uploaded before trying to open or work with them so that my own script doesn't cause problems with the logging process.

The way I see it, I can either have the script check the file timestamp and only work on the file after two or three minutes, I could use a separate table to monitor timestamps and file size and work from there, or I could only discard the zip as bad after two or three attempts, though I don't know how file locking may affect that.

Ultimately, I feel like I'm missing some much simpler option. While I'd rather not open up php to exec() functions for security reasons, it's a virtual server so I can handle things at a shell level and move only known good files to the directory for php to check. Any ideas?

Masked Pumpkin
May 10, 2008
I appreciate that this may start a derail, but if you're just getting into PHP, using a good editor like Notepad++ instead of plain old notepad can help a lot.

If you're just getting into PHP and have questions, I'd say that's exactly what this thread is for - good luck!

Masked Pumpkin
May 10, 2008

itskage posted:

I have a tutorial I give to new hires for setting up nginx+php on windows, with VSCode and the PHP extensions for debugging in VSCode, PHP Unit, Composer, NPM and Webpack (and now with setting up PHP CS+MD thanks to this thread). I'll have to remove some company specfic stuff from the thread, but if anyone's interested I can post it here.

PHP in VSCode does have some issues where it "jams" up when debugging and it's trying to lint with CS or MD. But usually you just hit stop and restart the debugger.

I interested - hit us up 🙂

Edit: Seriously, I've been using Notepad++ for ages now - Aptana failed after not supporting PHP7, if there's a good IDE I'd like to hear about it!

Masked Pumpkin fucked around with this message at 21:50 on Mar 20, 2018

Masked Pumpkin
May 10, 2008

itskage posted:

:words: Fantastic Advice™ :words:

This is a Good Post™ - thank you! I've always been leery of running PHP locally since I've got dev and prod servers I work off of, but having PHP running locally for error checking makes sense.

Edited for brevity since the original post is right above this one and this isn't the old E/N.

Masked Pumpkin fucked around with this message at 17:19 on Mar 28, 2018

Masked Pumpkin
May 10, 2008

cheese-cube posted:

Someone add that to the op it's great. Btw Masked Pumpkin you don't have to quote posts in their entirety, that's why :words: exists, a fun placeholder.

Good point - fixed :)

Adbot
ADBOT LOVES YOU

Masked Pumpkin
May 10, 2008

Kraus posted:

I'm a huge dork who is a fan of Star Trek and has a degree in linguistics. So, I built a file that outputs every possible syllable of Klingon. I am also a masochist who likes trying to write files in as few lines/functional blocks as possible. Does anyone know a way I could do this with less? I think I'm at the end of my creativity here.

Basically, there's three arrays of characters, and the file puts together every logically possible combination of those characters. Then, it asks, "Is the substring "ow" or "uw" present?" If so, echo the empty string. If not, echo the combination you're currently on.


This is for funsies, so please offer your most absurd suggestions.

code:


<?php

//All the possible onsets, nuclei, and codas. To produce the CV syllables without a separate loop, we add the empty string to the list of codas. 
		
		$onsets = array("p", "t", "q", "'", "b", "D", "tlh", "ch", "Q", "j", "S", "H", "v", "gh", "m", "n", "ng", "w", "r", "l", "y");

		$nuclei = array("a", "e", "I", "o", "u");

		$codas = array(" " , "p", "t", "q", "'", "b", "D", "tlh", "ch", "Q", "j", "S", "H", "v", "gh", "m", "n", "ng", "w", "r", "l", "y", "w'", "y'", "rgh");
		
		
	//We loop through all the logical possibilities, and if the illicit sequences /ow/ or /uw/ would happen, they don't. 

		for ($i = 0; $i < 21; $i++) {
			
			for($j = 0; $j < 5; $j++) {
				
				for($k = 0; $k < 25; $k++) {
					
					echo ($syl = $onsets[$i] . $nuclei[$j] . $codas[$k] . "<br>") && (strpos($syl, "ow") || strpos($syl, "uw")) ? "" : $syl;
					
				} //k-loop
				
			} //j-loop
			
		} //i-loop



EDIT:

Welp, I at least managed to use only one array:

code:

<?php

$sounds = array(" " , "p", "t", "q", "'", "b", "D", "tlh", "ch", "Q", "j", "S", "H", "v", "gh", "m", "n", "ng", "w", "r", "l", "y", "w'", "y'", "rgh", "a", "e", "I", "o", "u");

for ($i = 1; $i < 22; $i++) {
	
	for ($j = 25; $j < 30; $j++) {
		
		for ($k = 0; $k < 25; $k++) {
			
			echo ($syl = $sounds[$i] . $sounds[$j] . $sounds[$k] . "<br>") && (strpos($syl, "ow") || strpos($syl, "uw")) ? "" : $syl;
			
		} //k-loop
		
	} //j-loop
	
} //i-loop


Wow. Ok, so the code (at first glance) looks fine, but it's quarter to eleven on a Sunday night here and I just realised that this is way too much for me to deal with right now.

Hope your code works.

Dork.

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