Two arrays in foreach loop? - php

having difficulties because of my noobness, again. I dont know if I am doing this right, but I need to post an id variable with an array through a foreach loop to a mysql db. If that made no sense, its probably due to my lack of ability to articulate with technical jargon, so ill just post the code. Please view the notes in the PHP code.
Any help always appreciated.
Cheers, Lea
FORM:
<form method="post" action="<?php echo $PHP_SELF; ?>" enctype="multipart/form-data">
<?php
$num = 0;
while($num < $num_uploads)
{
?>
<input type="hidden" name="item_id[]" value="<?php echo $stockno; ?>" />
<input type="file" id="myfile" name="userfile[]" size="40">
<?php $num++;
}
?>
<input type="submit" name="Preview" value="Preview" />
</form>
PHP SCRIPT:
if(isset($_POST['Preview']) ) {
// START PHOTO QUERY
if(isset($_FILES['userfile']['tmp_name']))
{
/** loop through the array of files ***/
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
/*** check if the file is less then the max php.ini size ***/
elseif($_FILES['userfile']['size'][$i] > $upload_max)
{
$messages[] = "File size exceeds $upload_max php.ini limit";
}
// check the file is less than the maximum file size
elseif($_FILES['userfile']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['userfile']['tmp_name'][$i],$upload_dir.'/'.$_FILES['userfile']['name'][$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $_FILES['userfile']['name'][$i].' uploaded';
$name[] = $_FILES['userfile']['name'][$i];
$id[] = $_POST['item_id'];
// HAVING DIFFICULTIES HERE
foreach( $name as $value ) {
$sql = "INSERT INTO stock_photos (photo_filename) VALUES ('$value')";
mysql_query($sql);
foreach( $id as $val ) {
$sql2 = "UPDATE stock_photos SET photo_item_id = '$val' WHERE photo_filename = '$value'";
mysql_query($sql2) or die(mysql_error());
}
}
// END DIFFICULTIES HERE
}
else
{
/*** an error message ***/
$messages[] = 'Uploading '.$_FILES['userfile']['name'][$i].' Failed';
}
}
}
}
// END PHOTO QUERY
}

