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
spiritual bypass
Feb 19, 2008

Grimey Drawer
So you've got some big blob of json that represents a graph? Is it a tree structure? What are you trying to get from this data structure?

Adbot
ADBOT LOVES YOU

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Acidian posted:

I have an actual proper PHP question this time.

Using json_decode(), I have an array of nested arrays, and in theory I might be in a situation where I don't know how many child arrays there are.

With json_decode() I can chose to solve this as an object or as an associative array. One or the other doesn't seem to help me much in solving the problem.

So in theory, I need to go through each element, check if the element is a new array or not.

Then that array, might have more arrays, and I need to check each of those elements for new arrays.

Then I need to check those arrays for new arrays again.

In practice I know how many arrays there are, but to future proof the program, then I have to assume the amount of arrays and where they branch can change.

All the potential arrays should in theory be listed under $object->children_data or $array['children_data' => [new=>array]], if that is any help. However, it should seem possible to solve without that knowledge (could always use the is_array() function within a foreach loop as well).

I feel kinda stupid and I am baffled on how to solve this, but it seems like a common enough problem, so I hope you guys can help me.

In general you can solve problems of this type using recursion. I'll give a javascript solution.

code:
findArrayCount = (items) => { 
    var count = 0; 
    items.forEach((item) =>  {       
	 if(item.constructor === Array) { 
             count++; 
             count+= findArrayCount(item);
          }
     }); 
    return count;
}
The same thought process that can be used to count the array at the top level can be used on every array within, so just write a function that counts how many items are arrays within the json, and call that function on each individual array within.

Acidian
Nov 24, 2006

I solved the problem by using the array_walk_recursive function, and retrieving the data I needed from each branch and endpoint, without needing to know how many arrays there are or how they are nested.

If I want to make a check that the array structure is correctly formed, then I will have to solve this problem, but right now I have a solution that will work for now.


Bruegels Fuckbooks posted:

In general you can solve problems of this type using recursion. I'll give a javascript solution.

The same thought process that can be used to count the array at the top level can be used on every array within, so just write a function that counts how many items are arrays within the json, and call that function on each individual array within.

I don't know any Javascript currently, but I think I understand your code and what you mean. I can easily count the number of arrays by using array_walk_recursive() and counting the number of 'id' fields.

I am thinking that I could do a function using $array[$x][$y][$z]. Then it would iterate through $z until it is done, do a $y++ until all the $y's were done, then $x++ until all the array elements were done. I would have to assume there can be more than 3 dimensions, but if I code up to 5 dimensions then that should be pretty future proof, I think.

Right now it's alot of work for very little gain, so I think I will have to come back to this issue at a later date when I want to improve my code.

rt4 posted:

So you've got some big blob of json that represents a graph? Is it a tree structure? What are you trying to get from this data structure?

It's a tree structure, and it's catalogue data. Each branch has data values, and each end point has data values, for example they include an id field and a label field.

code:
Could be something like this: 

	   id
       /        \
     id         id
    /  \       / | \  
   id  id    id id id
  / | \           /  \    
 id id id        id  id   

Ranzear
Jul 25, 2013

It's probably a sorted tree, so I'd expect you to want an in-order traversal.

But you really need to wrap your head around the recursive approach. It's basically "Call the function that was called on me on my children first, then return my result with theirs."

Zamujasa
Oct 27, 2010



Bread Liar
php:
<?php

function fart($array) {
  $c 0;
  foreach ($array as $node) {
    if (isarray($node)) {
      $c += fart($node);
    } else {
      $c++;
    }
  }
  return $c;
}
Note that you can make $c whatever, it doesn't have to be a count. You could put every final node's value into it and then use array_unique on the end result, for example.

Zamujasa fucked around with this message at 02:25 on Jul 20, 2018

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Just wanna say gently caress what PHP does to $_FILES when there are multiple uploads. I know it's been like that forever, and that's why it can't be fixed, but good god what a stupid, backwards, broken way to handle it.

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."
I have a Wordpress template PHP file that interprets JSON and used to spit out a nice tap list. With the latest PHP it looks like bones_main_nav() has been deprecated and I get the following error:

