/    Sign up×
Community /Pin to ProfileBookmark

Reading data from file to multidimensional array

Hi.

Im trying to build a filtering system for a imagegallery in PHP. I want to be able to filter out images by category with checkboxes. What I´m currantly working on is reading data from a text file into an multidimensional array that I will later use to instantiate objects of a class and echo out each image.

I guess i have to use a foreach loop to explode each data into the array, but I´m not sure how to assign each data to the right array index.

I am thinking the array should look like this: (But please correct me if this dosent seem right)

[code]$images = array(array(“srcFile”=> “image1.jpg”, “thumbFile”=> “image1_250x250.jpg”, “altTag”=> “waterfall”,
“animal”=> false, “nature”=> true, “architecture”=> false),
array(“srcFile”=> “image2.jpg”, “thumbFile”=> “image2_250x250.jpg”, “altTag”=> “bridge”,
“animal”=> false, “nature”=> false, “architecture”=> true),
array(“srcFile”=> “image3.jpg”, “thumbFile”=> “image3_250x250.jpg”, “altTag”=> “dog”,
“animal”=> true, “nature”=> false, “architecture”=> false)
);
[/code]

This is what I have so far:

[code]
// Get datalines from file
$lineContent = explode(“n”, file_get_contents(‘./data.txt’));

// Split each dataline into datafields
foreach ($lineContent as $l) {
$arrayFields = explode(“|”, $l );

foreach ($arrayFields as $i) {
// Some code to assign data to right array index.
}
}[/code]

to post a comment
PHP

26 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJun 21.2018 — Obivously your file is kind of a CSV file where the separator is a "|" instead of a comma. There is a premade function in PHP for parsing this:

https://stackoverflow.com/questions/9139202/how-to-parse-a-csv-file-using-php

You just need to change the separator:
$data = fgetcsv($handle, 1000, "|")
What about the field names in your destination array? Does the file contain them or do you have to set them by yourself? It would be helpful if you post some sample lines of your file.
Copy linkTweet thisAlerts:
@cinemaorauthorJun 21.2018 — The file will look something like this. I will have more datafields but i´m keeping it simple for the example.

image01.jpg|image01_250x250.jpg|waterfall|false|true|false

image02.jpg|image02_250x250.jpg|bridge|false|false|true

image03.jpg|image03_250x250.jpg|architecture|true|false|false
Copy linkTweet thisAlerts:
@SempervivumJun 21.2018 — This should do the job:
$arr = [];
$keys = ["srcFile", "thumbFile", "altTag", "animal", "nature", "architecture"];
if (($handle = fopen("data.txt", "r")) !== false) {
while (($data = fgetcsv($handle, 1000, "|")) !== false) {
$num = count($data);
$arr2 = [];
for ($c = 0; $c < $num; $c++) {
$arr2[$keys[$c]] = $data[$c];
}
$arr[] = $arr2;
}
fclose($handle);
}
var_dump($arr);
Copy linkTweet thisAlerts:
@cinemaorauthorJun 21.2018 — Thanks a lot. Exactly the result i wanted.
Copy linkTweet thisAlerts:
@rootJun 21.2018 — IMHO, If I were doing this... I would make an upload page.

In that page you have the details you want stored with the image.

You then store the data into a database or in to an SQLite database (file type) as flat files are at best, demonstration usefulness (IMHO).

So your image will then get stored in a folder in a name structure of your chosing and the data about the image can be stored.

What this then means is you can simply make a database call to get any imaged of a type, not of a type, between certain dates, and any number of ways of manipulating the query to get what you are looking for.

Then you build the front end that will use the database.
Copy linkTweet thisAlerts:
@cinemaorauthorJun 21.2018 — Yeah, a database is probably the best way to deal with this. I thought about it when I started, but decided against it because I knew nothing about how to set up a database. I thought it would be easier to go with a flat file structure. Do you think it would take a lot of of time to learn enough about databases for this particular project?
Copy linkTweet thisAlerts:
@rootJun 22.2018 — PHP supports SQLite3 databases