I think you have a flaw in your logic. You don't want to have a nested foreach loop. Think about it:
You are looping over each filename. For each filename, you are looping over all IDs and update the filename ID with with each value from the ID array. You are basically overwriting the ID in the database with every UPDATE call, eventually setting the value to the last value of the $id array.
Thus, you actually should have the loops one after each other.
Assuming your $name and $id are filled properly and both contain the same number of items, you can do even better, using a normal for loop:
for($i = 0; $i < count($name); $i++ ) {
$sql = "INSERT INTO stock_photos (photo_filename, photo_item_id) VALUES ('". mysql_real_escape_string($name[$i]) . "', '" . mysql_real_escape_string($id[$i] . "')";
mysql_query($sql);
}
Note: Never never never trust user input, so take precautions through filtering and escaping like I did with mysql_real_escape_string().
Update:
And you can do even better with just one MySQL query by inserting multiple values at once:
function prepare($name, $id) {
return sprintf("'%s', '%s'",
mysql_real_escape_string($name),
mysql_real_escape_string($id));
}
$values = array_map('prepare', $name, $id);
$sql = 'INSERT INTO stock_photos (photo_filename, photo_item_id) VALUES (' . implode('),(', $values) . ')';
mysql_query($sql);
Reference: sprintf, array_map, implode

Related

Save multiple text content from multiple .txt files with file_get_contents in my database in php

I'm working on a script that allows me to take .txt files content from a folder on my computer and read them with file_get_contents() then save them to my database, each time I manage to save only the first file, and I would like to save the contents of each file from the values ​​retrieved by the file_get_contents() or file() function (with for loop).
Thank you for your help !
Here's the code:
<?php
$pdo = require 'db_settings.php';
if(isset($_POST['submit'])){
$line1 = $_FILES['filetxt']["tmp_name"];
echo '<pre>';
$count = count($line1);
for ($i=0; $i < $count; $i++) {
$insert1 = file_get_contents($line1[$i]);
// Begin
try {
$sql = "INSERT INTO fill_wp (content) VALUES (:insert1)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(":insert1" => $insert1));
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
//End
echo '</pre>';
}
<form method='post' action='get_temp.php'>
<input type="text" name="urldirectory" id="textfileurl">
<input type='submit' name='submit' value='Upload'>
</form>

PHP: Want to keep a persistent variable when submitting form and reloading self-processing form

I am creating a workout logger using PHP and MySQL. The way I have it set up currently, the user uses a select to choose a workout template - and that value is POSTed to the form page. The template name is used to query the database for the names of all the exercises in that template and the number of sets per exercise. The names and sets are put into parallel arrays.
A function is called which generates the form. An element for the template name (ex. Full Body Workout), one for the exercise name (ex. Barbell Deadlift), and one for the set number, with a label/input pair for: weight, reps, rest, and notes.
Screenshot
The increment for the exercise name variable is a counter in $_SESSION, which gets incremented after each successful database insert.
My question is on the logic aspect. How can do I go about incrementing the $_SESSION variable without reseting it back to zero?
session_start();
//User
$user = $_SESSION['email'];
$date = date("Y-m-d");
//Get this script
$thisScript = htmlentities($_SERVER['PHP_SELF']);
//This is the value I want to keep persistent
$_SESSION['nameCount'] = (int)0;
$nameCount = $_SESSION['nameCount'];
//Value from select
$template = $_POST['mySelect'];
//Set log submit button
$logSubmit = $_POST['logSubmit'];
//Check if user is signed in
if ($user) {
if ($template) {
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
//Return query
$result = getResult($template); //Returns result of template
$numRows = getExerciseNum($result);
$exerciseArray = exerciseList($result, $numRows); //Returns set of exercises in template
//For some reason, $result and $numRows is empty after being passed into $exerciseArray
//Reinitialize
$result = getResult($template); //Returns result of template
$numRows = getExerciseNum($result); //numRows
$setsArray = getSets($result, $numRows); //Gets number of sets as array
//Reinitialize
$result = getResult($template); //Returns result of template
$numRows = getExerciseNum($result);
$exerciseIDArray = exerciseIDList($result, $numRows);
//Build form
buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date, $nameCount, $exerciseIDArray);
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} else if (empty($template)){
//Do something if template is empty
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
echo "<p>Seems the template is empty</p>\n";
echo "<p>Template = $template</p>\n";
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} //End if ($template)
} else if (!isset($user)) {
//If user not logged in
require("include/redirect.php");
}
Here are the relevant functions: Build log builds the form and the insert is with it
//Build log form using query result and exercise name increment ($x)
function buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date, $nameCount, $exerciseIDArray) {
$logSubmit = $_POST['logSubmit'];
if (!isset($logSubmit)) {
echo "<form action='$thisScript' method='POST' name='log' id='log'>\n";
echo "<fieldset>\n";
echo "<legend>$template</legend>\n";
echo "<h2>$exerciseArray[$nameCount]</h2>\n";
echo "<input type='hidden' name='exerciseArray[]' value='$exerciseArray[$nameCount]'/>\n";
$j = 1;
//Generate exercise form with loop
for ($i=0; $i < $setsArray[$i]; $i++) {
echo "<fieldset>";
echo "<legend>Set $j</legend>\n";
//Use $template in a hidden value to work around issue of value being lost after submitting form
echo <<<BODYDOC
<label>Weight</label>
<input type="text" name="weight[]" required /> \n
<label>Reps</label>
<input type="number" name="reps[]" required /> \n
<label>Rest Time</label>
<input type="number" name="rest[]" required /> \n
<label>Notes</label>
<textarea name="notes[]"></textarea>
<input type="hidden" name="set[]" value='$j' />
<input type="hidden" name='mySelect' value='$template' />
</fieldset>
BODYDOC;
$j++;
} //End form for loop
echo "<br /><button type='submit' name='logSubmit'>Submit</button>\n";
echo "</fieldset>\n";
echo "</form>\n";
echo "<p><a href='newday.php'>Back</a></p>\n";
//Increment exerciseNameArray counter so next form dispays next exercise name
} //End if empty submit
if (isset($logSubmit)) {
//POSTed
$template = $_POST['mySelect'];
$set = $_POST['set'];
$weight = $_POST['weight'];
$reps = $_POST['reps'];
$rest = $_POST['rest'];
$notes = $_POST['notes'];
$user = $_SESSION['email'];
//Increment exercise name counter
$nameCount++;
//Update Log
updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date, $nameCount, $exerciseIDArray);
} //End else if
} //End buildLog($template, $x) function
function updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date, $nameCount, $exerciseIDArray) {
//Insert data with query
$numRows = count($exerciseArray);
//Insert user,exercise name, and date
$insert = "INSERT INTO stats_resistance
(user, exerciseName, date)
VALUES
('$user','$exerciseArray[$nameCount]', '$date')"
or
die(mysql_error());
$result = mysql_query($insert)
or
die("<b>Query Failed</b><br>$insert<br>" . mysql_error());
//Query for stat_ID
$query = "SELECT statsID
FROM stats_resistance
WHERE user = '$user'
AND exerciseName = '$exerciseArray[$nameCount]'
AND date = '$date'";
//Get result
$result = mysql_query($query)
or
die("<b>Query Failed</b><br>$query<br>" . mysql_error());
$statsID = mysql_fetch_object($result);
$statsID = $statsID->statsID;
//echo "statsID = " . $statsID;
//Insert into resistanceSets with statsID as foreignKey
//Can insert multiple value sets by including comma after set parentheses
$insert = "INSERT INTO resistanceSets
(statsID, exerciseID, setID, exerciseName, weight, numReps, rest, notes)
VALUES
('$statsID', '$exerciseIDArray[$nameCount]', '$set[0]', '$exerciseArray[$nameCount]', '$weight[0]', '$reps[0]', '$rest[0]', '$notes[0]'),
('$statsID', '$exerciseIDArray[$nameCount]', '$set[1]', '$exerciseArray[$nameCount]', '$weight[1]', '$reps[1]', '$rest[1]', '$notes[1]'),
('$statsID', '$exerciseIDArray[$nameCount]', '$set[2]', '$exerciseArray[$nameCount]', '$weight[2]', '$reps[2]', '$rest[2]', '$notes[2]')";
$result = mysql_query($insert)
or
die("<b>Query Failed</b><br>$insert<br>" . mysql_error());
//buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date, $nameCount, $exerciseIDArray);
} //End updateLog()
It's a simple matter of ensuring the variable is set, if it is then increment it like any other variable.
if(isset($_SESSION['nameCount'])) {
$_SESSION['nameCount']++;
}
Alternatively, given you've set the value of the session variable to a local variable you can increment this local variable and reassign that value to the session variable. I.e.
$nameCount++;
$_SESSION['nameCount'] = $nameCount;
Both will have the same result.

