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
spacebard
Jan 1, 2007

Football~

Sab669 posted:

I started using Netbeans instead of N++. I don't think it was underlined in yellow, but maybe it was. loving impossible to notice yellow underlining on a white background through. I suppose there would've been a notification flag in the line-number section... But yea; pretty sure there was no "heads up" :(

I thought that Netbeans would do this, but I guess it doesn't out of the box. phpcs (with PSR2 standards set) doesn't catch it either... PHPStorm does have a setting for it though.

Adbot
ADBOT LOVES YOU

Luxury Communism
Aug 22, 2015

by Lowtax

Grump posted:

EDIT: Post about a delete function. I ended up making unique pages for each row in my table and then adding a delete button on each page.

I originally wanted to list them all and have a delete button next to each item in the list, but I decided that was over my head, so I did it this way instead.

Hey! I'm getting better at PHP CRUD!

PHP code:
//Delete function. Grabs the id from the url then compares it to the id in the row 
//and deletes the appropriate row
function delete_word(){
	global $connection;
	$url_id = $_GET['id'];
	$query = "DELETE FROM words WHERE id = '".$url_id."'";
	if(mysqli_query($connection, $query)){
		echo "Deleted!";
		echo ("<SCRIPT LANGUAGE='JavaScript'>
    window.alert('Succesfully Updated')
    window.location.href='index.php';
    </SCRIPT>");
	}
	else{
		echo "ERROR";
	}
}

In addition to needing to sanitize $url_id as someone above mentioned, it's probably better to write the function as delete_word($id) and not access the superglobal directly in the function body. (for reuse)

Also, GET requests should always be safe (i.e. have no serious side-effects) as user-agents are allowed to issue "spurious" GET requests for pre-loading purposes and for caching purposes an http client may not even issue a request to the origin server at all! You want to use POST here.

Luxury Communism fucked around with this message at 00:38 on Feb 16, 2017

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Scaramouche posted:

This is a dumb question, but I have a wordpress plugin that has since updated and says that it no longer supports PHP 5.2 and under. I checked my phpinfo and it says 5.4.45, which theoretically checks out. However the impression I get is "if not compatible with 5.2 then it's 7.0 only"; am I safe to upgrade this plugin, or do I have to upgrade to PHP 7?

If it says it no longer supports 5.2 or under, you should assume that they mean 5.3 and higher, not 7.0 and higher. You should be fine but you should also shoot an email off to the plugin author asking them to clarify the requirements for everybody.

spiritual bypass
Feb 19, 2008

Grimey Drawer
Yeah that's probably a euphemism for "namespaces"

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

McGlockenshire posted:

If it says it no longer supports 5.2 or under, you should assume that they mean 5.3 and higher, not 7.0 and higher. You should be fine but you should also shoot an email off to the plugin author asking them to clarify the requirements for everybody.

Thanks, I'd already done that but was getting antsy about waiting for a response (still waiting...) so thought I'd post it here.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

rt4 posted:

The most important thing about that code sample is that it takes user in put from $_GET['id'] and sticks it directly into a query. You need to use a parameterized query to prevent a malicious user from carrying out an SQL injection attack.

http://php.net/manual/en/pdo.prepare.php

So something like this? I don't need to fetch or bind my results since I'm deleting, correct?

I kinda understand, but the documentation isn't doing a great job of explaining why this is protecting against malicious attacks.

e: I'll probably get around to playing with PDO after I complete this CRUD app. Just wanna get some basic understanding down first.

PHP code:
function delete_word(){
	global $connection;
	$url_id = $_GET['id'];
	if ($executed = mysqli_prepare($connection, 'DELETE FROM words WHERE id =?')){
		//binds parameters for markers (i=integer)
		mysqli_stmt_bind_param($executed, "i", $url_id);
		//execute the query
		mysqli_stmt_execute($executed);
		//close statement
		mysqli_stmt_close($executed);
	}
}

teen phone cutie fucked around with this message at 22:35 on Feb 20, 2017

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Grump posted:

So something like this? I don't need to fetch or bind my results since I'm deleting, correct?
Yes, only you also need to check that the query executed successfully. mysqli_stmt_execute returns a boolean.

quote:

I kinda understand, but the documentation isn't doing a great job of explaining why this is protecting against malicious attacks.

Imagine a world where id = '1 OR 1 = 1'. If you were doing plain old string concat, your query would end up being DELETE FROM words WHERE id =1 OR 1 = 1. The "OR 1=1" clause will match every single row in the table.

With the prepared statement, the string '1 OR 1 = 1' would be filled in where the question mark is, complete with what are effectively quotes. Using prepared statements gives you a good degree of certainty that users will not be able to manipulate your SQL commands. (There are ways to gently caress up prepared statements with MySQL, but most of them rely on some pretty deep character encoding magic poo poo and you shouldn't worry about that quite yet. It's easy enough to defend against but there's an education barrier to doing it right.)

Further, if id is only and must only be a positive whole integer, you need to validate that separately. You should be passing the id to delete to the function, not have the function pull it out of $_GET, and the code doing the calling should be responsible for making sure that it's going to pass that function a positive whole integer.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

McGlockenshire posted:

Yes, only you also need to check that the query executed successfully. mysqli_stmt_execute returns a boolean.

So is this as simple as wrapping mysqli_stmt_execute in an "if" statement?

McGlockenshire posted:

Imagine a world where id = '1 OR 1 = 1'. If you were doing plain old string concat, your query would end up being DELETE FROM words WHERE id =1 OR 1 = 1. The "OR 1=1" clause will match every single row in the table.

With the prepared statement, the string '1 OR 1 = 1' would be filled in where the question mark is, complete with what are effectively quotes. Using prepared statements gives you a good degree of certainty that users will not be able to manipulate your SQL commands. (There are ways to gently caress up prepared statements with MySQL, but most of them rely on some pretty deep character encoding magic poo poo and you shouldn't worry about that quite yet. It's easy enough to defend against but there's an education barrier to doing it right.)

Further, if id is only and must only be a positive whole integer, you need to validate that separately. You should be passing the id to delete to the function, not have the function pull it out of $_GET, and the code doing the calling should be responsible for making sure that it's going to pass that function a positive whole integer.

Thanks. This is super helpful. I have never been able to wrap my head around SQL injections

teen phone cutie fucked around with this message at 18:09 on Feb 21, 2017

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Grump posted:

So is this as simple as wrapping mysqli_stmt_execute in an "if" statement?

More than that, you need to actually do something appropriate if executing the delete fails, in a place where it makes sense. For example, rolling back a transaction and logging the error, and/or complaining to the user, or doing something else that tries to gracefully recover from an operation that shouldn't have failed.

When driving, it's best practice to drive defensively. When doing defensive driving, you assume that every other driver can't see you and will make poor judgement calls. Defensive coding is a thing, too. Assume all your user input is tainted by maliciousness or stupidity, and assume every call you make outside your program can fail at any time for any reason. This means checking types, forcing validation, and always checking return values when operations can be successful or unsuccessful. This is a lot of work, but it puts you in a better place when one of those weird things that shouldn't fail finally fails and you've already tried to account for it. Deletes can fail. So can selects, and a select failing in a way that leaves an error code is some pretty serious poo poo.

quote:

Thanks. This is super helpful. I have never been able to wrap my head around SQL injections

You should look up XSS, "cross-site scripting" some time as well. It's the same idea applied to HTML output, only with the added horror of Javascript being possible. There are many, many more types of content injection attacks, and some are even worse than these, like header injection.

Validate and type check your inputs, properly escape your outputs, and talk to external services using the most safe method possible. The world is out to hack you.

McGlockenshire fucked around with this message at 18:58 on Feb 21, 2017

bigmandan
Sep 11, 2001

lol internet
College Slice
HTML Purifier is a decent library for sanitizing input and strips out most XSS content. Ideally you would sanitize the input with HTML Purifier, validate the sanitized input against some rules (valid ranges, format, etc..), and then store it in the database. Escaping output is ideal unless you are doing some sort of HTML based WYSIWYG editor.

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
Mail question! I've got this script:

code:
<?php 
foreach ($_POST as $param_name => $param_val) {
    $message .=  "$param_name ( $param_val )\r\n";
}

$headers = 'From: [email]no-reply@fakewebsite.org[/email]' . "\r\n" .
    'Reply-To: [email]no-reply@fakewebsite.org[/email]' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail ("name@fakewebsite.org","Form Submission", $message, $headers);

?>
It's emailing if I change "name@fakewebsite.org" to my Gmail address, but it won't email anything to an email on the same domain name as the site. I remember reading something about maybe it being an issue if the email and site are hosted with different hosts? I've fixed issues like this before with SMTP plugins for Wordpress, but this is the first mail script I'm troubleshooting. Any help would be appreciated!

McGlockenshire
Dec 16, 2005

GOLLOCKS!

BJPaskoff posted:

It's emailing if I change "name@fakewebsite.org" to my Gmail address, but it won't email anything to an email on the same domain name as the site. I remember reading something about maybe it being an issue if the email and site are hosted with different hosts? I've fixed issues like this before with SMTP plugins for Wordpress, but this is the first mail script I'm troubleshooting. Any help would be appreciated!

If you are using your domain's email, use the SMTP server provided by the host of the (MX records for the) domain.

If you are sending as a gmail address, use Google's SMTP servers. Using your gmail address as the From address, but sending through your host's servers will significantly increase the likelihood of your mail being flagged as spam by the recipients.

Never use mail(). It's poo poo. You can't troubleshoot it, you can't debug it, you can't control it, and when things go wrong like this, you are completely up a creek. Instead, use Swiftmailer if you can, but it's fine to use use PHPMailer if learning Swiftmailer seems overwheming.

McGlockenshire fucked around with this message at 22:50 on Feb 21, 2017

bigmandan
Sep 11, 2001

lol internet
College Slice

McGlockenshire posted:

If you are using your domain's email, use the SMTP server provided by the host of the (MX records for the) domain.

If you are sending as a gmail address, use Google's SMTP servers. Using your gmail address as the From address, but sending through your host's servers will significantly increase the likelihood of your mail being flagged as spam by the recipients.

Never use mail(). It's poo poo. You can't troubleshoot it, you can't debug it, you can't control it, and when things go wrong like this, you are completely up a creek. Instead, use Swiftmailer if you can, but it's fine to use use PHPMailer if learning Swiftmailer seems overwheming.

PHPMailer is pretty good and my goto for one off scripts, but it's definitely worth learning the API of Swiftmailer if you use any of the frameworks that use it as its core mail lib (Laravel, Yii, etc..)

Impotence
Nov 8, 2010
Lipstick Apathy

BJPaskoff posted:

Mail question! I've got this script:

code:
<?php 
foreach ($_POST as $param_name => $param_val) {
    $message .=  "$param_name ( $param_val )\r\n";
}

$headers = 'From: [email]no-reply@fakewebsite.org[/email]' . "\r\n" .
    'Reply-To: [email]no-reply@fakewebsite.org[/email]' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail ("name@fakewebsite.org","Form Submission", $message, $headers);

?>
It's emailing if I change "name@fakewebsite.org" to my Gmail address, but it won't email anything to an email on the same domain name as the site. I remember reading something about maybe it being an issue if the email and site are hosted with different hosts? I've fixed issues like this before with SMTP plugins for Wordpress, but this is the first mail script I'm troubleshooting. Any help would be appreciated!

I am guessing you are on cPanel? It's because it's a piece of poo poo, if so. Pretty much only option is use a third party mail service

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer

McGlockenshire posted:

If you are using your domain's email, use the SMTP server provided by the host of the (MX records for the) domain.

If you are sending as a gmail address, use Google's SMTP servers. Using your gmail address as the From address, but sending through your host's servers will significantly increase the likelihood of your mail being flagged as spam by the recipients.

Never use mail(). It's poo poo. You can't troubleshoot it, you can't debug it, you can't control it, and when things go wrong like this, you are completely up a creek. Instead, use Swiftmailer if you can, but it's fine to use use PHPMailer if learning Swiftmailer seems overwheming.

I'm basically fixing another designer's mistakes so that the company won't lose the client. One of which is this email form - it's laid out well, but the form doesn't even use label tags or have a neat output when it does send an email. I'm probably going to install a Wordpress plugin, punch in their SMTP information into an SMTP plugin, and have it work that way. I'm not getting paid enough to figure out installing and configuring these PHP scripts, and all I have access to is their FTP and Wordpress login.

Biowarfare posted:

I am guessing you are on cPanel? It's because it's a piece of poo poo, if so. Pretty much only option is use a third party mail service

Why is cPanel lovely? I've never used any alternatives. I have Lithium, which is supposedly a highly rating Goon-run host, and they use cPanel.

DarkLotus
Sep 30, 2001

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

BJPaskoff posted:

I'm basically fixing another designer's mistakes so that the company won't lose the client. One of which is this email form - it's laid out well, but the form doesn't even use label tags or have a neat output when it does send an email. I'm probably going to install a Wordpress plugin, punch in their SMTP information into an SMTP plugin, and have it work that way. I'm not getting paid enough to figure out installing and configuring these PHP scripts, and all I have access to is their FTP and Wordpress login.


Why is cPanel lovely? I've never used any alternatives. I have Lithium, which is supposedly a highly rating Goon-run host, and they use cPanel.
Our mail runs through MailChannels and not direct to the internet like most cPanel hosts. This prevents blacklisting and bad IP reputations.
For best results, use SMTP for all mail and authenticate against localhost with a real email address as configured in cPanel.
Doing that will ensure proper mail delivery without stupid php headers attached. Install the cPanel SMTP plugin and be done with it.

Also, if they never setup their MX records properly, all email addressed to their own domain will send to a local mailbox and not off-server if their mail is hosted elsewhere.
This is typical when using G Suite or Office 365 and a 3rd party for DNS but not telling cPanel that the email is hosted by a 3rd party. cPanel is going to try and deliver mail to itself because it's the best option unless otherwise instructed. Some might call that lovely, but it makes perfect sense to me.

Need more than that, submit a ticket and I'll try to help.

DarkLotus fucked around with this message at 01:15 on Feb 22, 2017

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer

DarkLotus posted:

Our mail runs through MailChannels and not direct to the internet like most cPanel hosts. This prevents blacklisting and bad IP reputations.
For best results, use SMTP for all mail and authenticate against localhost with a real email address as configured in cPanel.
Doing that will ensure proper mail delivery without stupid php headers attached. Install the cPanel SMTP plugin and be done with it.

Also, if they never setup their MX records properly, all email addressed to their own domain will send to a local mailbox and not off-server if their mail is hosted elsewhere.
This is typical when using G Suite or Office 365 and a 3rd party for DNS but not telling cPanel that the email is hosted by a 3rd party. cPanel is going to try and deliver mail to itself because it's the best option unless otherwise instructed. Some might call that lovely, but it makes perfect sense to me.

Need more than that, submit a ticket and I'll try to help.

Oh, sorry for the confusion! The PHP mail problem is separate from my cPanel question. I'm happy with Lithium, but this client isn't hosted with you (but they would be if they were my client directly).

DarkLotus
Sep 30, 2001

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

BJPaskoff posted:

Oh, sorry for the confusion! The PHP mail problem is separate from my cPanel question. I'm happy with Lithium, but this client isn't hosted with you (but they would be if they were my client directly).

I think that explains the problem then :q:

Baxta
Feb 18, 2004

Needs More Pirate
This is maybe a dumb question but a client wants an ordering website done and he's adamant he wants it in PHP and he wants me to do it.

I'm alright with laravel but normally use .NET with the entity framework (which auto creates the db schema based mostly on your models).

Does laravel has some sort of plugin like EntityFramework so I don't have to go create the database and modify my poo poo in two places at once?

Master_Odin
Apr 15, 2010

My spear never misses its mark...

ladies
You're probably looking for Doctrine.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Master_Odin posted:

You're probably looking for Doctrine.

This.

While Laravel wants you to use the ORM it bundles, it's an ActiveRecord and comes with all the associated baggage. Doctrine is a Data Mapper and therefore comes with a completely different, but far superior, set of baggage. If you're coming from EF, then Doctrine will probably be more comfortable for you.

Do be warned that doing Doctrine correctly requires code generation for proxy classes and whatnot, but you can have it do this on the fly during development to avoid having to constantly run external tools. Each and every one of the command line tools that it wants you to use can also be called programmatically (migrations, etc).

Baxta
Feb 18, 2004

Needs More Pirate

McGlockenshire posted:

Master_Odin posted:

You're probably looking for Doctrine.
While Laravel wants you to use the ORM it bundles, it's an ActiveRecord and comes with all the associated baggage. Doctrine is a Data Mapper and therefore comes with a completely different, but far superior, set of baggage. If you're coming from EF, then Doctrine will probably be more comfortable for you.

Do be warned that doing Doctrine correctly requires code generation for proxy classes and whatnot, but you can have it do this on the fly during development to avoid having to constantly run external tools. Each and every one of the command line tools that it wants you to use can also be called programmatically (migrations, etc).

Great thanks guys. I'll make a little CRM and see how it works.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
This might be a longshot, but has anyone used curl in PHP to connect to the BigCommerce API?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Grump posted:

This might be a longshot, but has anyone used curl in PHP to connect to the BigCommerce API?

Not personally, but given that their official PHP client library lists curl as a requirement, I'd expect it's fine.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
Yup. That's the exact documentation I've been staring at for an hour.

Been trying to connect to this loving API through PHP with no luck.

e: Got it to connect through Curl. gently caress PHP man

teen phone cutie fucked around with this message at 22:30 on Mar 16, 2017

DarkLotus
Sep 30, 2001

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

Grump posted:

Yup. That's the exact documentation I've been staring at for an hour.

Been trying to connect to this loving API through PHP with no luck.

e: Got it to connect through Curl. gently caress PHP man

Look at Guzzle! It makes writing API clients a breeze!
http://docs.guzzlephp.org/en/latest/

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!
Has anyone ever tackled the Travelling Salesman problem?
I want to start at Location A, travel to B, C, D, E, F and G and return back to A in the most efficient route possible.
At this point I prefer to use Google Maps because I haven't used any other mapping service but am no stranger to APIs and can use any of them.
I basically just want a list, I don't even need to plot points on map. Just take a list of locations with a start and end point and build a route.
No driving directions, literally just an ordered list of which location to go next from the previous location.

-JS-
Jun 1, 2004

Does this help you at all?

https://developers.google.com/optimization/routing/tsp/tsp#directions_api

DarkLotus
Sep 30, 2001

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

Yeah, I actually found that and with the optimize parameter it works pretty well.
Just curious if anyone has done something different. Just never know...

FAT32 SHAMER
Aug 16, 2012



Hey all,

I have been tasked with writing a webpage that will display log files that are on the device and give the user the option to click a button to download them all as a .zip. I'm trying to figure out how exactly to go about this

I put this script together after reading up on ZipArchive
PHP code:
<?php
    $url = $_SERVER['DOCUMENT_ROOT'];
    $path = "./Logs";
    $zip = new ZipArchive();
    $zip->open('Logs.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

    #create recursive directory iterator
    $files  = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file) {
        //skip directories (they would be added automatically)
        if(!$file->isDir()){
            //get real and relative path for current file
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($path) + 1);

            //add current file to archive
            $zip->addFile($filePath, $relativePath);
        }
    }

    $zip->close();
I think I would have to use ajax to be able to interface this with my html button (or whatever the lingo is)

HTML code:
                    <div id="downloadButton">
                        <a href="#" class="myButton">Download All</a>
                    </div>
but i'm not sure. Anyone have any pointers?

edit: I think i found a solution, now to figure out how to make it an onClick'able script
http://stackoverflow.com/questions/1754352/download-multiple-files-as-zip-in-php
PHP code:
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);	 
javascript has spoiled me

FAT32 SHAMER fucked around with this message at 20:29 on Mar 23, 2017

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Why are you onclicking it? It's a link, so make it a link to the script that causes the file download. Yes, you want a plain old regular hyperlink.

Also you should make sure to set the proper cache control headers in addition to content type and disposition.

FAT32 SHAMER
Aug 16, 2012



McGlockenshire posted:

Why are you onclicking it? It's a link, so make it a link to the script that causes the file download. Yes, you want a plain old regular hyperlink.

Also you should make sure to set the proper cache control headers in addition to content type and disposition.

It's a group of .txt files that will get bundled into a zip and downloaded... if I just link to the script it will work?

Oh my god I'm so mad at myself right now

revmoo
May 25, 2006

#basta

funny Star Wars parody posted:

It's a group of .txt files that will get bundled into a zip and downloaded... if I just link to the script it will work?

Oh my god I'm so mad at myself right now

Should yeah. If you link to a script and it executes, then its running.

FAT32 SHAMER
Aug 16, 2012



Hey guys, more dumb noob questions and I will admit that a lot of it involves javascript so if it's better suited to that thread feel free to let me know. I'm trying to make it so that a user can select files that they wish to download or delete from the server (this is an offline embedded device with a lighttpd instance running so that the client has a pretty file management interface) and I can't figure out how exactly to tell the php what to do when the user clicks a button (either download the selected files as a zip or delete them). Here's my code:

PHP code:
<div id="page-navbar" class="navbar navbar-default navbar-fixed-top">
            
                    <ul id="page-top-nav" class="nav navbar-nav">
                        <li>
                            <a href="#" id="page-top-link">
                                <span title="Download Selected" class="fa fa-arrow-down fa-lg"></span>
                                <!--Download Selected-->
                            </a>
                        </li>
                    </ul>

 

                    <ul id="page-top-delete" class="nav navbar-nav">
                        <li>
                            <a href="#" onClick="toDelete()">
                                <span title="Delete Selected" class="fa fa-trash fa-lg"></span>
                                <!--Delete Selected-->
                            </a>
                        </li>
                    </ul>
                    <script type="text/javascript">
                        function rec(deletestuff) {
                            $('#newCode').load('delete_selected.php' deletestuff);
                        }
                    </script>

        </div>

<ul id="directory-listing" class="nav nav-pills nav-stacked">

                <?php foreach($dirArray as $name => $fileInfo): ?>
                    <li data-name="<?php echo $name; ?>" data-href="<?php echo $fileInfo['url_path']; ?>">
                        <a href="<?php echo $fileInfo['url_path']; ?>" class="clearfix" data-name="<?php echo $name; ?>">


                            <div class="row">
                                <span class="file-name col-md-7 col-sm-6 col-xs-9">
                                    <i class="fa <?php echo $fileInfo['icon_class']; ?> fa-fw"></i>
                                    <?php echo $name; ?>
                                </span>

                                <span class="file-size col-md-1 col-sm-2 col-xs-3 text-right">
                                    <?php echo $fileInfo['file_size']; ?>
                                </span>

                                <span class="file-modified col-md-2 col-sm-2 hidden-xs text-right">
                                    <?php echo $fileInfo['mod_time']; ?>
                                </span>

                                <span class="selected col-md-2 col-sm-2 col-xs-1 text-right">
                                    <form method="get">
                                        <input type="checkbox" name="selected[]" value="'.$file.'">
                                    </form>

                                </span>
                            </div>

                        </a>

                        <script>


                            $('input[type=checkbox]').each(function () {
                                if(this.checked) {
                                    toDelete.push(this.id);
                                }
                            });
                        </script>


PHP code:
class DeleteSelected
{
    public function deleteSelected() {
        #$selected = $_POST['selected[]'];
        foreach($_POST['selected[]'] as $file) {
            if(file_exists($lister->getDirectoryPath() . $file)) {
                unlink($lister->getDirectoryPath() . $file);
                echo "<script type='text/javascript'>alert('Files deleted successfully.');</script>";
            }
            elseif(is_dir($file)) {
                rmdir($file);
                echo "<script type='text/javascript'>alert('Files deleted successfully.');</script>";
            }
        }




    }

}
?>
What I'm trying to do is iterate through the checkbox elements to see if any are checked, and if so, add those files/file names to an array that will be passed to the delete function or to the zip function (once i figure out the delete function it will be easy to figure out the zip function). Like I said, I'm probably loving up the way the jQuery/AJAX/whatever is passing the values to the php, but ive been at this for 3.5 days and im about to put my head through a wall haha.

edit: trimmed the code up to get to the few spots that need to be looked at, ignore any weird floating divs that seem to be out of place :shobon:

edit2: I should also mention that I've forked PHP DirectoryLister to do this and while it's saved me a lot of time having to do a lot of the work for myself, for some reason the zipfiles his code creates dont have anything added to them which has been driving me crazy trying to figure out as well.

FAT32 SHAMER fucked around with this message at 21:40 on Apr 3, 2017

nielsm
Jun 1, 2009



funny Star Wars parody posted:

Hey guys, more dumb noob questions and I will admit that a lot of it involves javascript so if it's better suited to that thread feel free to let me know. I'm trying to make it so that a user can select files that they wish to download or delete from the server (this is an offline embedded device with a lighttpd instance running so that the client has a pretty file management interface) and I can't figure out how exactly to tell the php what to do when the user clicks a button (either download the selected files as a zip or delete them).

From this snippet, it looks like you're generally confused with order of execution, and what executes on server and what on client, and how to share data between the two.

HTML code:
                            <a href="#" onClick="toDelete()">
JavaScript code:
                        function rec(deletestuff) {
                            $('#newCode').load('delete_selected.php' deletestuff);
                        }
Here you first have a link that wants to call a JavaScript function named toDelete.
Right after that you define a JavaScript function named rec, which also happens to have a syntax error.
Are the two supposed to be related? Is the rec function actually supposed to be toDelete?

The syntax error is that you just stick 'delete_selected.php' deletestuff together like that, you need an operator (probably +) between them, except that would probably end up as an invalid URL. It's not clear what deletestuff would contain, from the parts you pasted.

HTML code:
                                        <input type="checkbox" name="selected[]" value="'.$file.'">
This is not going to paste any filenames or otherwise in, you're missing some PHP start/end tags around $file.

JavaScript code:
                            $('input[type=checkbox]').each(function () {
                                if(this.checked) {
                                    toDelete.push(this.id);
                                }
                            });
This snippet is run unconditionally as part of the page load. It's not in any event handler, so it would get run exactly once, and just add the it's of any initially checked boxes to the toDelete array.
Which brings me to, suddenly toDelete is an array, but you were using it as a function above.


I think the first thing you should consider is whether you actually need to use JavaScript at all. In your post in the general programming questions thread (which reminded me of this, I had intended to reply earlier but forgot about it) you mention that this thing will run locally only on a small computer, not over the internet. In that case you know something about the performance, you know there will only be a single user at a time, and you know that transfer speed and latency between client and server are both as perfect as they can be. So you don't need to use client side scripting to mask over the performance of regular network connections.

The much simpler solution, which may be what the original thing you're modifying already does, is to just have a plain old HTML form, no JS, you submit, which then batch deletes all the checked off files, and returns a new page with a new directory listing. Optionally with a log at the top/bottom about changes made.
If you really do want a dynamically updating view, you need to completely rework this. You should probably make an array of plain old checkboxes with no events attached. Then have a button you attach a JS event handler to, that event handler then finds all checked boxes, collects the data into a form submission format, uses an XMLHttpRequest to call a PHP script on the server, and waits for then processed the response. The PHP script it calls should accept the form input generated by the JS, process the files, and return a JSON object containing status for each element the JS requested things to be done for. When the JS receives this response, it can go over the returned JSON, find the checkboxes for the files successfully deleted, and replace those checkboxes with a message that the file was deleted, or any error that maybe occurred.


Edit: I made a sequence diagram.

nielsm fucked around with this message at 09:27 on Apr 8, 2017

FAT32 SHAMER
Aug 16, 2012



:doh:

I'm gonna try that out on Monday, I have no idea what I was trying to do with that as it currently is so thanks for the tips, it's really appreciated :)

spiritual bypass
Feb 19, 2008

Grimey Drawer
I have a Symfony console command that for some reason outputs every line I send to it with IO redirection. Here's the command:
php:
<?
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Enter emails, one per line:');
        $emails = (function (): \Generator {
            while ($email = readline()) {
                if (Validator::email()->validate($email)) {
                    yield $email;
                }
            }
        })();

        $output->writeln('Added ' . Contact\addBulk($this->db, $emails) . ' email addresses.');
    }
