I have a problem with this code.. When I post 3 images, the script inserts just last one in database.. How can i solve this?
Here's my code:
<?php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$valid_formats = array("jpg", "png", "gif", "bmp");
$max_file_size = 1024*2220; //100 kb
$path = "galerija/"; // Upload directory
$count = 0;
$key = generateRandomString();
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to execute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "Slika $name je pre velika!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "Ekstenzija $name nije valjana!";
continue; // Skip invalid file formats
} else { // No error found! Move uploaded files
if (move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$key.$name)){
$model->naziv = $key.$name;
$model->save();
}
}
}
}
}
?>
I think I should probably put some code after } else { //No error found, but i don't know what :S
You need to create an instance each time like below:
$model=new ModelName();
$model->naziv = $key.$name;
$model->save();
Related
I'm trying to process multiple files upload with foreach then rename the files with random string and store the file names in an array, here's my current code:
// this variable stores the id of last inserted row in MySQLi DB
$last_shipment_id = mysqli_insert_id($con);
// Array of valid file formats
$valid_formats = array("jpg", "jpeg", "png");
// the upload path
$path = "../uploads/"; // Upload directory
// count variable for foreach counting
$count = 0;
// variable for generated file names to use them later
$new_file_name = array();
foreach ($_FILES['files']['name'] as $f => $name) {
$ext = pathinfo($name, PATHINFO_EXTENSION);
$new_file_name[] = randomNumber(14)."-".$last_shipment_id.'.'.$ext;
if ($_FILES['files']['error'][$f] == 4) {
continue;
}
if ($_FILES['files']['error'][$f] == 0) {
if( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue;
} else {
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$new_file_name)) {
}
}
}
}
I can't find where the problem is, should I use foreach for every generated file name then use move_uploaded_file inside the foreach?
You are completely wrong. You have initialized $_FILES['files']['name'] in the foreach statement and trying to access $_FILES['files']['error'] and $_FILES["files"]["tmp_name"] in each iteration. Since this is an array it not possible.
So solution is as follows,
foreach($_FILES as $key=>$row){
$ext = pathinfo($row[$key]['files']['name'], PATHINFO_EXTENSION);
$new_file = randomNumber(14)."-".$last_shipment_id.'.'.$ext;
array_push($new_file_name,$new_file);
if ($row[$key]['files']['error'] == 4) {
continue;
}
if ($row[$key]['files']['error'] == 0) {
if( ! in_array($ext, $valid_formats) ){
$error_msg = "The file ". $new_file. " is not a valid format";
array_push($message, $error_msg);
continue;
} else {
if(move_uploaded_file($row[$key]["files"]["tmp_name"], $path.$new_file_name[$key])) {
}
}
}
}
Hope this can help you.
i tried to apply some of the existing samples found here in stackoverflow but the problem seems to be unsolved.
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*1000;
$path = "upload/";
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ) {
$message[] = "$name is not a valid format";
...
As urfusion said, $_FILES['files']['name'] is a string, not an array.
That you can do to iterate over all the filenames of submitted files is something like that:
if(is_array($_FILES['files']) && !empty($_FILES['files'])){ // if1
foreach($_FILES['files'] as $file_index=>$file_value){
if($file_index==='name'){ // if2
echo $file_value; // or do something with that name
} // end if2
} // end foreach
} // end if1
Okay so, the below php upload script already WORK, the part didn't work is only of renaming file if exist.
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
foreach ($_FILES['files']['name'] as $f => $img_name) {
if ($_FILES['files']['error'][$f] == 4) {
continue;
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$img_name est trop lourde !";
continue;
}
elseif( ! in_array(pathinfo($img_name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$img_name est pas valide !";
continue;
}
else{
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$img_name)) {
while(file_exists($path . $img_name)){
$increment++;
$img_name = $name.$increment.'.'.$extension;
$count++;
}
}
}
}
}
}
I have search a lot on php doc, try fews fews way to go but .. when i'm trying a file with a name already uploaded before, it's not changing the actual upload file.
You are determining the filename after you upload the file. determine it before.
Change like:
while(file_exists($path . $img_name)){
$increment++;
$img_name = $name.$increment.'.'.$extension;
$count++;
}
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$img_name)) {
// File Uploaded !!!
}
Edit:
I have changed your code. Comments in code.
$valid_formats = array("jpg", "JPG", "png", "PNG" , "bmp", "BMP");
$max_file_size = 1024*6000; //60 000 kb - 6 mb
$path = "../../../img/final/img_recipes/"; //directory
$count = 0;
$uploaded_image_names = array(); //create a new array
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
foreach ($_FILES['files']['name'] as $f => $img_name) {
if ($_FILES['files']['error'][$f] == 4) {
continue;
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$img_name est trop lourde !";
continue;
}
elseif( ! in_array(pathinfo($img_name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$img_name est pas valide !";
continue;
}
else{
// Moved name and extension initialization to here.
// Here is where you want to determine the actual filename
$name = pathinfo($img_name, PATHINFO_FILENAME);
$extension = pathinfo($img_name, PATHINFO_EXTENSION);
$increment = 0;
while(file_exists($path . $img_name)){
$img_name = $name.$increment.'.'.$extension;
$increment++;
}
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$img_name)) {
$count++;
//Store the uploaded filenames to array here
$uploaded_image_names[] = $path.$img_name;
}
}
}
}
}
foreach ($uploaded_image_names as $uploaded_image_name){
//store the $uploaded_image_name to db
}
Note: I have not tested this, as I don't have PHP available with me now.
I'm trying upload multiple images. Below you can see my code.
Image uploaded massage repenting (exactly the amount of image chosen to upload.)
How can i show "Image uploaded" massage only ones on successful submit?
If i put the message after the loop it will start to show no matter if there is any errors.
This is my PHP code:
<?php
error_reporting(0);
session_start();
include('db.php');
$id = $mysqli->escape_string($_GET['id']);
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "gallery/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$mysqli->query("INSERT INTO galleries(image) VALUES('$image_name')");
echo "Image uploaded";
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
}
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
?>
Any help will be appropriated.
You can implement a counter and when an upload completes successfully you can increment that counter variable then compare it against total number of array items after foreach loop completes. I modified your code for this (haven't checked it but should work).
<?php
error_reporting(0);
session_start();
include('db.php');
$id = $mysqli->escape_string($_GET['id']);
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "gallery/"; //a directory inside
$successfulUploads = 0;
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)) {
if ($size < (MAX_SIZE*1024)) {
$image_name=time().$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) {
$mysqli->query("INSERT INTO galleries(image) VALUES('$image_name')");
//echo "Image uploaded";
$successfulUploads = $successfulUploads + 1;
} else {
echo '<span class="imgList">Moving unsuccessful! </span>';
}
} else {
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
} else {
echo '<span class="imgList">Unknown extension!</span>';
}
}
if($successfulUploads === count($_FILES['photos'])){
echo 'UPLOAD SUCCESS!';
} else {
echo 'NOT ALL IMAGES WERE UPLOADED SUCCESSFULLY';
}
}
*If you wanted to get more complex with it you could create another array variable instead of a counter and if the upload fails you could add the file name to the array and then check the length of the array where I'm doing the comparison. If count > 0 then you would know there was an error and you could echo the filenames that failed to upload
I been working on this image script for too long now, and I still can't seem to get two things to work - the image type and error handling (if the fields are empty). I have the code for this, but every place I try to add it, it doesn't work.
my code:
$error_message="";
$MaxSize = "600000";
if (isset($_POST['btn_update'])){
function createRandomPassword() {
$chars = "abcde!##%^fghijkmnoABCDEFGHIJKpqrstuvwxyz023456789ABCDEFGHIJKLMNOPQRSTUVWZ!##%^&";
srand((double)microtime()*10000000);
$i = 0;
$pass = '' ;
while ($i <= 19) {
$num = rand() % 60;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
if ($_FILES['aMyUploads0']['size'] > $MaxSize || $_FILES['aMyUploads1']['size'] > $MaxSize || $_FILES['aMyUploads2']['size'] > $MaxSize)
{
$error_message = "ERROR: File too big!";
}
$aMyUploads = array();
$password = createRandomPassword();
foreach($_FILES as $aFile)
{
$newLocation = 'uploads/'.$password .$aFile["name"];
if(0 === $aFile['error'] && (false !== move_uploaded_file($aFile['tmp_name'], $newLocation)))
{
$aMyUploads[] = $newLocation;
}
else
{
$aMyUploads[] = '';
}
}
$error_message="Journal successfully saved.";
$connection = mysql_connect("localhost", "????", "???");
mysql_select_db("????", $connection);
$insert = "INSERT INTO photos (image1, image2, image3) VALUES
(
' ".$aMyUploads[0]." ',
' ".$aMyUploads[1]." ',
' ".$aMyUploads[2]." '
)";
$add_member = mysql_query($insert) or die(mysql_error());
}
code im trying to add with no luck:
//ERROR HANDLING CODE:
if(empty($aMyUploads[0]) || empty($aMyUploads[1]) || empty($aMyUploads[2]))
{
$error_message="Please fill in all fields.";
}
else
{
$error_message="Journal successfully saved.";
//IMAGE TYPE CODE:
$allowed_filetypes = array(".jpg", ".gif", ".jpeg", ".png");
$ext = substr($newLocation, strpos($newLocation,'.'), strlen($newLocation)-1);
if(!in_array($ext,$allowed_filetypes))
{
die('The file you attempted to upload is not allowed.');
}
Try this for checking required fields, inserted before the code that checks the file sizes.
// ERROR HANDLING CODE:
if (empty($_FILES) || empty($_FILES['aMyUploads0']) || empty($_FILES['aMyUploads1']) || empty($_FILES['aMyUploads2']))
{
// Handle error
}
And this for validating file types, inserted into your foreach.
// IMAGE TYPE CODE:
$allowed_filetypes = array("jpg", "gif", "jpeg", "png");
$ext = pathinfo($aFile['name'], PATHINFO_EXTENSION);
if (!in_array($ext, $allowed_filetypes))
{
// Handle error
}