check if file input field is empty using foreach loop

I have 7 file input fields namely:
<input type="file" accept="image/*" name="imgreq1">
<input type="file" accept="image/*" name="imgreq2">
<input type="file" accept="image/*" name="imgreq3">
<input type="file" accept="image/*" name="imgreq4">
<input type="file" accept="image/*" name="imgreq5">
<input type="file" accept="image/*" name="imgreq6">
<input type="file" accept="image/*" name="imgreq7">
How can I check if the other input fields are empty if I for example uploaded a file in the first and the second input fields. Then submit the form leaving the other fields empty?
Update:
<?php
if(isset($_POST['sumit'])){
$count = count($_FILES);
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name']) || !file_exists($_FILES['imgreq'.$i]['tmp_name'])){
echo "$i";
// your code
}else{
//to retrieve user_id to stored in the request table in the database
$query = "SELECT * FROM dummyclients_tbl WHERE user_id = '".$_SESSION['user']."'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_assoc($result)){
$sid= ''.$row['user_id'].'';
$coll=''.$row['college'].'';
$stat="Pending";
//$query="SELECT document_name FROM document_tbl WHERE document_id = '$passed_id'";
//$dn=mysql_query($query);
//$getname=mysql_fetch_assoc($dn);
//var_dump($getname);
//to analyze the contents of the image selected in filebrowser1
$image1=addslashes($_FILES['imgreq1']['tmp_name']);
$name1=addslashes($_FILES['imgreq1']['name']);
$image1=file_get_contents($image1);
$image1=base64_encode($image1);
//to analyze the contents of the image selected in filebrowser2
$image2=addslashes($_FILES['imgreq2']['tmp_name']);
$name2=addslashes($_FILES['imgreq2']['name']);
$image2=file_get_contents($image2);
$image2=base64_encode($image2);
//to analyze the contents of the image selected in filebrowser3
$image3=addslashes($_FILES['imgreq3']['tmp_name']);
$name3=addslashes($_FILES['imgreq3']['name']);
$image3=file_get_contents($image3);
$image3=base64_encode($image3);
//to analyze the contents of the image selected in filebrowser4
$image4=addslashes($_FILES['imgreq4']['tmp_name']);
$name4=addslashes($_FILES['imgreq4']['name']);
$image4=file_get_contents($image4);
$image4=base64_encode($image4);
//to analyze the contents of the image selected in filebrowser5
$image5=addslashes($_FILES['imgreq5']['tmp_name']);
$name5=addslashes($_FILES['imgreq5']['name']);
$image5=file_get_contents($image5);
$image5=base64_encode($image5);
//to analyze the contents of the image selected in filebrowser6
$image6=addslashes($_FILES['imgreq6']['tmp_name']);
$name6=addslashes($_FILES['imgreq6']['name']);
$image6=file_get_contents($image6);
$image6=base64_encode($image6);
//to analyze the contents of the image selected in filebrowser7
$image7=addslashes($_FILES['imgreq7']['tmp_name']);
$name7=addslashes($_FILES['imgreq7']['name']);
$image7=file_get_contents($image7);
$image7=base64_encode($image7);
//function nga defined sa dalum para i insert ang uploaded files sa databasess
saveimage($sid,$passed_id,$image1,$image2,$image3,$image4,$image5,$image6,$image7,$stat,$coll);
}
}
}
}
}
function saveimage($sid,$passed_id,$image1,$image2,$image3,$image4,$image5,$image6,$image7,$stat,$coll){
$con=mysql_connect("localhost","root","");
mysql_select_db("dummy",$con);
$qry="INSERT INTO request_tbl (user_id,document_id,imgreq1,imgreq2,imgreq3,imgreq4,imgreq5,imgreq6,imgreq7,request_status,college) VALUES ('$sid','$passed_id','$image1','$image2','$image3','$image4','$image5','$image6','$image7','$stat','$coll')";
$result=mysql_query($qry,$con);
if($result){
?>
<script>alert('Requirements Successfully Submitted!');</script>
<?php
}else{
?>
<script>alert('Error while submitting form!');</script>
<?php
}
}
?>
From OP's comment,
But how can you do it using for each loop this feature of php is a deep one ...
Use a simple for loop, in conjunction with is_uploaded_file() function, to check whether user has uploaded a file via HTTP POST or not, like this:
$count = count($_FILES);
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name'])){
// user has uploaded a file
}
}
Update:
Based on the below discussion with OP, the complete solution would be like this:
<?php
if(isset($_POST['sumit'])){
$count = count($_FILES);
$query = "SELECT * FROM dummyclients_tbl WHERE user_id = '".$_SESSION['user']."'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
if(mysql_num_rows($result)){
$row = mysql_fetch_assoc($result);
$sid = $row['user_id'];
$coll =$row['college'];
$query = "INSERT INTO request_tbl (user_id,document_id,imgreq1,imgreq2,imgreq3,imgreq4,imgreq5,imgreq6,imgreq7,request_status,college) VALUES ('$sid','$passed_id'";
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name']) && $_FILES['imgreq'.$i]['size']){
$query .= ",'" . base64_encode(file_get_contents(addslashes($_FILES['imgreq'.$i]['tmp_name']))) . "'";
}else{
$query .= ",NULL";
}
}
$query .= ",'$stat','$coll')";
saveimage($query);
}
}
function saveimage($qry){
$con = new mysqli("localhost", "root", "", "dummy");
$result=mysqli_query($con, $qry);
if($result){
?>
<script>alert('Requirements Successfully Submitted!');</script>
<?php
}else{
?>
<script>alert('Error while submitting form!');</script>
<?php
}
}
?>
As a sidenote, learn about prepared statement as it prevents your query from any kind of SQL injection attacks. Here's a good read on how you can prevent SQL injection in PHP.