code:
Fatal error: Uncaught Error: Call to undefined function bones_main_nav() in /home/wp-content/themes/Divi/page-taplist.php:29 Stack trace: #0 /wp-includes/template-loader.php(74): include() #1 /wp-blog-header.php(19): require_once('/wp-inclu...') #2 /index.php(17): require('/w...') #3 {main} thrown in /wp-content/themes/Divi/page-taplist.php on line 29
Below is the page-taplist.php snippet:
code:
<?php
/*
Template Name: Taplist Page
*/
?>

<?php get_header(); ?>

	<body <?php body_class(); ?> id="inner-bkgd">
	<script>
  		fbq('track', 'ViewContent');
	</script>

    <div id="wrap">
		<header role="banner">
                        <div class="navbar">
                            <div class="navbar-inner">
                                <div class="container-fluid">                                            
                                        <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                                            <span class="icon-bar"></span>
                                            <span class="icon-bar"></span>
                                            <span class="icon-bar"></span>
                                        </a>
                                        <a class="brand" id="logo" title="<?php echo get_bloginfo('description'); ?>" href="<?php echo home_url(); ?>">Logo here</a>


                                         
                                        <div class="nav-collapse collapse">
                                            <?php bones_main_nav(); // Adjust using Menus in Wordpress Admin ?>
                                        </div>
                                    
                                    <?php if(of_get_option('search_bar', '1')) {?>
                                    <form class="navbar-search pull-right" role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
                                        <input name="s" id="s" type="text" class="search-query" autocomplete="off" placeholder="<?php _e('Search','bonestheme'); ?>" data-provide="typeahead" data-items="4" data-source='<?php echo $typeahead_data; ?>'>
                                    </form>
                                    <?php } ?>
                                 
                                </div> <!-- end #container-fluid --> 
                                    
                            </div> <!-- end .navbar-inner -->
                        </div> <!-- end .navbar -->
                    
		</header> <!-- end header -->   
			
		<div class="container-fluid">
			
			<div id="content" class="clearfix row-fluid">
			
				<div id="main" class="span9 clearfix" role="main">

					<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
					
					<article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?> role="article">
						
						<header>
							
							<div class="page-header"><h1><?php the_title(); ?></h1></div>
						
						</header> <!-- end article header -->
					
						<section class="post_content">
							<?php the_content(); ?>

I can't find a good article on updating this call to get everything working. Is there a quick fix for it?

Heskie
Aug 10, 2002
bones_main_nav isn't a PHP function, but a function from a WordPress theme or plugin.

Going by the bones_ prefix, I'm assuming its this WP boilerplate theme: https://themble.com/bones/

I'm guessing your problem is that your theme is not set to be a child theme of Bones, and therefore now can't find the function it expects.

It looks like that theme no longer exists, but I did find a reference to the function on GitHub: https://github.com/DD9/boiler2/blob/a4b6cf0d5b02beb8d128f7bed159dca0bf7deee5/library/bones.php#L256

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."

Heskie posted:

bones_main_nav isn't a PHP function, but a function from a WordPress theme or plugin.

Going by the bones_ prefix, I'm assuming its this WP boilerplate theme: https://themble.com/bones/

I'm guessing your problem is that your theme is not set to be a child theme of Bones, and therefore now can't find the function it expects.

It looks like that theme no longer exists, but I did find a reference to the function on GitHub: https://github.com/DD9/boiler2/blob/a4b6cf0d5b02beb8d128f7bed159dca0bf7deee5/library/bones.php#L256

Is it possible to take bones.php and stick it in my theme so add those functions? It might be more of a wordpress specific question...

itskage
Aug 26, 2003


raej posted:

Is it possible to take bones.php and stick it in my theme so add those functions? It might be more of a wordpress specific question...

Probably. So long as nothing in there is relying on something else that's missing.

e: I don't endorse this fix though.

Acidian
Nov 24, 2006

I have gotten into a situation now where I plan to set up multiple cron jobs, but some of the scripts are potentially very time consuming, and my worry is that they might overlap. That is, new script might start running before the last one was complete. There are also certain script I want to be sure are run in a proper sequence, to check that certain conditions are in place, or put those conditions into place if they are not. One script I was running took 24 hours to complete, but I have some ideas on how to improve on this, and it wont take 24 hours every time its run, only the first time (populating tables over REST API which requires a response from the client for every line). In the case of the 24 h queue script, which on most days might take 0-5 minutes, if the cron job is set up to run every 15 minutes and the update suddenly takes an hour, then I cant have the same script running 4 times.