?>
The Contact\addBulk function is just DB interactions, without any other side effects. Any idea why I get output like this from the command?
Am I misunderstanding something about readline or the shell?
code:
$ ./ql contact:add-bulk < emails.txt
Enter emails, one per line:
[email]user1@example.com[/email]
[email]user2@example.com[/email]
...
UPDATE: Apparently this is a characteristic of readline(). Replacing it with STDIN fixes the issue while preserving all the other behavior: $email = trim(fgets(STDIN))

spiritual bypass fucked around with this message at 13:41 on Apr 12, 2017

bEatmstrJ
Jun 30, 2004

Look upon my bathroom joists, ye females, and despair.
Looking for a PHP coder for a relatively easy webpage project. Hit me up if interested in making a little side money.

SA-Mart thread
https://forums.somethingawful.com/showthread.php?threadid=3817116

revmoo
May 25, 2006

#basta
Post more details, because that doesn't sound like a simple project.

Adbot
ADBOT LOVES YOU

bEatmstrJ
Jun 30, 2004

Look upon my bathroom joists, ye females, and despair.

revmoo posted:

Post more details, because that doesn't sound like a simple project.

Yeah I guess I don't know how hard it is, but I've done some image manipulation stuff in the past and don't remember it being terribly difficult. But here's a graphic representation of what I need to do. Let me know what you think.

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