I was getting an error of undifined index 'shop' when i submit the form bellow, and when i gave submit button a name and tested if it exists (isset) I had a negative response weridly, here's my code:
<?php
session_start();
$data['titre'] = 'Ajouter des médias';
$this->load->view('templates/header',$data);
$this->load->view('templates/navbar');
if(isset($_SESSION['username'])){
global $con;
$userid = getUserId($_SESSION['username']);
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['form_posted'])){
if(isset($_POST['shopid'])) $shop = $_POST['shopid'];
if($_POST['shopid'] == 0){
echo '<div class="alert alert-danger"> Aucune boutique n\'a été choisie!</div>';
}
else
{
if($_FILES['video']['name']!= NULL || $_FILES['images']['name'][0] != NULL){
if(isset($_FILES['images']) && $_FILES['images']['name'][0] != NULL){
$avatarAllowedExtensions = array("jpeg", "jpg", "png", "gif");
$name_array = $_FILES['images']['name'];
$tmp_name_array = $_FILES['images']['tmp_name'];
$type_array = $_FILES['images']['type'];
$size_array = $_FILES['images']['size'];
$error_array = $_FILES['images']['error'];
for($i = 0; $i < count($tmp_name_array) ; $i++){
$exploded_img = explode('.', $name_array[$i]);
$img_Extension = strtolower(end($exploded_img));
if(in_array($img_Extension, $avatarAllowedExtensions)){
$img_name = rand(1000000,10000000). '.' . $img_Extension;
move_uploaded_file($tmp_name_array[$i], "uploads/shops/" . $img_name);
$stmt = $con->prepare("INSERT INTO shop.shop_images (ID_boutique, pic) VALUES (?,?)");
$stmt->execute(array($shop, $img_name));
$insertid = $con->lastInsertId();
$stmt = $con->prepare("INSERT INTO publications ( type, tableid, ID_boutique) VALUES (?,?,?)");
$stmt->execute(array(2, $insertid, $shop));
if($_FILES['video']['name']== NULL){
echo '<div class="alert alert-success">Chargement réussi.</div>';
header('refresh:1.5;url='.base_url("boutiques/store/".$shop."#media"));
}
}
}
}
if(isset($_FILES['video']) && $_FILES['video']['name']!= NULL){
$maxsize = 5242880*3;
$name = $_FILES['video']['name'];
$target_dir = "uploads/videos/";
$videoFileType = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$videoName = rand(1000000,10000000). '.' . $videoFileType;
$target_file = $target_dir . $videoName;
// Select file type
// Valid file extensions
$extensions_arr = array("mp4","avi","3gp","mov","mpeg");
// Check extension
if( in_array($videoFileType,$extensions_arr) ){
// Check file size
if(($_FILES['video']['size'] >= $maxsize) || ($_FILES["video"]["size"] == 0)) {
echo '<div class="alert alert-danger">Vidéo très large, 15MB maximum!</div>';
}else{
if(move_uploaded_file($_FILES['video']['tmp_name'],$target_file)){
// Insert record
global $con;
$stmt = $con->prepare("INSERT INTO shop_videos(ID_boutique,video) VALUES('".$shop."','".$videoName."')");
$stmt->execute();
$insertid = $con->lastInsertId();
$stmt = $con->prepare("INSERT INTO publications ( type, tableid, ID_boutique) VALUES (?,?,?)");
$stmt->execute(array(4, $insertid, $shop));
echo '<div class="alert alert-success">Chargement réussi.</div>';
header('refresh:1.5;url='.base_url("boutiques/store/".$shop."#media"));
}
}
}else{
echo '<div class="alert alert-danger">Extension invalide!</div>';
}
}
}
else{
echo '<div class="alert alert-danger">Aucun fichier selectionné!</div>';
}
}
}
else echo 'POST VARIABLE HASNT PASSED!';
?>
<div class="offset-md-2 col-md-8">
<div class="container block">
<div class="card bg-light mb-3">
<div class="panel-header">Nouvelles photos</div>
<div class="card-body">
<form enctype="multipart/form-data" action="<?php echo current_url(); ?>" method="POST" class="form-horizontal">
<div class="form-group row">
<label class="col-sm-3 control-label" for="file">Ajouter des photos:</label>
<input name="images[]" id="shop_pics" type="file" multiple>
</div>
<div class="gallery"></div>
<div class="form-group row">
<label class="col-sm-3 control-label" for="file">Ajouter une vidéo:</label>
<input name="video" id="video-upload" type="file">
</div>
<p class="offset-md-2" style="font-size: 12px; font-style: italic;">NB: La vidéo ne doit pas dépasser 15mb de volume.</p>
<div class="video-preview"></div>
<div class="form-group row">
<label class="col-sm-2 control-label">Assigner à une boutique:</label>
<div class="col-sm-8 col-md-6">
<?php
$stmt = $con->prepare("SELECT * from shop.boutiques where userID = ?");
$stmt->execute(array($userid));
$boutiques = $stmt->fetchALL();
if(!empty($boutiques)){
echo '<select name="shopid" class="shopselect" required="required">';
echo '<option>Choisir une boutique</option>';
foreach (myShops() as $boutique) {
echo '
<option value='.$boutique['ID_boutique'].'>'.$boutique['nom'].'</option>';
} echo '</select>';
}
?>
</div>
</div>
<div class="form-group">
<div class="text-center">
<input type="submit" name="form_posted" value="Ajouter" class="btn btn-primary">
<input type="reset" value="Annuler" class="btn btn-danger">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<?php
}
else{
echo '<p class="alert alert-primary">Connectez-vous ou créez un compte rapidement pour pouvoir déposer des articles</p>';
}
$this->load->view('templates/footer');
?>
PS: it happens only when I load a video, works well when I upload photos, any help would be welcome
About halfway down your code, you have:
// Valid file extensions
$extensions_arr = array("mp4","avi","3gp","mov","mpeg");
// Check extension
if (in_array($videoFileType, $extensions_arr)) {
if (($_FILES['video']['size'] >= $maxsize) || ($_FILES["video"]["size"] == 0)) {
// do stuff
So your code is checking if the file you've uploaded has any of the extensions in $extensions_arr (.mp4, .avi, .3gp, .mov, .mpeg).
Once you've uploaded the file, it then checks the size and makes sure it's not either 0 or greater than the max file size. As an aside, to make this a little bit more readable, why not just use
if (in_array($videoFileType, $extensions_arr)) {
if (($_FILES['video']['size'] <= $maxsize) || ($_FILES["video"]["size"] > 0)) {
// do stuff
and check that the file size is less than max size but greater than 0?
The problem here is that you haven't declared $shop anywhere in the code, maybe you meant $target_file?
Related
Working on a small image gallery project in php and mysql. The project has two table. Album (albumId and albumName) and gallery(id, imageName, albumId, img_name). So, when user need to create a image gallery, they need to input all the information like title, album name, and image. I am able to do most of the part, the section I was stuck was with inserting the dropdown list, which in my case is album. Here is my add_photo.php
<!--Adding Post Area-->
<form action="add_photo_check.php" method="POST" enctype="multipart/form-data">
<?php
if(isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
<!--Form for post-->
<div class="form-group">
<label for="posttitle">
<h5>Photo Title</h5>
</label>
<textarea name="imageName" class="form-control" placeholder="photo title.." ></textarea>
</div>
<div class="form-group">
<label for="album">Select Album</label>
<select class="form-control" name="albumId" id="album">
<option>Select Album</option>
<?php
$sql = "select * from album";
$res = mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($res)){
echo"<option value=\"" .$row['albumId'] . "\" >" .$row['albumName']."</option>\n";
}
?>
</select>
</div>
<div class="form-group">
<label for="uploadimage">
<h5>Upload image</h5>
</label>
<div class="btn">
<input type="file" name="image">
</div>
</div>
<input type="submit" value="Publish" name="publish" class="btn btn-primary">
</form>
</div>
This is my function file add_photo_check.php
<?php
include "includes/header.php";
if(isset($_POST['publish']))
{
$title=$_POST['imageName'];
$title=mysqli_real_escape_string($conn,$imageName);
$title=htmlentities($imageName);
$id=$_POST['albumId'];
$id=mysqli_real_escape_string($conn,$albumId);
$id=htmlentities($albumId);
$uploadOk = 1;
$img_name = $_FILES['image']['name'];
$errorMessage = "";
if($img_name != "") {
$targetDir = "images/upload/";
$img_name = $targetDir . uniqid() . basename($img_name);
$imageFileType = pathinfo($img_name, PATHINFO_EXTENSION);
if(strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "png" && strtolower($imageFileType) != "jpg") {
$_SESSION['message']="<div class='alert alert-danger'> Sorry, only jpeg, jpg and png files are allowed!</div>";
$uploadOk = 0;
}
if($_FILES['image']['size'] > 100000){
$_SESSION['message']="<div class='alert alert-danger'> Image is too big to upload!</div>";
header("Location: add_photo.php");
}
if($uploadOk) {
if(move_uploaded_file($_FILES['image']['tmp_name'], $img_name)) {
//image uploaded okay
}
$sql="insert into gallery (title, id, img_name) value('$imageName','$albumId', '$img_name')";
$res=mysqli_query($conn,$sql);
if($res)
{
$_SESSION['message']="<div class='alert alert-success'> Post Successfuly Published</div>";
header("Location: add_photo.php");
}
else
{
$_SESSION['message']="<div class='alert alert-danger'> Something went wrong!</div>";
header("Location: add_photo.php");
}
}
}
}
?>
Any help will be greatly appreciated. Thank you.
I can succesfully save the image from my database using this code
if(isset($_POST['btn-update'])){
$id = $_REQUEST['id'];
$sql = "SELECT * FROM article WHERE id=:id";
$query= $db_con->prepare($sql);
$query->execute(array(':id' => $id));
while($row=$query->fetch(PDO::FETCH_ASSOC)){
$images_ = $row['image'];
$files_ = $row['file'];
}
$file_image = $_FILES['image-files'];
$file_image_Name = $_FILES['image-files']['name'];
$file_image_TmpName = $_FILES['image-files']['tmp_name'];
$file_image_Size = $_FILES['image-files']['size'];
$file_image_Error = $_FILES['image-files']['error'];
$file_image_Type = $_FILES['image-files']['type'];
if(!empty($_FILES['image-files']['tmp_name'])){
//handle first upload
$file_image_Ext = explode('.', $file_image_Name);
$file_image_ActualExt = strtolower(end($file_image_Ext));
$file_image_allowed = array("jpg", "jpeg", "png");
if(in_array($file_image_ActualExt, $file_image_allowed)){
if($file_image_Error === 0){
if($file_image_Size < 1000000){
$file_image_NameNew = "image-".uniqid('',true).'.'.$file_image_ActualExt;
$file_image_Destination = 'uploaded_files/uploaded_files_articles_images/' .$file_image_NameNew;
move_uploaded_file($file_image_TmpName, $file_image_Destination);
}else{
echo "You file size is too big!";
}
}else{
echo "There was an error uploading the file!";
}
}else{
echo "You cannot upload files of this type!";
}
}else{
$file_image_NameNew = '';
}
if($user->InsertArticle($articleTitle,$date_today,$bodyContent,$file_image_NameNew))
{
header("Location:admin-index?UploadedSuccesfully!");
}
}
Now what I am trying to do is edit the image but it seems like my code is missing something and I couldn't figure out why is it not succesfully editing.
Here's my code for editing the image from database
$location = $_FILES['image']['name'];
$fileTmpNameLocation = $_FILES['image']['tmp_name'];
if(!empty($_FILES['image']['tmp_name'])){
//allow file types
$fileExtLocation = explode('.', $location);
$fileActualExtLocation = strtolower(end($fileExtLocation));
$allowedLocation = array("jpg", "jpeg", "png");
if(in_array($fileActualExtLocation, $allowedLocation)){
$fileNameNewLocation = $images_;
$fileDestinationLocation = 'uploaded_files/uploaded_files_articles_images/' .$fileNameNewLocation;
move_uploaded_file($fileTmpNameLocation, $fileDestinationLocation);
}
}else{
$fileNameNewLocation = '';
}
if($user->UpdateFile($id,$title,$content,$fileNameNewLocation)){
$user->Redirect('edit-index.php?UpdatedSuccesfully');
}else{
echo "There's something wrong!";
}
Here's my UpdateFile Method
public function UpdateFile($id,$title, $content, $image){
try{
$stmt = $this->db->prepare("UPDATE article SET title=:title, content=:content, image=:image WHERE id=:id");
$stmt->bindParam(":title", $title);
$stmt->bindParam(":content", $content);
$stmt->bindParam(":image", $image);
$stmt->bindParam(":id", $id);
$stmt->execute();
return $stmt;
}catch(PDOException $ex){
echo $ex->getMessage();
}
}
Could someone help me out please.
EDIT:
<form action = "edit.php" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title of the Article</label>
<input type="text" class="form-control" id="title" name="title" value="<?php echo $title; ?>">
<br \>
<label for="bodyContent">Content</label>
<textarea class="form-control" rows="5" id="content" name="content"><?php echo $content; ?></textarea>
<br>
<div class="row">
<div class="col-md-4">
<label for="exampleFormControlFile1">Upload Image Only</label>
<input type="file" name="image" class="form-control-file" id="image">
<div class="col-md-12">
<?php
if(empty($images_)){
//nnothing to display
}else{
echo "<img src='uploaded_files/uploaded_files_articles_images/$images_' class='img-responsive img-rounded'>";
}
?>
</div>
</div>
<div class="col-md-4">
<label for="exampleFormControlFile1">Upload File</label>
<input type="file" name="files" class="form-control-file" id="files">
<div class="col-md-12">
<?php
if(empty($files_)){
//nothing to display
}else{
echo "<a href='uploaded_files/uploaded_files_articles/$files_' download>".$files_."</p>";
}
?>
</div>
</div>
<div class="col-md-4">
<input type="hidden" name="id" value=<?php echo $_GET['id']; ?>>
</div>
</div>
<br>
<button type="submit" name="btn-update" class="btn btn-primary">Update</button>
</div>
</form>
I am on Ubuntu. I am trying to take user file upload of small images. I checked the $_FILES it's filled with data. I tried to debug the move command but it doesnot echo anything.
if ($_SERVER['REQUEST_METHOD'] == 'POST' ){
//Now handle everything
if(isset($_POST["submit"])) {
print_r($_FILES);
//Store the image
if(!empty($_FILES['uploaded_file']))
{
$path = "/neel/public/img/";
$path = $path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo 'Its working';
} else{
echo 'I am done!!!';
die();
}
}
createnewEvent($conn);
header('Location:/neel/index.php');
}
}
You can check if the file exists by checking its name.
if(!empty($_FILES['file']['name']))
Where file is the name of input field for file.
P. G above here is correct.
Instead of checking, if $_POST['submit']
You should check this:
if(isset($_FILES['uploaded_file']['name']))
Try this code it's a complete sign up form with PHP , Bootstrap
HTML
<div class="container">
<div class="row">
<br>
<h1 class="text-center">Create new account</h1>
<br>
<div class="col-lg-4 col-md-6 col-sm-12">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="name" placeholder="Your Name">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" placeholder="Password">
</div>
<div class="form-group text-center">
<div class='file-input'>
<input type='file' name="profile-img">
<span class='button label' data-js-label>Choose your profile image</span>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success form-control form-control-lg" name="signup" value="Signup">
</div>
</form>
</div>
</div>
</div>
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors;
if (empty($_POST['name'])) {
$errors[] = "Name field is empty";
}
if (empty($_POST['username'])) {
$errors[] = "Username field is empty";
}
if (empty($_POST['password'])) {
$errors[] = "Password field is empty";
}
if (empty($_FILES['profile-img'])) {
$errors[] = "You should upload profile image";
} else{
$img = $_FILES['profile-img'];
$ext = end(explode('.', $img['name']));
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 4; //MegaBytes
if (! in_array($ext, $allowed_extensions)) {
$errors[] = "Please , Choose a valid image";
}
$img_size = $img['size'] / 1000000; // By Megabyte
if ($img_size > $max_size) {
$errors[] = "This picture is so large";
}
}
if (!empty($errors)) {
echo '<div class="container">';
foreach ($errors as $error) {
echo '
<div class="alert alert-danger" role="alert">
' . $error . '
</div>
';
}
echo "</div>";
} else {
$username = filter_var(htmlentities(trim($_POST['username'])), FILTER_SANITIZE_STRING);
$name = filter_var(htmlentities(trim($_POST['name'])), FILTER_SANITIZE_STRING);
$password = sha1(filter_var(htmlentities(trim($_POST['password'])), FILTER_SANITIZE_STRING));
// Profile Picture :-
$imgname = uniqid(uniqid()) . #date("Y-m-d") . "." . $ext;
$target_bath = "uploads/imgs/";
$target_bath = $target_bath . basename($imgname);
$orginal_img = $img['tmp_name'];
if (move_uploaded_file($orginal_img, $target_bath)) {
$sql = "INSERT INTO users(name, username, password,profile_picture, r_d) VALUES ('$name', '$username', '$password', '$target_bath', NOW())";
$result = mysqli_query($conn, $sql);
header('location: ./login.php');
}
}
}
The script you've shown shown will only "not echo anything" if $_SERVER['REQUEST_METHOD'] is not "POST". Assuming your description of events is accurate, then the problem is in the form #halojoy has asked that you show here.
I do hope that you are not redirecting the script back to itself. Also you shouldn't attempt to do a redirect after an echo.
This question already has answers here:
Multiple files upload in Codeigniter
(5 answers)
Closed 8 months ago.
I have inilabs school management script, working fine. But I'm trying to modify. I want to upload more than one image in database
Here is add.php
' <?php
if(isset($image))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
?>
<label for="photo" class="col-sm-2 control-label col-xs-8 col-md-2">
<?=$this->lang->line("student_photo")?>
</label>
<div class="col-sm-4 col-xs-6 col-md-4">
<input class="form-control" id="uploadFile1" placeholder="Choose File" disabled />
</div>
<div class="col-sm-2 col-xs-6 col-md-2">
<div class="fileUpload btn btn-success form-control">
<span class="fa fa-repeat"></span>
<span><?=$this->lang->line("upload")?></span>
<input id="uploadBtn1" type="file" class="upload" name="image" />
</div>
</div>
<span class="col-sm-4 control-label col-xs-6 col-md-4">
<?php if(isset($image)) echo $image; ?>
</span>
</div>
<?php
if(isset($imageaadhar))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
?>
<label for="aadhar" class="col-sm-2 control-label col-xs-8 col-md-2">
<?=$this->lang->line("student_aadhar")?>
</label>
<div class="col-sm-4 col-xs-6 col-md-4">
<input class="form-control" id="uploadFile2" placeholder="Choose File" disabled />
</div>
<div class="col-sm-2 col-xs-6 col-md-2">
<div class="fileUpload btn btn-success form-control">
<span class="fa fa-repeat"></span>
<span><?=$this->lang->line("upload")?></span>
<input id="uploadBtn2" type="file" class="upload" name="imageaadhar" />
</div>
</div>
<span class="col-sm-4 control-label col-xs-6 col-md-4">
<?php if(isset($imageaadhar)) echo $imageaadhar; ?>
</span>
</div>
<?php
if(isset($imagebirthc))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
?>
<label for="birthc" class="col-sm-2 control-label col-xs-8 col-md-2">
<?=$this->lang->line("student_birthc")?>
</label>
<div class="col-sm-4 col-xs-6 col-md-4">
<input class="form-control" id="uploadFile3" placeholder="Choose File" disabled />
</div>
<div class="col-sm-2 col-xs-6 col-md-2">
<div class="fileUpload btn btn-success form-control">
<span class="fa fa-repeat"></span>
<span><?=$this->lang->line("upload")?></span>
<input id="uploadBtn3" type="file" class="upload" name="image" />
</div>
</div>
<span class="col-sm-4 control-label col-xs-6 col-md-4">
<?php if(isset($imagebirthc)) echo $imagebirthc; ?>
</span>
</div>'
This is controller/add.php for upload single image. How to modify for upload two more image ?
$classesID = $this->input->post("classesID");
if($classesID != 0) {
$this->data['sections'] = $this->section_m->get_order_by_section(array("classesID" =>$classesID));
} else {
$this->data['sections'] = "empty";
}
$this->data['sectionID'] = $this->input->post("sectionID");
if($_POST) {
$rules = $this->rules();
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == FALSE) {
$this->data["subview"] = "student/add";
$this->load->view('_layout_main', $this->data);
} else {
$sectionID = $this->input->post("sectionID");
if($sectionID == 0) {
$this->data['sectionID'] = 0;
} else {
$this->data['sections'] = $this->section_m->get_allsection($classesID);
$this->data['sectionID'] = $this->input->post("sectionID");
}
$dbmaxyear = $this->student_m->get_order_by_student_single_max_year($classesID);
$maxyear = "";
if(count($dbmaxyear)) {
$maxyear = $dbmaxyear->year;
} else {
$maxyear = date("Y");
}
$section = $this->section_m->get_section($sectionID);
$array = array();
$array["name"] = $this->input->post("name");
$array["dob"] = date("Y-m-d", strtotime($this->input->post("dob")));
$array["sex"] = $this->input->post("sex");
$array["religion"] = $this->input->post("religion");
$array["email"] = $this->input->post("email");
$array["phone"] = $this->input->post("phone");
$array["address"] = $this->input->post("address");
$array["classesID"] = $this->input->post("classesID");
$array["sectionID"] = $this->input->post("sectionID");
$array["section"] = $section->section;
$array["roll"] = $this->input->post("roll");
$array["username"] = $this->input->post("username");
$array['password'] = $this->student_m->hash($this->input->post("password"));
$array['usertype'] = "Student";
$array['parentID'] = $this->input->post('guargianID');
$array['library'] = 0;
$array['hostel'] = 0;
$array['transport'] = 0;
$array['create_date'] = date("Y-m-d");
$array['year'] = $maxyear;
$array['totalamount'] = 0;
$array['paidamount'] = 0;
$array["create_date"] = date("Y-m-d h:i:s");
$array["modify_date"] = date("Y-m-d h:i:s");
$array["create_userID"] = $this->session->userdata('loginuserID');
$array["create_username"] = $this->session->userdata('username');
$array["create_usertype"] = $this->session->userdata('usertype');
$array["studentactive"] = 1;
$new_file = "";
if($_FILES["image"]['name'] !="") {
$file_name = $_FILES["image"]['name'];
$file_name_rename = $this->insert_with_image($this->input->post("username"));
$explode = explode('.', $file_name);
if(count($explode) >= 2) {
$new_file = $file_name_rename.'.'.$explode[1];
$config['upload_path'] = "./uploads/images";
$config['allowed_types'] = "gif|jpg|png";
$config['file_name'] = $new_file;
$config['max_size'] = '1024';
$config['max_width'] = '3000';
$config['max_height'] = '3000';
$array['photo'] = $new_file;
$this->load->library('upload', $config);
if(!$this->upload->do_upload("image")) {
$this->data["image"] = $this->upload->display_errors();
$this->data["subview"] = "student/add";
$this->load->view('_layout_main', $this->data);
} else {
$data = array("upload_data" => $this->upload->data());
$this->student_m->insert_student($array);
$this->session->set_flashdata('success', $this->lang->line('menu_success'));
redirect(base_url("student/index"));
}
} else {
$this->data["image"] = "Invalid file";
$this->data["subview"] = "student/add";
$this->load->view('_layout_main', $this->data);
}
} else {
$array["photo"] = $new_file;
$this->student_m->insert_student($array);
$this->session->set_flashdata('success', $this->lang->line('menu_success'));
redirect(base_url("student/index"));
}
}
} else {
$this->data["subview"] = "student/add";
$this->load->view('_layout_main', $this->data);
}
} else {
$this->data["subview"] = "error";
$this->load->view('_layout_main', $this->data);
}
}
Help me please
your file name
<input id="uploadBtn3" type="file" class="upload" name="image[]" />
in controller
$files = $_FILES;
$count = count($_FILES['uploadfile']['name']);
for($i=0; $i<$count; $i++)
{
$_FILES['uploadfile']['name']= $files['uploadfile']['name'][$i];
$_FILES['uploadfile']['type']= $files['uploadfile']['type'][$i];
$_FILES['uploadfile']['tmp_name']= $files['uploadfile']['tmp_name'][$i];
$_FILES['uploadfile']['error']= $files['uploadfile']['error'][$i];
$_FILES['uploadfile']['size']= $files['uploadfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());//function defination below
$this->upload->do_upload('uploadfile');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$image[] = $fileName;
}
$fileName = $image;
Well, I have page to add items, and have an input for uploading a file to the site.
The Image doesn't upload to the site..
Where is the problem?
The code is between the:
## IMAGE IMAGE IMAGE IMAGE IMAGE ##
add.php
<form action="add.php" method="post">
<input name="title_name" type="text" class="form-control" style="width: 250px;margin-left:auto;margin-right:auto;display:inline;" placeholder="שם הפריט או נושא" /> <br />
<textarea name="description" class="form-control" rows="5" placeholder="תיאור הפריט..." style="width: 250px;margin-left:auto;margin-right:auto;display:inline;"></textarea> <br />
<input class="btn btn-primary" name="uploadedfile" type="file" style="width: 250px;margin-left:auto;margin-right:auto;display:inline;"> <br />
<input name="type" type="text" class="form-control" style="width: 250px;margin-left:auto;margin-right:auto;display:inline;" placeholder="סוג הפריט" /> <br />
<button type="submit" class="btn btn-primary" name="submitAdd">הוסף פריט</button>
</form>
<br>
<div class="container">
<?php
$title_name = $_POST['title_name'];
$description = nl2br($_POST['description']);
$username = $_SERVER['REMOTE_ADDR'];
$type = $_POST['type'];
$ok = 1;
if(isset($_POST['submitAdd'])) {
if(empty($title_name)) {
echo '<div class="alert alert-danger fade in">
×
<strong>שגיאה:</strong> The name of item can stay empty
</div>';
$ok = 0;
}
if(!empty($title_name) && !preg_match("/[A-Za-z0-9א-ת\.\,\_\- ]/", $title_name)) {
echo '<div class="alert alert-danger fade in">
×
<strong>שגיאה:</strong> שם הפריט מכיל תווים לא מורשים
</div>';
$ok = 0;
}
if(!empty($description) && !preg_match("/[A-Za-z0-9א-ת\.\,\_\- ]/", $description)) {
echo '<div class="alert alert-danger fade in">
×
<strong>שגיאה:</strong> תיאור הפריט מכיל תווים לא מורשים
</div>';
$ok = 0;
}
if (!empty($userfile) && !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $userfile)) {
echo '<div class="alert alert-danger fade in">
×
<strong>שגיאה:</strong> Error with name of file
</div>';
$ok = 0;
}
## IMAGE IMAGE IMAGE IMAGE IMAGE ##
//
$uploadImageStatus = 1;
$userfile = $_POST['uploadedfile'];
$name = strtolower($_FILES['uploadedfile']['name']);
$ext = pathinfo($name, PATHINFO_EXTENSION);
$allow = array("png", "jpeg", "jpg");
$target_path = 0;
if ($userfile > 0) {
if(!in_array($ext, $allow)) {
echo '<div class="alert alert-danger fade in">
×
<strong>שגיאה:</strong> This file type dont allowed
</div>';
$uploadImageStatus = 0;
}
if($uploadImageStatus !== 0 && $_FILES['uploadedfile']['error'] !== 0) {
$nameFile = $_FILES['uploadedfile']['name'];
$target_path = "images/".basename(md5($_FILES['uploadedfile']['name']).time()).".$ext";
if(move_uploaded_file($nameFile, $target_path)) {
$uploadImageStatus2 = 1;
}
else {
$uploadImageStatus2 = 0;
echo '<div class="alert alert-danger fade in">
×
<strong>שגיאה:</strong> Error on try upload this image
</div>';
}
}
}
## IMAGE IMAGE IMAGE IMAGE IMAGE ##
change you form tag
<form action="add.php" method="post">
to
<form action="add.php" method="post" enctype="multipart/form-data">
and also change
if ($userfile > 0) {
to
if (!empty($_FILES["uploadedfile"])) {