I have an idea, which I am pretty sure I got from this thread but I can't find where someone mentioned it, which is to set up a queue table in mysql. I am thinking a cron job php script will run and start the php scripts that are listed in the sql table one by one sequentially, and the scripts themselves will mark themselves as ongoing when they start. This way the another cron job script can be run to add jobs to the queue-table, or check if all the necessary scripts are already in the table/queue, and running or waiting to be run, and if the script is already in the table, then it will not add it again.

I am also thinking that I will find a loop in the scripts (all the scripts have a loop somewhere in the code) which can send an update to the SQL table every time it loops, to show that it's actually running. If my server crashes, maybe because of power outage, then the job table would be there with the queue in place, but no scripts would actually be running. So a cron job script would have to flush the "running" scripts from the queue, or maybe just empty the queue outright, and the way to figure out if a script is running or not is if it is continuously sending some kind of keep-alive information to the table. The down side of this is that the scripts would potentially take longer to run if they continuously send database updates. It might be smart if I could set up a loop counter, and say that the updates to the database queue-table only need to be sent every modulo 10, 100 or 1000 of the loop counter. Just so the queue flusher script knows that the script has sent a keep-alive the last 10-30 minutes or so.

Do you goons have any input on this? Is this a good idea, or are there better ways of doing this? I am switching over to production in a little over a week, so I don't have a whole lot of time if I need to learn something new.

bigmandan
Sep 11, 2001

lol internet
College Slice
Most of what you have said seems pretty reasonable. If you want a fairly simple way to handle script(s) from running at the same time, you can use a locking mechanism. For example

https://symfony.com/doc/current/components/lock.html

If you need finer grain control on when scripts are run you may want to look into supervisord instead of cron.

joebuddah
Jan 30, 2005
What would cause a conversion error when using post data for a SQL server between query.

format is yyyy-mm-dd

I am using SQL server.

I am using jQuery date picker for the form.
The query works if I use $_get for Datatables.
But when I use $_post it throws an error. This is driving me crazy.

I

McGlockenshire
Dec 16, 2005

GOLLOCKS!

joebuddah posted:

What would cause a conversion error when using post data for a SQL server between query.

What specific error are you getting, for which specific data?

Acidian
Nov 24, 2006

bigmandan posted:

Most of what you have said seems pretty reasonable. If you want a fairly simple way to handle script(s) from running at the same time, you can use a locking mechanism. For example

https://symfony.com/doc/current/components/lock.html

If you need finer grain control on when scripts are run you may want to look into supervisord instead of cron.

I want to learn to use the Symfony framework, since the application I am using is written in symfony and I want to do some back end modifications later down the line. If what I say sounds reasonable, then I will just stick with that for now, and learn a better way when I start learning Symfony.

I have "supervisor" installed on the server for the application, not sure if that does the same as "supervisord", but right now I don't think I need "fine grain" control so I think it's ok.

Thank you.

bigmandan
Sep 11, 2001

lol internet
College Slice

Acidian posted:

I want to learn to use the Symfony framework, since the application I am using is written in symfony and I want to do some back end modifications later down the line. If what I say sounds reasonable, then I will just stick with that for now, and learn a better way when I start learning Symfony.

I have "supervisor" installed on the server for the application, not sure if that does the same as "supervisord", but right now I don't think I need "fine grain" control so I think it's ok.

Thank you.

You can use the lock library without using the rest of the framework.

spiritual bypass
Feb 19, 2008

Grimey Drawer
You could also add flock to the front of your cron command to let the OS handle locking for you

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

joebuddah posted:

What would cause a conversion error when using post data for a SQL server between query.

format is yyyy-mm-dd

I am using SQL server.

I am using jQuery date picker for the form.
The query works if I use $_get for Datatables.
But when I use $_post it throws an error. This is driving me crazy.

I

Not sure if it's true in your case, but I've found date pickers can be influenced by local settings (e.g. localization) so you need to be strict about parsing that info before the database acts on it.

