Issue Querying LDAP in PHP - php

I am currently working on a script that queries Active Directory to check if a user is a Domain Admin. The filter works correctly when I test it with ldp.exe. However, when I run the filter in php it does not return anything. However, just checking the SAM account returns correctly.
Thank you!
$ldap_host = "Example.internal";
$base_dn = "DC=Prefix,DC=Example,DC=internal";
$filter = "(&(sAMAccountName=test)(memberof=CN=Domain Admins,CN=Users,DC=Prefix,DC=Example,DC=internal))";
$ldap_user = "username";
$ldap_pass = "password";
$ldap_port = 3268;
$connect = ldap_connect( $ldap_host, $ldap_port)
or exit(">>Could not connect to LDAP server<<");
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($connect, $ldap_user, $ldap_pass)
or exit(">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
or exit(">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entries returned<p>";
$ii=0;
for ($i=0; $ii<$info[$i]["count"]; $ii++){
$data = $info[$i][$ii];
echo $data.": ".$info[$i][$data][0]."<br>";
}
ldap_close($connect);
?>

Based on the code, I'm assuming you are trying to walk the returned objects and their attributes in the for loop at the end. The problem is how you are iterating. Here's the returned data structure per the manual.
return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry
return_value[i]["dn"] = DN of the ith entry in the result
return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = NAME of the jth attribute in the ith entry in the result
return_value[i]["attribute"]["count"] = number of values for
attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry
Based on this code:
$ii=0;
for ($i=0; $ii<$info[$i]["count"]; $ii++){
$data = $info[$i][$ii];
echo $data.": ".$info[$i][$data][0]."<br>";
}
You are setting $i=0; and not iterating it so it's always 0, corresponding with the first entry in your returned array. You are actually walking through the attributes of the object, which is fine if you only ever expect 1 result back (I suspect that's not the case).
You might try the following function from the docs:
function cleanUpEntry( $entry ) {
$retEntry = array();
for ( $i = 0; $i < $entry['count']; $i++ ) {
if (is_array($entry[$i])) {
$subtree = $entry[$i];
//This condition should be superfluous so just take the recursive call
//adapted to your situation in order to increase perf.
if ( ! empty($subtree['dn']) and ! isset($retEntry[$subtree['dn']])) {
$retEntry[$subtree['dn']] = cleanUpEntry($subtree);
}
else {
$retEntry[] = cleanUpEntry($subtree);
}
}
else {
$attribute = $entry[$i];
if ( $entry[$attribute]['count'] == 1 ) {
$retEntry[$attribute] = $entry[$attribute][0];
} else {
for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
$retEntry[$attribute][] = $entry[$attribute][$j];
}
}
}
}
return $retEntry;
}
USAGE:
$info = ldap_get_entries($connect, $read);
$clean_info = Array();
foreach($info as $entry)
{
$clean_info[] = cleanUpEntry($entry);
}
print_r($clean_info);
Output:
array(256) {
["uid=doe,ou=People,dc=example,dc=net"]=>
array(3) {
["uid"]=>
string(4) "doe"
["cn"]=>
string(14) "John Doe"
["telephonenumber"]=>
string(4) "1234"
}
["uid=foo,ou=People,dc=example,dc=net"]=>
...
You may also consider using print_r($info) after calling ldap_get_entries() to see exactly what is in there.

Related

Check if all values in array are in database and store ones that aren't in new array [duplicate]

This question already has answers here:
Check if all values in an array exist in a database column
(2 answers)
Closed 1 year ago.
I have an array that looks something like this -> ["john.smith#gmail.com", "jane.doe#gmail.com", "jack.smith#gmail.com"]. I want to increment $count for each email that exists in the database. If it doesn't exist (invalid), then I want to push it to the $invalidEmails array.
After that, I want to set my $output according to whether all the emails in the original array are valid or not. They're valid if all of them exist in the database. I'd appreciate some help with this as I'm not sure how to go about it from here. It doesn't work for all cases right now, for example if first email is valid but second one is invalid.
This is what I have so far:
$result = $conn->query("SELECT mail FROM dej_colleagues");
$rows = mysqli_fetch_all($result, MYSQL_ASSOC);
$tags = preg_split("/\,/", $_POST['tags']);
$invalidEmails = array();
$count = 0;
for ($i = 0; $i < sizeof($tags); $i++) {
$trim_brackets = trim($tags[$i], '[]');
$trim_quotes = trim($trim_brackets, '"');
foreach($rows as $row) {
if ($trim_quotes == $row["mail"]) {
$count += 1;
break;
}
}
if ($count == 0) {
array_push($invalidEmails, $tags[$i]);
}
}
$output = array();
if (sizeof($tags) == $count) {
$output = array("validity => "valid emails");
}
else {
$output = array("validity" => "invalid emails", "emails" => $invalidEmails;
}
echo json_encode($output);
Your code seems convoluted, so rather than debug it I started with a more focussed query and worked from there.
Basically, the query asks the database for a list of emails that appear in your $tags array, then uses array_diff() to find any that appear in $tags, but not in the database.
From there you can produce your output directly.
ini_set('display_errors',1);
$mysqli = new mysqli('mysql.lv.local','userName', 'userPassword','schemaName' );
// Assuming the input is a string and not an array, json_decode it.
$tags = '["john.smith#gmail.com", "Jane.doe#gmail.com", "jack.smith#gmail.com","fred.jones#gmail.com"]';
$tags = json_decode($tags);
// switch everything to lower case
$tags = array_map('strtolower', $tags);
// Build and prepare a query with placeholders. Note conversion to lower case
$sql = 'select distinct lower(`mail`) from `emails` where lower(`mail`) in (?'.str_repeat(',?', count($tags)-1).')';
//echo $sql;
$stmt = $mysqli->prepare($sql);
// Bind the values from $tags to the query
$stmt->bind_param(str_repeat('s', count($tags)), ...$tags);
// Execute
$stmt->execute();
// Bind a variable for the result
$stmt->bind_result($email);
// Retrieve the emails in to $dbMails
$dbMails = [];
while ($stmt->fetch()) {
$dbMails[] = $email;
}
//var_dump($dbMails);
// Anything that's in $tags but not in $dbMails is invalid
$absentEmails = array_diff($tags, $dbMails);
//var_dump($absentEmails);
if ($absentEmails) {
$op= ["validity"=>"Invalid enails", 'emails'=>array_values($absentEmails)];
} else {
$op= ["validity"=>"Valid enails"];
}
echo json_encode($op);

How to output multi-dimensional array to CSV file in PHP?

I'm having a bit of an issue with converting my multidimensional array to a CSV file. The issue is that it also contains more arrays within the array.
I'm trying to convert the output of all the entries and attributes of an LDAP server into a CSV file.
A really similar question to mine can be found here: link
Essentially, I'll need the same output as the excel spreadsheet in that question, except for my fields. The issue is that not every LDAP entry has the same attributes. So some of the boxes will be empty.
So for instance I'll have
DN, ObjectClasses, Email, Phone Number, CN, UserID
cn=admin,dc=example,dc=com, top, email#gmail.com, 123-456-7890, training, 12345
But some of my arrays don't have all elements, so for instance, they are missing an email or phone number, but the rest of the elements do have the email or phone number, so I can't manually just enter all the attributes. (Also can't do this as I don't know all of the attributes that the user will need).
Here's my current output:
Amount of entries: 23dc=example,dc=com,objectclass,top,dcObject,organization,example.com,example,cn=admin,dc=example,dc=com,objectclass,simpleSecurityObject,organizationalRole,admin,"LDAP administrator",uid=newton,dc=example,dc=com,Newton,objectclass,inetOrgPerson,organizationalPerson,person,top,newton,newton#ldap.forumsys.com,"Isaac Newton",uid=einstein,dc=example,dc=com,objectclass,inetOrgPerson,organizationalPerson,person,top,"Albert Einstein",Einstein,einstein,einstein#ldap.forumsys.com,314-159-2653,uid=tesla,dc=example,dc=com,objectclass,inetOrgPerson,organizationalPerson,person,top,posixAccount,"Nikola Tesla",Tesla,tesla,tesla#ldap.forumsys.com,88888,99999,home,uid=galieleo,dc=example,dc=com,objectclass,inetOrgPerson,organizationalPerson,person,top,"Galileo Galilei",Galilei,galieleo,galieleo#ldap.forumsys.com,uid=euler,dc=example,dc=com,objectclass,inetOrgPerson,organizationalPerson,person,top,euler,Euler,"Leonhard Euler",euler#ldap.forumsys.com
Basically, it's just completely unorganized (don't mind the amount of entries: 23 part)
I was wondering how I could organize all my outputs?
Here's my current code:
<?php
session_start();
$ldaprdn = 'cn=read-only-admin,dc=example,dc=com';
$ldappass = 'password';
$ldapuri = "ldap.forumsys.com";
// Connecting to LDAP
$ldapconn = ldap_connect($ldapuri)
or die("That LDAP-URI was not parseable");
//We need to set the LDAP Protocol Version or else it isn't able to bind properly to the LDAP server.
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
//We bind to the LDAP server using the previous credentials and location.
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
//Gives where to search & what to search for
$dn = "dc=example,dc=com";
$filter = "(objectclass=*)";
//Saves the result into result variable
$result = ldap_search($ldapconn, $dn, $filter);
$info = ldap_get_entries($ldapconn, $result);
//Saves all the attributes of all entries into an array.
function cleanUpEntry( $entry ) {
$retEntry = array();
for ( $i = 0; $i < $entry["count"]; $i++ ) {
if (is_array($entry[$i])) {
$subtree = $entry[$i];
//This condition should be superfluous so just take the recursive call
//adapted to your situation in order to increase perf.
if ( ! empty($subtree['dn']) and ! isset($retEntry[$subtree['dn']])) {
$retEntry[$subtree['dn']] = cleanUpEntry($subtree);
}
else {
$retEntry[] = cleanUpEntry($subtree);
}
}
else {
$attribute = $entry[$i];
if ( $entry[$attribute]['count'] == 1 ) {
$retEntry[$attribute] = $entry[$attribute][0];
} else {
for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
$retEntry[$attribute][] = $entry[$attribute][$j];
}
}
}
}
return $retEntry;
}
echo "Amount of entries: ".(sizeof(cleanUpEntry($info)));
/*
//Prints all the elements in the array
echo "<pre>";
print_r(cleanUpEntry($info));
echo "</pre>";*/
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$arrayList=array_flatten($value);
foreach ($arrayList as $listItem) {
$result[] = $listItem;
}
}
else {
$result[$key] = $value;
}
}
return $result;
}
function arrayToValues(array $data)
{
$output = array();
foreach ($data as $key => $item) {
if (is_array($item)) {
$output = array_merge($output, array($key), arrayToValues($item));
} else {
$output[] = $item;
}
}
return $output;
}
$csvData = implode(',', arrayToValues(cleanUpEntry($info)));
$csvExport = explode(',', $csvData);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="export.csv";');
$f = fopen('php://output', 'w');
fputcsv($f, arrayToValues($csvExport));
?>