Simple to set up if your web host has it enabled.

Make a folder

run a simple script to make the database file.

change / nodify the file permissions, these should be lowered to the point that the file is not accessible or visible to the outside world but is visible to the system and its owner, this process is alsow able to be done through a PHP script...

<?php
$db = new SQLite3("test.db3");
chmod("test.db3", 0600 ); // or could be 0644
$db->close();
?>


Something as simple as running that in a folder of its own should produce an empty SQLite3 database file that is not visible to anyone but the site owner, system so that any PHP script on the site can access that file but it will never be downloadable because it is not visible.

Having run the script on my server, found a file test.db3 with the file permissions set to 0600 which is as low as you can go, it may be that you need 0644 as the permissions, you won't know until you encounter problems.

If you run that on your web host, if you get errors, then read the errors, it may be that you need to change the php.ini for your site or your host doesn;t want you running a freebie on a server that they charge extra for a database...
Copy linkTweet thisAlerts:
@cinemaorauthorJun 22.2018 — MySQL and MariaDB are the only databases listed at my web host. SQLite3 is probably not supported then. Would MySQL be a lot of work setting up?
Copy linkTweet thisAlerts:
@NogDogJun 22.2018 — SQLite3 is _probably_ available, as it is just files that the PHP extension reads and writes to locally, with the entire DBMS existing within PHP itself. But MySQL/MariaDB would be running (most likely) on a separate database server and likely with some sort of automated backup in place (but don't take that for granted), and would probably be a more robust solution. But, if you use PHP's PDO extension, you can easily switch from one DBMS to another as your needs change (though if you use any non-standard DBMS-specific functions, that might take some tweaking if/when you change).
Copy linkTweet thisAlerts:
@cinemaorauthorJun 23.2018 — I have access to a MySQL tutorial so I´m doing that right now, at least to learn the basics of databases. How do I manage SQLite3 database? Can I do it from phpmyadmin or is that strictly for MySQL? I´m running MAMP on my computer if that helps.
Copy linkTweet thisAlerts:
@ginerjmJun 23.2018 — If you host is not currently supporting a db interface such as you ask, they probably won't be adding any time soon just for you. Are you sure that MariaDB is being supported by your host and not something more all-encompassing like PDO?
Copy linkTweet thisAlerts:
@cinemaorauthorJun 23.2018 — MySQL / MariaDB is the only db listed at the info page for what is included in the webserver, so I just assumed nothing else was supported. I could always ask them though. But would it be a bad choice going for MySQL over SQLite?
Copy linkTweet thisAlerts:
@rootJun 23.2018 — The point of SQLite3 is that it is SQL like MySQL.

MySQL is the standard set up, however, depending on your web host, you need to check what their restrictions AKA Caps are...

Some web hosts will allow up to 1 Gigabyte databases, majority charge you for the pleasure of having access to a database, a fair few like mine throw all the tool box at you and you have no limits...

So I would check and ensure that you will not have any surprise billing coming your way.

In either choice and other systems that are on offer, your database is only as secure as your coding in your script. So if you are going to implement a database and you are going to be inserting information in to it from a web form, or you are using any of the input streams in to the server, should all be scrutinised and sanitised in to safe variables or a safe array.

You should bone up on SQL Injection as well as Script Injection.
Copy linkTweet thisAlerts:
@cinemaorauthorJul 06.2018 — My webhost confirmed that SQLite3 is available. However they adviced me not to use it since it its not suitable for parallel processes. Would this be a big issue for my use?
Copy linkTweet thisAlerts:
@rootJul 06.2018 — Not according to what I had read.

IMHO this is possibly BS on the hosts part because they likely have had issues in the past because people do not make the file system only visible, as in not changin the file permissions like many security related things with PHP and HTML there are a lot of bad programming about and poor examples and this leads to issues over security.

So as long as you chmod() the file for t he database so its 0600 or 0644 or maximum of 0666 you want the file visible to the system and script execution but not publicly visible of list able.

In fact, I would say that using parallel processes is more problematic IF the coder fails to issue the kill command for that process which will be sat there consuming resources that could be freed up elsewhere.

I doubt that you will be needing anything of that type of processing power.
Copy linkTweet thisAlerts:
@cinemaorauthorJul 06.2018 — I´ll describe my website a little better just in case. Maybe the parallel processes issue will be more clear.

The site will have 4 content pages.

  • 1. photogallery page

  • 2. Videgallery page

  • 3. Article page for critques

  • 4. Miscellaneous page.


  • The miscellaneous page will consist of a mix of images, videos and articles that dont fit in the other pages pluss audio clips. Im not sure how I should structure this in the database. Should I have a table for each page? Or should I have a table for each media type (images, videos, articles, audio)? I´m guessing the latter makes more sense, but it kind of makes sense to separate different kind of images in their own tables as well. (Photography table, 3d renders table, graphic design table).
    Copy linkTweet thisAlerts:
    @rootJul 06.2018 — My suggestion is to look at the post by a board member who wrote a simple but effective block of code for getting users set up with the fundamentals of uploading.

    https://www.webdeveloper.com/forum/d/101466-how-to-upload-images-using-php

    Uploading files is no different.
    Copy linkTweet thisAlerts:
    @cinemaorauthorAug 05.2018 — @root#1593634

    Hi again. Just a quick question, would you recommend connecting to sqlite3 database through PDO? I´m not sure if I should bother learning it.
    Copy linkTweet thisAlerts:
    @rootAug 05.2018 — I have no experience of PDO, SQLite has a set of PHP commands that do the job just fine.
    Copy linkTweet thisAlerts:
    @NogDogAug 06.2018 — @cinemaor#1594582

    PDO may make sense if you think you might migrate from SQLite to some other DBMS as some point. Otherwise it's pretty much whichever you find more efficient to get the job done.
    Copy linkTweet thisAlerts:
    @rootAug 06.2018 — On delving in to the PDO thing, appears PDO can be used withe sqlite3.
    Copy linkTweet thisAlerts:
    @cinemaorauthorAug 08.2018 — I was thinking about using PDO mainly for security reasons. From what I have read it offers good protection against SQL injections. Would PDO be good in that respect or is regular PHP just as good?
    Copy linkTweet thisAlerts:
    @ginerjmAug 08.2018 — Both PDO and MysqlI provide protection against injections simply because they both take advantage of prepared queries. Personally I (and apparently many people here as well) prefer PDO since it is very clear and straight-forward in its use. The manual shows very clear and concise examples of how to use it.

    I don't know what you are thinking about when you say 'regular PHP just as good'. The two don't relate.
    Copy linkTweet thisAlerts:
    @NogDogAug 09.2018 — PDO is one of many PHP database extensions ( http://php.net/manual/en/refs.database.php ), as are the MySQLi and SQLite3 extensions, so they're all essentially "regular PHP", though I guess PDO is classified as a "database abstraction" extension, since it is more or less DBMS-agnostic. I've been using object-oriented PDO exclusively for PHP database usage for several years now, so I'm probably biased; but now I think in PDO when doing any PHP database stuff.
    Copy linkTweet thisAlerts:
    @langtuqnAug 09.2018 — 
    I was using mongodb to save large data, current data up to 200k, I optimized the indexes but sometimes the CPU went high, and the error "server reached max_children setting (10"
    Copy linkTweet thisAlerts:
    @cinemaorauthorAug 09.2018 — @ginerjm#1594708

    "I don't know what you are thinking about when you say 'regular PHP just as good'. The two don't relate."

    I meant PHP without the PDO extension. I wasnt really sure what PDO was when I wrote it so I fooled myself to belive it wasnt PHP.
    ×

    Success!

    Help @cinemaor spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 3.29,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,

    tipper: Anonymous,
    tipped: article
    amount: 10 SATS,
    )...