PHP - How To Store File Names Derived From Glob() In Variable Array
Hi,
I want to store files to variable array using glob() like $files[0] = xyz.txt $files[1] = pqr.txt . . . $files[n] = nfile.txt I know how to list files from directory using glob() Code: [Select] <?php foreach (glob("*.txt") as $filename) { echo "$filename size " . filesize($filename) . "\n"; } ?> How can I do that ? Similar TutorialsAs you can see here I have the following code Code: [Select] <?php session_start(); session_register('hazard2'); //INITIALIZE ERROR VARIABLES $errorFound = false; $errorIcon['hazard2'] = ''; if (isset($_POST['submitbutton'])) { //SET SESSION VARIABLES $_SESSION['hazard2'] = $_POST['hazard2']; //TEST FORM INFORMATION if(count($_POST['hazard2']) != 3) { $errorFound = true; $errorIcon['hazard2'] = 'Error Question 2'; } //IF NO ERRORS WERE FOUND, CONTINUE PROCESSING if (!$errorFound) { header( "Location: hazardresult.php" ); } } ?> It's lazy I know, but the script is on a file called hazard2.php, is there anyway to have all of the hazard2's in the code come from the file name. So when I make hazard3, I don't have to change all the hazard2's to hazard3's Thank you hello, um i got a form that stored an array of variables upon users clicks. it submits to another page fine as an array and i can print them using if(!empty($_POST['langSpoken'])) { echo "\n<p><strong>You selected the following LangSpoken:</strong></p>\n<ul>"; foreach($langSpoken as $lang) { // exclude any items with chars we don't want, just in case someone is playing if(!preg_match('/^[-A-Z0-9\., ]+$/iD', $lang)) continue; // print the lang echo "\n\t<li>" . htmlspecialchars($lang) . "</li>"; } echo "\n</ul>"; } else { echo "\n<p>No items selected</p>"; } it prints a list a of array like english spanish but i need to store each one in one variable so i can store in a database is there a way? thanks I am attempting to us glob to display contents of a users folder using a session variable. Example: I have a session variable called department Code: [Select] $row_fullname['department']; In department I have the name of the department the user belongs to such as: office, plant, maintenance, and groundskeeping I created a folder called docs inside of docs there are 4 subfolders called office, plant, maintenance, and groundskeeping I found this code which will display the contents of the folder: Code: [Select] <?php $files = glob( './docs/office/*.*' ); foreach ( $files as $file ) { echo '<a href="./docs/office/' . basename( $file ) . '"target="_blank">' . basename( $file ) . '</a><br />'; } ?> The above code works fine, but I would like it to only display the contents of a departments folder only if the user is part on that department. Here is an example that I know is completely wrong but it may help explain what I am trying to do. Code: [Select] <?php ]<?php $files = glob( './docs/echo $row_fullname['department'];/*.*' ); foreach ( $files as $file ) { echo '<a href="./docs/echo $row_fullname['department'];/' . basename( $file ) . '"target="_blank">' . basename( $file ) . '</a><br />'; } ?>Thanks for your time I am using glob() to see a list of .zip files on my website. I wanted to display them on a drop down list. I got that working fine, but the file path shows up with it. Any idea how to remove it? Here is the code I am using. Code: [Select] <?php $dir = "/downloads/"; $files = glob($dir."*.zip", GLOB_NOSORT); echo'<select name="Files">'; foreach($files as $file){ echo'<option value="'.$file.'">'.$file.'</option>'; } echo'</select>'; ?> I would like to go from a glob list, which is working great, to a download link kinda thing. So, The glob list is shown and each file has a link. The problem is that the download folder for PHP is apparently NOT within my website, but in another portion of the server. Also that when I modify the code to work within the website, it doesnt work. Probably because of the glob array. Anyone have an idea on how to fix this? Code: Code: [Select] <?php $dir = "/downloads/"; $files = glob($dir."*.zip", GLOB_NOSORT); // echo'<select name="Files">'; foreach($files as $file){ // echo'<option value="'.$file.'">'.basename($file).'</option>'; echo '<p><a href="/downloads/'.basename($file).'">'.basename($file).'</a></p>'; }; // echo'</select>'; ?> My Php Buddies, I have mysql tbl columns these:
id: Now, I want to display their row data by excluded a few columns. Want to exclude these columns: date_&_time account_activation_code account_activation_status id_verification_video_file_url password
So, the User's (eg. your's) homepage inside his account should display labels like these where labels match the column names but the underscores are removed and each words' first chars CAPITALISED:
Id: 1
For your convenience only PART 1 works. Need help on Part 2 My attempted code:
PART 1 <?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Query to get columns from table $query = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'members' AND TABLE_NAME = 'users'"); while($row = $query->fetch_assoc()){ $result[] = $row; } // Array of all column names $columnArr = array_column($result, 'COLUMN_NAME'); foreach ($columnArr as $value) { echo "<b>$value</b>: ";?><br><?php } ?> PART 2 <?php //Display User Account Details echo "<h3>User: <a href=\"user.php?user=$user\">$user</a> Details</h3>";?><br> <?php $excluded_columns = array("date_&_time","account_activation_code","account_activation_status","id_verification_video_file_url","password"); foreach ($excluded_columns as $value2) { echo "Excluded Column: <b>$value2</b><br>"; } foreach ($columnArr as $value) { if($value != "$value2") { $label = str_replace("_"," ","$value"); $label = ucwords("$label"); //echo "<b>$label</b>: "; echo "$_SESSION[$value]";?><br><?php echo "<b>$label</b>: "; echo "${$value}";?><br><?php } } ?> PROBLEM: Columns from the excluded list still get displayed. Edited November 19, 2018 by phpsaneI am trying to use the variable $RATETHESE to include an array into file A. The array is in file B. PhP File A include_once(dirname(__FILE__) . '/PhpFileB.php'); global $RATETHESE; $VALID_RATING_IDS = $RATETHESE; Php File B $RATETHESE = "array("1", "2");" For some reason it is printing the array on the page, and the array is not being used to run the script. Did i do anything wrong? Hello, I have a variable called $Price, We are getting it through Mysql Database using While loop. We getting the data from database in ordered by ID. Now then i have requirement to store that data into Low to High form ... Like we are receiving $price lke unordered form .. 50 14 35 25 00 145 52 Here i just want to store it in Low to high form like 00, 14,25,35 ... and so on .. Please suggest me the appropriate code. While($myrow=mysql_fetch_array($result, MYSQL_ASSOC)) { some codes return value $price. // want to store in array } $array($price) // here want to store in Low to high with key value. I was wondering how I would go about doing a sorting of a new element being added on the page. This element would have to be alphabetically sorted into the existing elements onto the page. For example: I am making a file manager, so when a user creates a new file, it would be sorted into the already existing files and displayed in the spot that it should.
All necessary details would be provided by PHP, so I would only need help with the JavaScript part.
Honestly, I have no clue how I would get around to doing that. I was thinking earlier that it would involve looping through each class of file_name and getting the text() value. Then add all of the values into an array and sorting it somehow. Then it would be getting the <tr> of which file_name is before it, and then append under it somehow.
I'm not asking for any free code, but I was wondering which (JavaScript/JQuery) functions I would be looking for. I was also wondering if the idea I had would be beneficial or not, or if there were any other ways. Here is how the files are displayed as is:
<?php // There may be undefined variables, this is only part of it $return = '<table id="manager" class="table table-bordered"> <thead> <tr class="table_header"> <th><input id="select" type="checkbox"></th> <th>Name</th> <th>Size</th> <th>Last Modified</th> <th>Type</th> <th>Permissions</th> <th></th> </tr> </thead> <tbody>'; $path = $_SERVER['DOCUMENT_ROOT']; // Scan the directory and remove the paths from the result $files = array_diff(scandir($path), array(".", "..")); // Get the number of files in the directory $num_files = count($files); // If there are no files in the directory, return the empty directory variable we defined earlier if($num_files == 0) return $empty_dir; $directory_array = array(); $file_array = array(); foreach($files as $file) { // Set the path correctly $file_path = $path."/".$file; // If the item is a directory if(is_dir($file_path)) $directory_array[] = $file; // The item is a file else $file_array[] = $file; } // Sort each of the arrays alphabetically sort($directory_array); sort($file_array); // Merge the directories and files into one array - directories shown first $files = array_merge($directory_array, $file_array); // Loop through the items foreach($files as $file) { $file_name = $file; // Set the path correctly $file = $path."/".$file; // Get the information for the file if(is_dir($file)) $file_size = "--"; else $file_size = @filesize($file); if($file_size === false) { $checkbox = '<input id="files_check" type="checkbox" name="files[]" value="'.htmlentities($file_name).'">'; $file_name = htmlentities($file_name). " - <b>Fatal Error Reading</b>"; $file_size = "--"; $last_modified = "--"; $type = "--"; $permissions = "--"; $actions = "--"; } else { $finfo = finfo_open(FILEINFO_MIME_TYPE); $checkbox = '<input id="files_check" type="checkbox" name="files[]" value="'.htmlentities($file_name).'">'; if(is_dir($file)) { $file_name = '<i class="icon-folder-open"></i> <a href="manager.php?path='.htmlentities($file_name).'/">'.htmlentities($file_name).'</a>'; } else { $file_name = '<i class="icon-file"></i> <a href="manager/view_contents.php?file=/'.htmlentities($file_name).'&token='.htmlentities($_SESSION['secure_token']).'">'.htmlentities($file_name).'</a>'; } $file_size = htmlentities(get_appropriate_size($file_size)); $last_modified = htmlentities(get_appropriate_date(filemtime($file))); $type = htmlentities(finfo_file($finfo, $file)); $permissions = htmlentities(substr(sprintf('%o', fileperms($file)), -4)); $actions = '<i class="actions"></i>'; } $return .= "<tr> <td>{$checkbox}</td> <td class='file_name'>{$file_name}</td> <td>{$file_size}</td> <td>{$last_modified}</td> <td>{$type}</td> <td class='permissions'>{$permissions}</td> <td class='action'>{$actions}</td> </tr>"; } $return .= '</tbody> </table>'; return $return; ?> hi i am trying to make a payroll calculator script that takes employee info, calculates pay, displays submitted info in a table, stores info in an array, and updates the array when new info is submitted. i have most of these accomplished, i am having trouble with the "store into an array, and update the array when new info is submitted" parts of the project. i am still not very fluent in php so there may be easier ways to achieve what i have so far. any pointers would be a great help, this part has got me stumped. Quote i need to store a variable from database like if i have "copies" in one of my column in my database then i have to store a particular value for copies store it to $copies here i want that i can store value of copies into $copies $update_book="update book set copies=copies-1 where bookid='$bookid'"; $result=mysql_query($update_book,$linkID1); if($result) { print "<html><body background=\"header.jpg\"> <p>book successfully subtracted from database</p></body></html>"; } else { print "<html><body background=\"header.jpg\"> <p>problem occured</p></body></html>"; } } It seems that in the following script I am not able to make $page contain some values as it always acts as it contains 0. The script will give you more idea about what I wanna do with it. Code: [Select] <?php include('dbinfo.inc'); session_start(); $connect= mysql_connect($host,$dbuser,$password) or die("connect to database fails"); mysql_select_db($dbname, $connect); //This will set the number of messages we want to display on each page $rows_per_page = 5; function show_msg() { echo "<tr align='center'> <td>$row[message]</td> </tr> <tr><td><strong>Sent By: $_SESSION[username] ON Date: $row[date]</strong></td></tr> <tr><td></td></tr>"; } //This will set the necessay variables required to set the page layout function page_vars() { $sql = "select * from msgs"; $result = mysql_query($sql, $connect); $numrows = mysql_num_rows($result); $total_pages = ceil($numrows/$rows_per_page); //Check whether page is given or not if(isset($_GET["page"])) { $page = $_GET["page"]; } else { $page = 1; } if($page < 1): { $page = 1; } elseif($page > $total_pages): { $page = $total_pages; } endif; } if($_SESSION[loggedin] == TRUE && $_SESSION[actype] == lecturer) { echo "<form action='postmsg.php' method='POST'>"; echo "<table width='80%' border='1'><tr align='center'><td><strong>To send a new message type it in the below box and press SUBMIT</strong> </td></tr>"; echo "<tr align='center'> <td><textarea name='msgarea' cols='40' row='5'></textarea></td> </tr> <tr align='center'> <td><input type='submit' value='Send Message' /></td> </tr> </table>"; $limit .= 'LIMIT '.($page - 1)*$rows_per_page.', '.$rows_per_page; echo $limit; $sql = "select * from 'msgs' $limit"; $result = mysql_query($sql); echo "<table width='80%' border='1'>"; $row = mysql_fetch_assoc($result); while($row) { show_msg(); } } else { page_vars(); $limit .= 'LIMIT '.($page - 1)*$rows_per_page.', '.$rows_per_page; $sql = "select * from msgs $limit"; $result = mysql_query($sql,$connect); echo "<table width='80%' border='1'>"; while($row = mysql_fetch_assoc($result)) { show_msg(); } echo "<tr align='center'> <td> <a href='$_SERVER[php_self]?page=1'>First Page</a> <a href='$_SERVER[php_self]?page=($page - 1)'>$page</a> <a href='$_SERVER[php_self]?page=$page'>$page</a> <a href='$_SERVER[php_self]?page=($page + 1)'>$page</a> <a href='$_SERVER[php_self]?page=($total_pages)'>>>>Last Page</a> </td> </tr>"; echo "</table>"; } ?> now when i echo $limit it always shows "-5, 5" , that's not what i want from this script. Instead I want limit to store "0, 1" with the same concept not direct because it will change according to what $_GET[page] holds. Hope I will get the solution here.... Hi, I'm trying to edit some database fields, I have text1, text2, text3, text4, text5, text6 etc.. They are displayed on the index.php page, with an edit link so the user can choose which set to edit // Extract details from database $sql = "SELECT * FROM data WHERE id=1"; $stmt = $db->prepare($sql); $stmt->execute(); $e = $stmt->fetch(); <h1><?php echo $e['text1']) ?></h1> <p><?php echo ($e['text2']); ?></p> <p><a href="edit.php">EDIT</a></p> <h1><?php echo $e['text3']) ?></h1> <p><?php echo ($e['text4']); ?></p> <p><a href="edit.php">EDIT</a></p> <h1><?php echo $e['text5']) ?></h1> <p><?php echo ($e['text6']); ?></p> <p><a href="edit.php">EDIT</a></p>
edit.php: // Extract details from database $sql = "SELECT * FROM data WHERE id=1"; $stmt = $db->prepare($sql); $stmt->execute(); $e = $stmt->fetch(); <form method="post" action="process.php" enctype="multipart/form-data"> <label>Page Title <input type="text" name="text1" maxlength="90" value="<?php echo $e['text1'] ?>" /> </label> <br> <label>Title Text</label> <textarea name="text2"><?php echo $e['text2'] ?></textarea> <input id="button" type="submit" name="submit" value="Save Changes" /> and then update them: process.php $sql = "UPDATE data SET text1=?, text2=? WHERE id=1 LIMIT 1"; $stmt = $db->prepare($sql); $stmt->execute( array( $_POST['text1'], $_POST['text2'] ) ); $stmt->closeCursor(); Question: How can I pass the form values dynamically from the index.php page so I don't have to hard code text1, text2 etc into the edit.php and process.php page and have a different update & process page for each set of data?
Thanks in advance. Hi There, I would like to place the last for month names into an variable- for example: February 2011 January 2011 December 2010 November 2010 But I would like them to all have the same variable ($date) - so when I use it in a mssql_fetch_assoc - it increments with every instance of $date, as there will be one instance of $date for every row returned, getting older with every row. Hope that is enough info? Cheers Matt The Code Below is for my Colony Building page for my game. That particular code is supposed to display the number of buildings built, which it does, and also allow me to change the number of buildings built, which it doesn't. The code is part of a loop that displays all the possible buildings of a given type, in this case Iron Mines, that can be built on the colony. Basically what I need to know is, how do I change the name of the column that is being updated as the code loops. Currently it is setting all the forms to alter the number of Basic iron mines on a colony. I am hoping I can somehow call the names of all the columns into an array and use the same code that picks which column value i am selecting, the $?(an array)[$b](an incrementing number to call the correct array value): $?[$b]. Then I would replace Basic, in the column part of the UPDATE code with the array and result selector so that the first time i include() the code it creates the form and sets it to alter Basic, but the second time it sets the code to alter the value in the next column. Code: [Select] <?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = 'root'; $dbname = 'aosdb'; $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); $b=1; $queryp = "SELECT * FROM IMBuilt WHERE idcol = $idcol"; $resultp = mysql_query($queryp); $Base = mysql_fetch_row($resultp); if(isset($_POST["built"])) { if($_POST) { $Badd = $Base[$b]+$_POST["built"]; $queryi="UPDATE IMBuilt SET Basic=$Badd WHERE idcol = $idcol"; mysql_query($queryi); } } $queryf = "SELECT * FROM IMBuilt WHERE idcol = $idcol"; $resultf = mysql_query($queryf); $Basic = mysql_fetch_row($resultf); ?> <p class="bd" id="built">| Built: <?php echo $Basic[$b] ?> |</p> <form class="bd" method="post" action="IronMineList.php"><input type="varchar" name="built"><input type="submit" value="Build"></form> </div> Hello, I'm having some issues with PHP thinking that the variables that I send it are the actual columns in my database. First, I pull off Quadratic_Functions and introductory_problem from http://localhost:8888/algebra_book/Chapters/Quadratic_Functions/introductory_problem.php using the code below: Code: [Select] $chapter_page = $_SERVER['PHP_SELF']; $chapter_page_array = explode('/',$chapter_page); $size =count($chapter_page_array); $chapter = $chapter_page_array[$size-2]; $page = $chapter_page_array[$size-1]; $page_array = explode('.', $page); $page = $page_array[0]; Based on my printing of the variables $chapter and $page I think that it's doing what I want it to do. I then use the following function: Code: [Select] $supplemental_id = getSupplementalId($dbRead,$chapter,$page); to check out if the there's a supplemental_id for the Quadratic_Function chapter and introductory_problem page name via: Code: [Select] function getSupplementalId($read,$user_id,$chapter,$page) { $sql = "SELECT supplemental_id FROM instructors_supplemental WHERE page_name = $page AND chapter_name='$chapter"; return $read->fetchRow($sql); } If I stick in actual values, as seen below, the thing runs fine. Code: [Select] $sql = "SELECT supplemental_id FROM instructors_supplemental WHERE page_name = 'introductory_problem' AND chapter_name='Quadratic_Functions'"; But if I run it in the abstract version, with variables for page and chapter name (the first version), I get Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'introductory_problem' in 'where clause'' in... It's almost as if it thinks that my variables are the names of the columns. Any thoughts would be appreciated.... Currently I am adding the concept of "entitlements" to my website. In the past, my "article.php" script would simply look to the URL for which article was being requested and then load it. However now that I am also adding the concept of "premium content" for "paid members", I need a way to control who sees what. What I am wondering is - from a security standpoint - how much information I should load into the $_SESSION variable. For instance, right now when a user logs in, I think I just store the "memberID" and "FirstName" and possibly "Username". It would be more efficient when a Member logs in to also retrieve their "Membership Plan" and store that in the $_SESSION variable, so that as they browse my website, each page can simply grab $_SESSION['MembershipPlan'] and run that through a function that I need to build and then determine if the user gets to access said page. However, maybe it would be more secure to have it so when a user lands on page XYZ, I would look at their "memberID" and query the database to get their "MembershipPlan"? Any thoughts on each approach? Again, my main concern is *security*, but I also suppose this plays into "performance".
I am building a website that uses session variables extensively. The site is getting a little complicated, and I am starting to lose track of which session variables are assigned, and what their values are. Is there some way where I can create a piece of code that will display all of the existing session variables and their values? //multi query $sql= "SELECT option_value FROM settings WHERE option_name = 'email_temp_issue';"; //1 $sql .="SELECT title FROM books WHERE id = '$bookid';"; //2 $sql .="SELECT fullName from students WHERE email = '$username'"; //3 $sql_run = mysqli_multi_query($connection,$sql); if(mysqli_num_rows($sql_run)>0) { foreach ($sql_run as $row) { $email_template = $row['option_value']; //retrieve from query 1 $title = $row['title']; //retrieve from query 2 $name = $row['fullName']; //retrieve from query 3 } } I am trying to store the data from the multi query into each variable, which I am not sure how to do..Anyone can help? :) I'm trying to input the results from a query into html, but I'm just getting the variable names rather than their values. I used single quotes for the echo statement, but I think I must need to switch to double to do that. But then I have problems with the double quotes from the class names (ex. class="SideBoxTitle"). Code: [Select] <?php // get user's videos from database $conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error()); $query = "SELECT * FROM haas12_test.videos"; $result = mysqli_query($conn, $query) or die ("Couldn't execute query."); while($row = mysqli_fetch_assoc($result)) { extract($row); echo ' <div id="topBox" class="mainVideoSideBoxes" > <div class="SideBoxTitle" ><h3> $vidtitle </h3> </div><!-- close SideBoxTitle --> <div class="sideBoxVidContainer"> <div class="SideBoxScreenCast" > $vidurl </div><!-- close SideBoxScreenCast --> <div class="SideBoxDesc" ><p> $viddesc </p> </div><!-- close SideBoxDesc --> </div><!-- close sideBoxVidContainer --> </div><!-- close mainVideoSideBoxes --> </div><!-- close mainVideoSideBoxes --> '; // end echo staement } ?> |