PHP loop to read from SQLite and write to arrays/JSON

I have a SQLite3 database which contains 4 tables with 9 rows each.
I've tried to do each one of the arrays one-by-one, with basically the same code as below (everything in the foreach loop), and it worked fine. I guess I just made some stupid mistakes (I don't really use PHP, this is pretty much the only project I've used it in). I tried to fix it, but somehow PHP is not really friendly today.
Currently the code below returns a JSON with 4 empty arrays.
<?php
header('Content-type: application/json');
$db = new PDO('sqlite:whad.db')or die('Could not open database');
$arDaniel = array();
$arAndi = array();
$arDave = array();
$arSimon = array();
for ($j=0; $j < 4; $j++) {
$name;
$arr;
if (j == 0) {
$name = 'Daniel';
$arr = $arDaniel;
}
elseif (j == 1) {
$name = 'Andi';
$arr = $arAndi;
}
elseif (j == 2) {
$name = 'Dave';
$arr = $arDave;
}
elseif (j == 3) {
$name = 'Simon';
$arr = $arSimon;
}
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $name ORDER BY date(Datum)";
$i = 1;
foreach($res = $db->query($query) as $value) {
$curr = array();
array_push($curr["Datum"] = $value[0]);
array_push($curr["ID"] = $value[1]);
array_push($curr["RR"] = $value[2]);
array_push($curr["RL"] = $value[3]);
array_push($curr["KB"] = $value[4]);
array_push($curr["BD"] = $value[5]);
array_push($curr["SD"] = $value[6]);
array_push($curr["KH"] = $value[7]);
array_push($curr["Reihenfolge"] = $value[8]);
array_push($arr[$i] = $curr);
$i++;
}
}
$json = array(
"Daniel" => $arDaniel,
"Andi" => $arAndi,
"Dave" => $arDave,
"Simon" => $arSimon
);
echo json_encode($json);
$db = NULL;
?>
EDIT: Removed quotes around $curr.
You have many unnecassary variables with the same data.
You simply could do the following
<?php
header('Content-type: application/json');
$db = new PDO('sqlite:whad.db')or die('Could not open database');
$json = array(
"Daniel" => array(),
"Andi" => array(),
"Dave" => array(),
"Simon" => array()
);
foreach($json as $name => &$arr){
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $name ORDER BY date(Datum)";
$stmt = $db->query($query);
//now comes the trick, that you tell pdo to fecth them already as array
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($arr);
echo json_encode($json);
?>
Look at the first example here: http://php.net/manual/de/pdostatement.fetchall.php
Also note the & before $arr, which will handle the $arr variable as reference (also the unset, because after the last pass, it would still be set, this is just good style to clean up)
Update:
As in the other answer you have to use PDO::FETCH_ASSOC to get an array with only the index names.
There are more than one error in your code:
$arDaniel = array();
$arAndi = array();
$arDave = array();
$arSimon = array();
for ($j=0; $j < 4; $j++) {
$name; # <---
$arr; # <---
This sort of ‘declaration’ in php is unnecessary, you can remove $name and $arr (it's not an error, btw);
if (j == 0) { # <---
In the for loop you use $j, you can't use j here: replace it with $j (in php variables are ever prepended by $);
$name = 'Daniel';
$arr = $arDaniel; # <---
By this assignment, you want change the original array, but with this assignment by value, you in fact create a copy of $arDaniel, and new elements are added only to $arr, not to $arDaniel; to do this, you have to do an assignment by reference through & keyword: replace this (and following similar) line with $arr = &$arDaniel;
}
elseif (j == 1) { # <--- see above
$name = 'Andi';
$arr = $arAndi; # <--- see above
}
elseif (j == 2) { # <--- see above
$name = 'Dave';
$arr = $arDave; # <--- see above
}
elseif (j == 3) { # <--- see above
$name = 'Simon';
$arr = $arSimon; # <--- see above
}
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $name ORDER BY date(Datum)";
$i = 1; # <---
The query is formally correct, but I don't know your table structure. $i = 1; is unnecessary (see below);
foreach($res = $db->query($query) as $value) {
$curr = array();
array_push($curr["Datum"] = $value[0]); # <---
array_push($curr["ID"] = $value[1]); # <---
array_push($curr["RR"] = $value[2]); # <---
array_push($curr["RL"] = $value[3]); # <---
array_push($curr["KB"] = $value[4]); # <---
array_push($curr["BD"] = $value[5]); # <---
array_push($curr["SD"] = $value[6]); # <---
array_push($curr["KH"] = $value[7]); # <---
array_push($curr["Reihenfolge"] = $value[8]); # <---
array_push($arr[$i] = $curr); # <---
$i++; # <---
}
}
The array_push syntax is not correct (see manual page): the correct syntax is array_push( $existentArray, $newElement ). In addition, you can't use array_push to add an associative value, you can use it only for numeric key. Change $curr assignments simply in $curr['Datum'] = $value[0]; etc...
To append $curr to $arr, you have to change the line in array_push( $arr, $curr ) or (better, as php recommends if only one element is appended) $arr[] = $curr;. After these changes, the $i++; line can be deleted.
$json = array(
"Daniel" => $arDaniel,
"Andi" => $arAndi,
"Dave" => $arDave,
"Simon" => $arSimon
);
echo json_encode($json);
$db = NULL;
Now your script is clean (I hope).
Your script remain a bit redundant. You can simplify it in this way:
$array = array( 'Daniel'=>array(), 'Andi'=>array(), 'Dave'=>array(), 'Simon'=>array() );
foreach( $array as $key => &$val )
{
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $key ORDER BY date(Datum)";
$result = $db->query( $query );
$val = $result->fetchAll( PDO::FETCH_ASSOC );
}
$json = json_encode( $array );
echo $json;
By this way, you init an array with names as key, then, in a foreach loop by reference (&$val) you perform a sql query searching in table $key and you fetch all results directly in array (in this example the values are stored as associative arrays, like in your example, but you can use PDO::FETCH_OBJ to store data as object). At the end, you encode the array end echo it.
Edit:
I see a previous answer nearly identical to mine...
BTW, I leave mine because I have spent a lot of time to explain various errors...

Pulling NHL Standings from XML Table with PHP

I'm working on a project in which I pull various statistics about the NHL and inserting them into an SQL table. Presently, I'm working on the scraping phase, and have found an XML parser that I've implemented, but I cannot for the life of me figure out how to pull information from it. The table can be found here -> http://www.tsn.ca/datafiles/XML/NHL/standings.xml.
The parser supposedly generates a multi-dimmensional array, and I'm simply trying to pull all the stats from the "info-teams" section, but I have no idea how to pull that information from the array. How would I go about pulling the number of wins Montreal has? (Solely as an example for the rest of the stats)
This is what the page currently looks like -> http://mattegener.me/school/standings.php
here's the code:
<?php
$strYourXML = "http://www.tsn.ca/datafiles/XML/NHL/standings.xml";
$fh = fopen($strYourXML, 'r');
$dummy = fgets($fh);
$contents = '';
while ($line = fgets($fh)) $contents.=$line;
fclose($fh);
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
print_r($arrOutput[0]); //This print outs the array.
class xml2Array {
var $arrOutput = array();
var $resParser;
var $strXmlData;
function parse($strInputXML) {
$this->resParser = xml_parser_create ();
xml_set_object($this->resParser,$this);
xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");
xml_set_character_data_handler($this->resParser, "tagData");
$this->strXmlData = xml_parse($this->resParser,$strInputXML );
if(!$this->strXmlData) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->resParser)),
xml_get_current_line_number($this->resParser)));
}
xml_parser_free($this->resParser);
return $this->arrOutput;
}
function tagOpen($parser, $name, $attrs) {
$tag=array("name"=>$name,"attrs"=>$attrs);
array_push($this->arrOutput,$tag);
}
function tagData($parser, $tagData) {
if(trim($tagData)) {
if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
}
else {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
}
}
}
function tagClosed($parser, $name) {
$this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this- >arrOutput)-1];
array_pop($this->arrOutput);
}
}
?>
add this search function to your class and play with this code
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
// first param is always 0
// second is 'children' unless you need info like last updated date
// third is which statistics category you want for example
// 6 => the array you want that has wins and losses
print_r($arrOutput[0]['children'][6]);
//using the search function if key NAME is Montreal in the whole array
//result will be montreals array
$search_result = $objXML->search($arrOutput, 'NAME', 'Montreal');
//first param is always 0
//second is key name
echo $search_result[0]['WINS'];
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, $this->search($subarray, $key, $value));
}
return $results;
}
Beware
this search function is case sensitive it needs modifications like match to
a percentage the key or value changing capital M in montreal to lowercase will be empty
Here is the code I sent you working in action. Pulling the data from the same link you are using also
http://sjsharktank.com/standings.php
I have actually used the same exact XML file for my own school project. I used DOM Document. The foreach loop would get the value of each attribute of team-standing and store the values. The code will clear the contents of the table standings and then re-insert the data. I guess you could do an update statement, but this assumes you never did any data entry into the table.
try {
$db = new PDO('sqlite:../../SharksDB/SharksDB');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "DELETE FROM standings";
$result = $db->query($query);
$xmlDoc = new DOMDocument();
$xmlDoc->load('http://www.tsn.ca/datafiles/XML/NHL/standings.xml');
$searchNode = $xmlDoc->getElementsByTagName( "team-standing" );
foreach ($searchNode as $searchNode) {
$teamID = $searchNode->getAttribute('id');
$name = $searchNode->getAttribute('name');
$wins = $searchNode->getAttribute('wins');
$losses = $searchNode->getAttribute('losses');
$ot = $searchNode->getAttribute('overtime');
$points = $searchNode->getAttribute('points');
$goalsFor = $searchNode->getAttribute('goalsFor');
$goalsAgainst = $searchNode->getAttribute('goalsAgainst');
$confID = $searchNode->getAttribute('conf-id');
$divID = $searchNode->getAttribute('division-id');
$query = "INSERT INTO standings ('teamid','confid','divid','name','wins','losses','otl','pts','gf','ga')
VALUES ('$teamID','$confID','$divID','$name','$wins','$losses','$ot','$points','$goalsFor','$goalsAgainst')";
$result= $db->query($query);
}

How to store string in an array? - PHP

I'm trying to store a string in an array, but it doesn't save the array:
<?php
session_start();
$username = $_POST["username"];
$password = $_POST["password"];
$users = array();
$passes = array();
/*if (isset($_SESSION['users'])) {
$users = unserialize($_SESSION['users']);
}
if (isset($_SESSION['passes'])) {
$passes = unserialize($_SESSION['passes']);
}*/
if (isset($_POST['button'])) {
$login_successful = false;
for ($i = 0; $i < count($_SESSION['user']); $i++) {
if ($username === $_SESSION['user'][$i] && $password === $_SESSION['pass'][$i]) {
echo "<p style=\"font-family: Open Sans\">Logged in as " .$users[$i] ."</p>";
$login_successful = true;
break; // no need to continue the loop here, so we break out of it
}
}
if (!$login_successful) {
echo "<p style=\"font-family: Open Sans\">Login Failed</p>";
}
}
else if (isset($_POST['register'])) {
$users = array_push($users, $username);
$passes = array_push($passes, $password);
$_SESSION['user'] = serialize($users);
$_SESSION['pass'] = serialize($passes);
echo "Made your account successfully! Go back to login";
}
else if (isset($_POST['userlist'])) {
$users = unserialize($_SESSION['users']);
$passes = unserialize($_SESSION['passes']);
for ($i = 0; $i < count($users); $i++) {
echo $user[$i];
echo $passes[$i];
}
}
?>
It doesn't save the array, it changes it only for the current page it was called on and then the array goes back to nothing.
Thanks in advance
You seem to have a huge misunderstanding of how PHP works. Each time a php script runs, it's like the first very first time it has ever ran. So, your array will be removed from memory when the script finishes.
However, if you want to carry data between requests, you can try a session.
session_start();//important
//YOUR EXISTING ARRAY
$array = array("element", "element 2", "element 3");
//ADD YOUR NEW ELEMENT TO THE ARRAY
$array = array_push( $array, "NEW ELEMENT" );
//store the new serialized (converted to string) array
$_SESSION['my_array'] = serialize( $array );
if ( isset($_SESSION['my_array']) ) {
//grab the serialized (string version) of the array, and convert it back to an array
$my_array = unserialize( $_SESSION['my_array'] ); //holds [0] => "el1", [1] => "el2"
}
Read more about sessions from the PHP manual.
You can also try cookies or storing the array into a database. Just know that cookies are stored on the user's computer, and sessions are stored on the server.
you can use array_push like this : $user=array_push($user,$username);
That's all!
let's do some improvement on Ryan Smith's solution to make it simpler
session_start();
$_SESSION['users'][] = 'Hello';
var_dump($_SESSION['users']);
// if you wanna use $users,
/*
if(isset($_SESSION['users'])) {
$users = unserialize($_SESSION['users']);
}
*/

Categories