<input type = "file"> EMPTY

i have this problem regarding file upload on php.
I always get this error msg.
Warning: file_get_contents(): Filename cannot be empty in
C:\xampp\htdocs\omf2\emprecords\add8.php on line 25
this is my line 25
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
But still saves the info on my database.
What i am trying to do is save the rest of the records on my database even if not selecting a file to upload. And yes the records are saved and the Attachment field (mediumblob) is [BLOB - 0 B]
Question: How can i eliminate the error/warning message? (because everything is really fine)
<meta http-equiv="refresh" content="2;URL='emphistory.php'">
<?php
{
echo "<center><font color='#AAA' size='3'><br/>Record Added!</center>";
}
?>
<?php
$con=mysqli_connect("localhost","root","","dbomf");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM valueholder");
$row = mysqli_fetch_array($result);
$count = '';
$IDNUM = $row['Val'];
$NS = addslashes($_POST ['NS']);
$ad = addslashes($_POST ['ad']);
$hr = addslashes($_POST ['HR']);
$name = $con->real_escape_string($_FILES['uploaded_file']['name']);
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
include ('../dbconn.php');
$query = "INSERT INTO tblemphist1 VALUES
('".$count."', '".$IDNUM."', '".$NS."', '".$ad."', '".$hr."', '".$data."', '".$name."')";
$result = $db->query($query) or die($db->error);
$db->close();
here
<form method="post" action="add8.php" enctype="multipart/form-data">
<td><strong>Attachment</strong></td>
<td>:</td>
<td><input type="file" name="uploaded_file"></td>
</tr>
</form>
<input type = "file">
should be
<input name="uploaded_file" type = "file">
also form method should be post and use enctype='multipart/form-data
<form action="" method="post" enctype="multipart/form-data">
<input name="uploaded_file" type = "file">
</form>
also check
$name = ''; $data = '';
if ((is_uploaded_file($_FILES['uploaded_file']['tmp_name']) && !($_FILES['uploaded_file']['error'])) {
$name = $con->real_escape_string($_FILES['uploaded_file']['name']);
$data = $con->real_escape_string(#file_get_contents($_FILES['uploaded_file']['tmp_name']));
}
include ('../dbconn.php');
$query = "INSERT INTO tblemphist1 VALUES ('".$count."', '".$IDNUM."', '".$NS."', '".$ad."', '".$hr."', '".$data."', '".$name."')";
$result = $db->query($query) or die($db->error);
Use an if statement. For example:
if (!empty($_FILES)) {
$data = $con->real_escape_string(
file_get_contents($_FILES['uploaded_file'] ['tmp_name'])
);
}
Before accessing any property of $_FILES['uploaded_file'] you have to check the value $_FILES['uploaded_file']['error']. And yes, it's a good idea to check if such key exists at all - as with anything coming from the user, there is no guarantee that it exists in the request.
Simply check if the variable is not empty
$data = '';
if (!empty($_FILES['uploaded_file']['tmp_name'])) {
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
}
if error doesn't affect your project just ignore it and add this code in top of your php.
<?php ERROR_REPORTING(E_ALL & ~E_NOTICE); ?>
it will ignore and hide the error. :)

How to upload image and save path to database?

I have a page where some images are shown (database driven). Here is the code of my gallery.php :
<ul id="portfolio-list" class="gallery">
<?php
$sql="select * from eikones ";
$res=mysql_query($sql);
$count=mysql_num_rows($res);
for ( $i = 0; $i < $count; ++$i )
{
$row = mysql_fetch_array( $res );
$co=$i+1;
if(isset($row[ "path" ]))
{
$path= $row[ "path" ];
}
if(isset($row[ "auxon" ]))
{
$auxon = $row[ "auxon" ];
}
if($_SESSION['role'] == "admin")
echo "<li class=\"pink\"><img src=\"$path\" alt=\"Pic\"></li>\n";
}
?>
</ul>
Now I want to have a form where I will be able to upload an image. I am trying this but it doesn't work :
<form enctype="multipart/form-data" action="gallery.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
include 'conf.php'; //database connect
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO eikones"; //table name = "eikones" and it has two columns named "auxon" and "path". The auxon is the id.
$query .= "(image) VALUES ('','$data')";
$results = mysql_query($query, $link) or die(mysql_error());
print "DONE";
}
else {
print "NO IMAGE SELECTED";
}
?>
It says "NO IMAGE SELECTED" and nothing new comes into the database.
After some hours I found a solution. It works. Although I would still be happy to find a second solution (according to the code I first posted here). Here is the second solution :
form page :
<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
insert to database page :
<?php
include 'conf.php';
if ($_FILES["image"]["error"] > 0)
{
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
echo"<font size = '5'><font color=\"#0CF44A\">SAVED<br>";
$file="images/".$_FILES["image"]["name"];
$sql="INSERT INTO eikones (auxon, path) VALUES ('','$file')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<font size = '5'><font color=\"#0CF44A\">SAVED TO DATABASE";
}
mysql_close();
?>
There are plenty of small classes you can download to handle your image uploads. Here's something small I just coded up. It will allow you to set validation for file type and file size. Feel free to make some methods private or hardcode the protected variables in the constructor if you know they'll always be the same. It may need a little work, but you can either use this class or pull out the bits you need to do it procedurally. Forgive any minor errors.
class ImageUploader{
protected
$size_limit,
$allowed_extensions;
$failed_saves;
public function __construct(int $limit, array $extensions){
$this->size_limit = $limit;
$allowed_extensions = $extensions;
}
public function saveImage(array $images){
foreach($images as $image){
if($this->meetsSizeLimit($image['size'])){
if($this->hasValidExtension(end(explode(".", $image["name"])))){
$this->storeImage($image, $this->getNextImageIndex());
}
else $failed_saves[$image["name"] = "Invalid file type.";
}
else $failed_saves["name"] = "File is too large.";
}
return $failed_saves;
}
public function meetsSizeLimit(int $size){
return $size <= $this->size_limit;
}
public function hasValidExtension(string $extention){
return in_array($extension, $this->allowed_extensions)
}
public function storeImage($image, $unique_id){
move_uploaded_file($image["tmp_name"], "you_relative_file_path" . $image["name"]);
rename('your_relative_file_path' . $image["name"], 'your_relative_file_path/img' . $unique_id . '.' . $extension);
//Place your query for storing the image id and path in table 'eikones'
}
public function getNextImageIndex(){
//Code to get the next available image id or MAX(id) from table 'eikones'
}
}

Categories