How to store string in an array? - PHP - 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']);
}
*/

Related

How do you retrieve an array based on user input?

This is the data in the text file contain the data
I have already store the data in the array
enter image description here
<?php
if (!(isset($_GET['job_title']) && empty($_GET['job_title']))) {
$job_title = $_GET['job_title'];
echo $job_title;
$filename = __DIR__ . '/jobpost.txt';
if (file_exists($filename)) {
$data= null;
$allData = array();
$handle = fopen($filename, "r");
while (!feof($handle)) {
$onedata = fgets($handle);
if ($onedata != "") {
$data = explode("\t", $onedata);
$allData[] = $data;
}
}
echo "<pre>";
print_r($allData);
echo "</pre>";
} else {
echo "file does not exist";
}
} else {
echo "<p class=\"bg_danger\"> must enter the job title </p>";
}
?>
My question is when user enter an input "software engineering" and based on the input value, must retrieve the related the array.
First don't forget to filter/sanitize your user inputs.
Now Check while storing data into the array if you can create a array with keys as "software engineering"
if that's not possible you can loop through array once & create array you need
$arrNewDataArray = [];
foreach( $dataArray as $arr ){
$arrNewDataArray[$arr[1]] = $arr;
}
Then you will be able to check if user input value is present in the array & retrieve it like below.
$userinput = 'software engineering';
$arrayYouNeed = [];
if( isset( $arrNewDataArray[$userinput] ) ) {
$arrayYouNeed = $arrNewDataArray[$userinput];
}

Move information from one variable to another (same page)

Since i have many diffrent workers on my workkey and i just want to print every work once. I Though of doin a check like this.
At the end of the loop i wanna save the value from workkey. So before every print i will check, If the new workkey is diffrent from the last one = Dont print.
$counter = 0;
while(db2_fetch_row($queryexe)) {
$work = db2_result($queryexe, 'workkey');
$fname = db2_result($queryexe, 'fname');
$lname = db2_result($queryexe, 'lname');
if ($workkey != $saveworkkey){
$counter = 0;
}
if ($counter < 1){
print ( some stuff)
print ( some stuff)
print ( some stuff)
}
$workkey = $saveworkkey;
$counter++;
}
What I do to solve the issue is to add all values to an array with the key as array key. This way, even if there are duplicates they will overwrite eachother.
$workers = array()
while ($record = db2_fetch_row($queryexe)) {
$workers[$record['workkey']] = $record;
}
To print your values you can simply foreach
foreach ($workers as $worker) {
// print worker
}

Issue Querying LDAP in 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.

Retrieve all values in my loop and format it to json

I'm trying to build a page which queries my database and then formats output so another webservice/page can access the data.
Ideally I wanted to explore having the data in JSON format, but that is not working. The other problem I have which is more major than the JSON not working is, if I have 3 records in $reportsResult, only the last one is displayed.
Anyone with some help please. Oh do I also need to print_r for the external webpage to retrieve the data or is there a better way?
class Pupil {
public $FirstName = "";
public $LastName = "";
}
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
}
json_encode($Pupil);
OK managed to figure out how how to get all records from the loop, but its still not displaying in json format when I do a print_r - am I missing something?
$AllPupils = array();
foreach($reportsResult->getRecords() as $reportRecord)
{
$Pupil = new Pupil();
$Pupil->FamID = $reportRecord->getField('FName');
$Pupil->ChildName = $reportRecord->getField('SName');
array_push($AllPupils, $Pupil);
}
json_encode($AllPupils);
Everytime your foreach loop starts again, it will override your $Pupil variable.
Try an array instead:
$Pupil = array()
$i = 0;
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil[$i] = new Pupil();
$Pupil[$i]->FirstName = $reportRecord->getField('FName');
$Pupil[$i]->LastName = $reportRecord->getField('SName');
$i++;
}
echo json_encode($Pupil);
Edit: mikemackintosh's solution should also work and could be a little bit faster (depending on the size of your foreach loop).
To display the results you need to echo your data (not only json_encode).
You will probably run into issues since json_encode wont handle the whole object. for that, you may want to serialize the $Pupil object.
Something like below may work for you though. It will assign the values to a returned array, which will allow json_encode to execute gracefully:
class Pupil {
public $FirstName = "";
public $LastName = "";
public function getAttr(){
return array("FirstName" => $this->FirstName, "LastName" => $this->LastName);
}
}
$json = array();
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
$json[] = $Pupil->getAttr();
}
echo json_encode($json);
I am not sure why you have that class defined, but you know what in your for each have something like
foreach ($reportsResult->getRecords() as $key => $record) {
$data[$key]['firstname'] = $record->getField('Fname');
$data[$key]['lastname'] = $record->getField('Sname');
}
And then you can check the final array using print_r
and while output you can simply do a print json_encode($data) and it will give you a json string of all the items in the data array.
In php (at least), json_encode takes an array as parameter.
Therefore you should add a constructor to your class
function __construct($first, $last)
{
this.$FirstName = $first;
this.$LastName = $last;
}
and one for getting the full name as an array, ready to be jsoned
function getNameArray()
{
$nameArray = array();
$nameArray['firstName'] = this.$FirstName;
$nameArray['lastName'] = this.$LastName;
return $nameArray;
}
then in that foreach you build another array with all the pupils
$pupils = array();
foreach (bla bla)
{
$first = $reportRecord->getField('FName');
$last = $reportRecord->getField('SName');
$Pupil = new Pupil($first, $last);
array_push($pupils, $pupil.getNameArray());
}
finally, you have everything preped up
json_encode($pupils);
I'm sure there's other ways to debug your stuff, I use print_r mainly also.

Serialize BEFORE the mysql_fetch_array?

I'm trying to use memcache but I'm stuck on a small part. I've got a function that gives in result an array of several things (most of them being strings), and one of them is the result of the mysql_query() function.
Here is how I am trying to unserialize:
$posts_count = my query;
/* MEMCACHE KEY GEN*/
$memcache_key = md5($posts);
$pagination = memcache_get($memcache, $memcache_key);
if($pagination==NULL) {
echo 'NOT CACHED';
$pagination = (the function that will call mysql_query)
//SAVE A SERIALIZED VERSION OF THE ARRAY
$memcache->set($memcache_key, serialize($pagination), 0, 3600);
}
else {
$pagination = unserialize($pagination);
}
//THIS IS ONLY THE RESULT OF mysql_query!!!
$posts = $pagination[result];
while($var = mysql_fetch_array($posts)) { ... stuffs here }
Any idea on how to "save" this result of mysql_query before the mysql_fetch_array? Or any idea how to use memcache to cache the whole while loop?
How about something like this:
$posts_count = "my query";
/* MEMCACHE KEY GEN*/
$memcache_key = md5($posts);
$pagination = memcache_get($memcache, $memcache_key);
if ($pagination == NULL) {
echo 'NOT CACHED';
$pagination = function_that_will_call_mysql_query();
// Create an array of all the results
$data = array();
while ($row = mysql_fetch_assoc($pagination['result'])) {
$data[] = $row;
}
$pagination['result'] = $data;
//SAVE A SERIALIZED VERSION OF THE ARRAY
$memcache->set($memcache_key, serialize($pagination), 0, 3600);
} else {
$data = unserialize($pagination);
}
// THIS IS ONLY THE RESULT OF mysql_query!!! (but now it's an array)
$posts = $pagination['result'];
while ($var = array_shift($posts)) {
// ... do stuff here
}

Categories