What I'd suggest is:
- Capturing the date string in both cases and see how they differ (my guess is that if there is a difference it's on T value)
- Forcing a CONVERT(x,datetime)/GetDate before trying to use it in a query

This discussion goes over some of the tricks and further down the page lists some of the more obscure ints for GetDate:
https://stackoverflow.com/questions/889629/how-to-get-a-date-in-yyyy-mm-dd-format-from-a-tsql-datetime-field

EDIT-Whhops, thought this was the SQL thread, you were probably looking for a code solution

joebuddah
Jan 30, 2005
This is my error message
code:
Array ( [0] => Array ( [0] => 22007 [SQLSTATE] => 22007 [1] => 242 [code] => 242 [2] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. [message] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. ) ) 
What I ended up doing is changing the date to iso format. Then stripped out the '-'.

Thanks for the help

Edit I still don't understand why it's throws an error on one server but works on the other. Both of which run SQL server

joebuddah fucked around with this message at 23:17 on Aug 22, 2018

Acidian
Nov 24, 2006

rt4 posted:

You could also add flock to the front of your cron command to let the OS handle locking for you

That seems really simple, will check that out, thanks!

Acidian
Nov 24, 2006

I am running into a weird memory issue with a script. It's a short looping script that uploads an image, so it continously loads in an image file, converts it to base 64 and saves it to a variable, uploads the image to a server and unsets the image file. Then the proccess repeats. Since this is in a while statement, and the variables are the same onces being used over and over, shouldn't the memory allocation (size and address) stay more or less the same with some fluctiuations of 1-2mb depending on the image size?

code:
    //Fetching 1 product in JSON form.
$product = $sql_client_products->get_products();

//Infinite loop insurance.
$i = 0;
    while($product && $i<10000){
        $product = json_decode($product['ProductJSON'], true);

        //Get file location and image file name.
        $file_loc = $product['media_gallery_entries'][0]['content']['base64_encoded_data'];
        $filen_name = $product['media_gallery_entries'][0]['content']['name'];

        //Fetch image from server.
        if($ak_client->get_image_from_url($filen_name, $file_loc)){
            $image_base64_encoded_data = base64_encode(file_get_contents($filen_name));

            //Remove the image location and instead insert the base64 image date
            $product['media_gallery_entries'][0]['content']['base64_encoded_data'] = $image_base64_encoded_data;
            unlink($filen_name);
        }
        //Uploading the product with image to database.
        if($mag_client->add_product($product)){
            //Deleting the product from database.
            $sql_client_products->del_product($product['sku']);
        }

        $date = new DateTime();
        echo $date->format('H:i:s') . ": " . ++$i . "sku: ". $product['sku'] . "\n";

	//Get new product, if table is empty, returns false.
        $product = $sql_client_products->get_products();
    }

bigmandan
Sep 11, 2001

lol internet
College Slice

Acidian posted:

I am running into a weird memory issue with a script. It's a short looping script that uploads an image, so it continously loads in an image file, converts it to base 64 and saves it to a variable, uploads the image to a server and unsets the image file. Then the proccess repeats. Since this is in a while statement, and the variables are the same onces being used over and over, shouldn't the memory allocation (size and address) stay more or less the same with some fluctiuations of 1-2mb depending on the image size?

code:
    //Fetching 1 product in JSON form.
$product = $sql_client_products->get_products();

//Infinite loop insurance.
$i = 0;
    while($product && $i<10000){
        $product = json_decode($product['ProductJSON'], true);

        //Get file location and image file name.
        $file_loc = $product['media_gallery_entries'][0]['content']['base64_encoded_data'];
        $filen_name = $product['media_gallery_entries'][0]['content']['name'];

        //Fetch image from server.
        if($ak_client->get_image_from_url($filen_name, $file_loc)){
            $image_base64_encoded_data = base64_encode(file_get_contents($filen_name));

            //Remove the image location and instead insert the base64 image date
            $product['media_gallery_entries'][0]['content']['base64_encoded_data'] = $image_base64_encoded_data;
            unlink($filen_name);
        }
        //Uploading the product with image to database.
        if($mag_client->add_product($product)){
            //Deleting the product from database.
            $sql_client_products->del_product($product['sku']);
        }

        $date = new DateTime();
        echo $date->format('H:i:s') . ": " . ++$i . "sku: ". $product['sku'] . "\n";

	//Get new product, if table is empty, returns false.
        $product = $sql_client_products->get_products();
    }

I don't see anything erroneous that would cause memory issues. Without knowing what $ak_client, $mag_client, etc. are doing under the hood it's difficult to tell.

You may want to do some profiling with xdebug and cachegrind. Depending on the version I think profiling was removed then added back into xdebug at some point though.

Acidian
Nov 24, 2006

bigmandan posted:

I don't see anything erroneous that would cause memory issues. Without knowing what $ak_client, $mag_client, etc. are doing under the hood it's difficult to tell.

You may want to do some profiling with xdebug and cachegrind. Depending on the version I think profiling was removed then added back into xdebug at some point though.

Ok, thanks, I will try running xdebug on it later tonight. I have also increased the max script size from 128MB to 2GB, so will see how far that gets me.

ak_client and mag_client are guzzle functions just sending a request and recieving data. Again it's the same variables being called over and over, can't see any situation where any new variables would be "piling up". I also uploaded 43000 products without images using the same class and functions.

my bony fealty
Oct 1, 2008

Anyone written a GraphQL server in PHP and if so which implementation did you use? How was the experience?

The webonyx graphql-php project seems to be the most popular one?

Peggle Fever
Sep 21, 2005

shake it

bigmandan posted:

I don't see anything erroneous that would cause memory issues. Without knowing what $ak_client, $mag_client, etc. are doing under the hood it's difficult to tell.

You may want to do some profiling with xdebug and cachegrind. Depending on the version I think profiling was removed then added back into xdebug at some point though.

PHP does not do a great job with memory in a loop like this.

Try to minimize your calls to the database. Process the images, then make a single operation to the database with all the successful images. Log any errors from the images.

Wazzerphuk
Feb 9, 2001

Hating Chelsea before it was cool
Winner of the PWM POTM for September
Winner of the PWM POTM for January
Co-Winner of the PWM POTM for March

my bony fealty posted:

Anyone written a GraphQL server in PHP and if so which implementation did you use? How was the experience?

The webonyx graphql-php project seems to be the most popular one?

I've been playing around with one in my limited dev time at work and I'm liking it so far. Using the webonyx bundle on top of Symfony 4.1 (using overblog/graphql-bundle) and they play really nicely together. I'm very new at the whole GraphQL thing though, and I haven't been doing anything particularly complicated. This is strictly a read-only application so I couldn't tell you how well it works with mutations, but I'm not at all sold on GraphQL being responsible for inserts/updates anyway,

Acidian
Nov 24, 2006

Trying to enable ssl on my webserver and I am losing my mind. Sorry to pester the PHP thread about this, but there is no specific webserver thread I think.

I am trying to use letsencrypt with certbot. It refuses to write the /.well-known/acme-challenge/ folder. I have tried disabling all sites, and just made a new config file that is super basic:

Cloudfare is blocking me trying to add the following text, so I will have to add it as a photo.



Both fail. I have been at this for 3 hours now trying different configurations. The example.com domain has ssl encryption with another provider, I do not know who, but I am just trying to add some ssl encryption to the subdomain at check.example.com

In all cases, it refuses to write the /.well-known/acme-challenge/ folder. No matter where I point the configuration to or how I chmod or chown the folders.

Acidian
Nov 24, 2006

Peggle Fever posted:

PHP does not do a great job with memory in a loop like this.

Try to minimize your calls to the database. Process the images, then make a single operation to the database with all the successful images. Log any errors from the images.

My first script did not use a database, but because uploading to the server takes alot of time, 4-7seconds per product depending on image size for request and response, I wanted to run one script that adds all the products to a database, which goes super fast. Then I have 5-10 scripts running separately using shell_exec() to upload the data from the database. This cut the upload time from 48 hours to under 12 hours for the whole database. Usually I will not be uploading the whole database, only the changes being made, but sometimes there might be many thousand changes and I want the changes uploaded before people start work in the morning.

Edit: If it's all about calls to the databse, then maybe I could add 10 products (need to see product description lenghts and size of the text sql field to calculate how many products I could safely add) to one row, then make 1 call, process 10 products and upload each, then make a new database call.

Acidian fucked around with this message at 16:56 on Sep 11, 2018

Ranzear
Jul 25, 2013

Run getenforce to see if SELinux is active.

If it's running, that's why. You aren't military contract or medical records, you don't need it. It's an obtuse and obfuscate pile of poo poo and we totally had this exact issue yesterday because Linode's Centos image now has it on by default.

kiwid
Sep 30, 2013

I'm about to work with an external API that requires OAuth2. In the past I've always just opted for using API keys since most third party APIs offer alternatives and I didn't at the time want to dive down the rabbit hole of OAuth2. Anyway, the API I'll be working with is DocuSign and they require OAuth2.

My question is, how do you typically store the access tokens? Also, the DocuSign API documentation says that you can't refresh their tokens so you need to regenerate them when they expire but it appears to allow you to set the expiry time. What would be a good duration to expire these access tokens?

I'm working with the Laravel framework if it matters.

spiritual bypass
Feb 19, 2008

Grimey Drawer
Depends on your level of giving a poo poo. At the lowest tier, you could commit them to your repo (dangerous). Next step up is to store them in an environment variable on the server. Above that, you could have a server running something like Vault that stores all your secrets and your various web applications connect to it every time they need a secret.

SpaceAceJase
Nov 8, 2008

and you
have proved
to be...

a real shitty poster,
and a real james
Can someone give me a rundown on state machines and any reputable libraries? For something simple like a support ticket being opened, moving to a different status level, and closing, etc.

spiritual bypass
Feb 19, 2008

Grimey Drawer
It's more of a mental model than something you get from a library. The Wikipedia page is pretty good. Any textbook on data structures ought to cover it, too. In my own words, you'd think about how your program starts and finishes and every step in between. Draw a directed graph of all the different decisions that happen along the way. Basically all business needs can be represented by a state machine rather than any particular algorithm.

Speaking of state machines and web dev, you should take a look at Elm as food for thought. It's a language/framework combo for building web frontends that forces you to explicitly enumerate the possible states of your program and how they flow. It feels tedious every time you start building something new, but the feeling of getting a program that comes out bug free on the first shot is amazing.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
It sounds like the thing you're looking for can also be called "workflow," and it looks like there are plenty of library options. I've never used one in the past and instead just did the minimal necessary work manually. It's not too hard. If I was going to use a library, I'd start by looking at the Symfony Workflows library to see how well it might work for my use case.

You should also google BPMN and then run away from it.

Acidian
Nov 24, 2006

I want to zip a folder full of images. Opening an archive, adding 1 image, closing the archive works. However, it is slow, it makes a new zip file for every image, and sometimes the close() function fails and the temp file is left in the folder and the image is not added ( I assume).

Trying to open the archive before the foreach loop, does not work. It doesnt even try to make the file it seems, but the open() statement still returns TRUE. I really don't understand what is going on.

This works:

code:

$files = scandir($dir);
$image_archive = 'images.zip';

            foreach ($files as $file){
                if($file == '..' || $file == '.'){
                    continue;
                }

                $zip = new ZipArchive();
                $zip->open($image_archive, ZipArchive::CREATE);

                $file_loc = $dir . $file;
                $zip->addFile($file_loc, $file);
                $zip->close();
}

This does not work:

code:

$files = scandir($dir);
$image_archive = 'images.zip';

$zip = new ZipArchive();
$zip->open($image_archive, ZipArchive::CREATE);

            foreach ($files as $file){
                if($file == '..' || $file == '.'){
                    continue;
                }

                $file_loc = $dir . $file;
                $zip->addFile($file_loc, $file);
                }
$zip->close();

What am I doing wrong?

spacebard
Jan 1, 2007

Football~

Acidian posted:

This does not work:

code:

$files = scandir($dir);
$image_archive = 'images.zip';

$zip = new ZipArchive();
$zip->open($image_archive, ZipArchive::CREATE);

            foreach ($files as $file){
                if($file == '..' || $file == '.'){
                    continue;
                }

                $file_loc = $dir . $file;
                $zip->addFile($file_loc, $file);
                }
$zip->close();

What am I doing wrong?

This worked for me pretty much as-is (PHP 7.1). I plopped it into some php file, made sure $dir and $image_archive had __DIR__ concatenated, ran it, and I got a zip file with my files.

Do you have any memory or file system restrictions? Or maybe the calling code is timing out or closing the file handle? Honestly no clue other than that why it wouldn't work since you've pretty much guaranteed the files exist.

Acidian
Nov 24, 2006

Ok, thank you for checking. I will just try and do some further testing and see, and check the php.ini file for any memory restrictions.

To me it doesn't even seem to make the file, and when I tried making the file beforehand and just appending the images to the file, that did not work either.

Kraus
Jan 17, 2008
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

Kraus fucked around with this message at 21:33 on Jan 27, 2019

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.

Adbot
ADBOT LOVES YOU

spiritual bypass
Feb 19, 2008

Grimey Drawer
You could make it slightly shorter by using short array declarations

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