I'm trying to upload a file (image) to sql table via pathfile but I keep getting these error "undefined index : image on line 3 and line 24". I already defined the image in the userpage. I'm not using BLOB because it consumes too much space. In my sql table, I simply set the image column as vachar. I already checked the php.ini file in xampp ,the upload is on and the maximum is 2MB upload file.Please help. tq.
Below is the userpage:
<?php
//useracc-test.php
//start session
session_start();
require 'connect-test.php';
include 'upload.php';
if(isset($_POST['username'])){
$userName = $_POST['username'];
$query = "SELECT id, name, username, telno FROM users WHERE username = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $userName);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_array();
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['name'];
$_SESSION['username'] = $row['username'];
$_SESSION['telno'] = $row['telno'];
}
?>
<html>
<head>
<script type="text/javascript">
function MM_jumpMenu(targ,selObj,restore){ //v3.0
eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
if (restore) selObj.selectedIndex=0;
}
</script>
</head>
<body>
<div id="apDiv3">
<p> </p>
<p> </p>
<p> </p>
<p><span class="TabbedPanelsContent">
<?php
echo $_SESSION['id']."<br/>";
echo $_SESSION['name']."<br/>";
echo $_SESSION['username']."<br/>";
echo $_SESSION['telno']."<br/>";
?>
<?php
if(isset($_POST['submit']))
{
$id = $_POST['id'];
$name2 = $_POST['name2'];
$color2 = $_POST['color2'];
$hobby2 = $_POST['hobby2'];
$radiobtn = $_POST['radiobtn'];
$image = $_POST['image'];
$stmt = $conn->prepare("INSERT INTO useradvert (id,name2,color2,hobby2,radiobtn,image) VALUES (?,?,?,?,?,?)");
$stmt->bind_param("isssss",$id,$name2,$color2,$hobby2,$radiobtn,$image);
$stmt->execute();
// $stmt->close();
// $conn->close();
//think of something later how to close and logout
/* <?php unset($_SESSION);
session_destroy(); ?> */
}
?>
</p>
<p> </p>
<form name="form2"
action="useracc-test.php" method="post" enctype="multipart/form-data">
<p> </p>
<table width="500" border="0">
<tr>
<td>category</td>
<td><select name="jumpMenu" id="jumpMenu" onChange="MM_jumpMenu('parent',this,0)">
<option value="useracc-test.php" selected>Category</option>
<option value="useracc-test.php">Members</option>
<option value="useracc-test2-jumpmenu.php">Non-members</option>
</select></td>
</tr>
<tr>
<td>ID:</td>
<td><input name="id" type="text" id="id" value="<?php echo $_SESSION['id']; ?>" ></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name2" id="name2"></td>
</tr>
<tr>
<td>Color</td>
<td><input type="text" name="color2" id="color2"></td>
</tr>
<tr>
<td>Hobby</td>
<td><input type="text" name="hobby2" id="hobby2"></td>
</tr>
<tr>
<td>Sex</td>
<td>male
<input type="radio" name="radiobtn" id="radio" value="male">
female
<input type="radio" name="radiobtn" id="radio2" value="female"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" name="image" id="image"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" id="submit" value="submit"></td>
</tr>
</table>
<div align="center"></div>
<p> </p>
</form>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p>
</body>
</html>
below is the upload.php file where I run the upload script.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image or not
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["image"]["size"] > 200000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I'm getting error undefined index on line 3 and line 24.
error line 3 refers to below;
$target_file = $target_dir . basename($_FILES["image"]["name"]);
error line 24 refers to below;
if ($_FILES["image"]["size"] > 200000) {
All the code that depends on the post parameters should be inside the if isset($_POST['submit']) block. Otherwise, none of the other $_POST or $_FILE parameters will be set.
The other problem you're having is that you're posting to the wrong script. The form should say action = "upload.php".
<?php
if(isset($_POST["submit"])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image or not
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["image"]["size"] > 200000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
Related
I have the following PHP code in which i am creating a post with title description and image and i am storing image in a folder images. all things working fine while i create a post this move file to images folder. title , description and imagepath gone to news folder and so on. but when firstly arrive on createnews.php page this error is shown how to handle this error.
NOTE: this error is shown on page load after loading post is submitting correctly
Error
Notice: Undefined index: fileToUpload in E:\Software projects Folder\htdocs\Criclite\createnews.php on line 63
Sorry, there was an error uploading your file.
createnews.php
<!DOCTYPE html>
<html>
<head>
<title>Add news</title>
</head>
<body>
<form action="createnews.php" method="post" enctype="multipart/form-data">
<h2>Add Post Details Here</h2>
<?php if (isset($_GET['error'])) { ?>
<p class="error"><?php echo $_GET['error']; ?></p>
<?php } ?>
<label>Title</label>
<input type="text" name="title" placeholder="Enter Post Title"><br>
<label>Description</label>
<br>
<textarea rows="8" cols="100" name="description"></textarea>
<br><br>
<label >Select image:</label>
<input type="file" name="fileToUpload"
value="" />
<div>
<button onclick="allnews()" type="submit"name="upload">
Submit
</button>
</div>
</form>
</body>
</html>
<?php
include("db_config.php");
require_once "header.php";
$target_dir = "images/";
$file_name = date("U").".jpg";
$target_file = $target_dir . $file_name;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$title=$_POST['title'];
$description=$_POST['description'];
$sql= "
INSERT INTO `news` ( `title`, `description`, `image`) VALUES ( '".$title."', '".$description."', '".$target_file."')";
if ($link->query($sql) === TRUE) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
}
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
This may not be a clean approach but a quick one. You can just add the following snippet to make sure that the form submission script only executes when the form is posted. You can add this at the beginning of the script.
<?php
if(!isset($_POST["submit"])){
return false;
}
...
I made an upload form called upload.php with action up.php so I upload images in the folder C:/xampp/htdocs/uploadimages and in the page upload.html I would like to make a dynamic slideshow containing all new and old pictures.
upload.php
<body>
<form action="up.php" method="post" enctype="multipart/form-data">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
<p><strong>Note:</strong> Only <b> .jpg </b> and <b> .png </b> formats allowed to a max size of 3 MB.</p>
</form>
<div class="gallery">
<div class="gallery-image">
<?php
$directory = "C:/xampp/htdocs/uploadimages";
$images = glob($directory . "/*.jpg");
foreach($images as $image)
{
echo " <img src=\"basename($image)\"> ";
echo "<br>" ;
}
?>
</div>
</body>
up.php
<?php
$target_dir = "C:/xampp/htdocs/uploadimages/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if (file_exists($target_file)) {
echo "File already exists. <br>";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 3 * 1024 * 1024) {
echo "Your file is too large. <br>";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png") {
echo "Only JPG and PNG files are allowed. <br>";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded. <br>";
} else {
echo "There was an error uploading your file. <br>";
}
}
?>
I tried the basename($image) inside a for-each loop but nothing worked
I want to Upload imagename into database and directory then want to show it on preview page (preview.php ). but its not working at all. as i am new to programming, so i need support. here the problem is, neither the image save into directory nor into the database.
here is the form page (form5.php) where we select image and after click on submit it goes to next page pptupload.php.
<form method="post" action="pptupload.php?appid=<?php echo $appid; ?>" enctype='multipart/form-data'>
<table>
<tbody>
<tr>
<img id="pptimg" src="#" width="600px" height="300px" alt="Scanned Passport" />
<input type="file" id="file" name="file" />
</tr>
<tr>
<input name='but_upload' type="submit" class="btn btn-primary" value="Save and Continue">
</tr>
</tbody>
</table>
</form>
here is the next Page (pptupload.php ) . On this Page, I want redirect to next page preview.php after successful upload of image and if it failed then show error and return back to the image selection page called form5.php .
<?php
session_start();
$appid = $_GET['appid'];
include("connect.php");
if(isset($_POST['upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
// Insert record
$query = "insert into payments(app_id, pptimg) values('$appid','$name')";
if (mysqli_query($connect,$query)){
echo "Image were updated successfully.";
header("Location: preview.php?appid=".$appid);
}else{
echo "Photo not uploaded".mysqli_error($connect);
}
?>
Check below code :
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I want to prepare 5 photo upload form and user need to select all 5 photo at once and the submit the form
then i need to store all 5 photos in the Target Directory by renaming image as "1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg". I stored only one image but after add For loop for save more than one file its not working ....please support.
// Image Upload FORM
<form action="saveinntion.php" method="post" enctype="multipart/form-data">
<h1>Upload Your Innovation</h1
<fieldset>
<legend><span class="number">4</span>Upload Images</legend>
<input type="file" name="img1" id="img1" >
</br>
<input type="file" name="img2" id="img2">
</br>
<input type="file" name="img3" id="img3">
</br>
<input type="file" name="img4" id="img4">
</br>
<input type="file" name="img5" id="img5">
</br>
</fieldset>
<button type="submit">Submit</button>
</form>
saveinntion.php file
<?php
include("dbconnection.php");
$target_dir = "Upload/";
$img=$_POST['img'];
for ($i = 0; $i < 5; $i++) {
$target_file = $target_dir . basename($_FILES['$img[]']["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES['$img[]']["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "jpeg" ) {
echo "Sorry, only JPG & JPEG files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES['$img[]']["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES['$img[]']["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
header("Location: upload1.php?id=$msg");
?>
Your problem is with your naming. as #Twinfriends said in the command it is highly unlikely to upload any file
replace $_FILES['$img[]'] with $_FILES['img'.($i+1)] in your code.
line # 5
$target_file = $target_dir . basename($_FILES['img'.($i+1)]["name"]);
line #13
if ($_FILES['img'.($i+1)]["size"] > 500000) {
line #25
if (move_uploaded_file($_FILES['img'.($i+1)]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES['img'.($i+1)]["name"]). " has been uploaded.";
To renaming file.
$imageFileType = pathinfo($_FILES['img'.($i+1)]["name"],PATHINFO_EXTENSION);
$target_file = $target_dir . ($i+1).".".$imageFileType;
I'm currently working on some code. Where you should be able to upload a file and select witch type of file it is.
I'm using urls to make an database entry on the upload page , so my link should look like
www.mydomain.domain?id=1&type=type
But php only gets the id because it uses get from the previous page.
So it looks like this
www.mydomain.domain?id=1&type=
So my question is how can I get the selection in the url?
I tried it with jQuery but I suck at it ;D.
My form code:
<?php
$datetype = $_POST['dateiart'];
echo $datetype;
$ek = $_GET['id'];
?>
<form action="upload.php?id=<?php echo $ek; ?>&type=<?php echo $datetype;?>" target="_blank" method="post" enctype="multipart/form-data" id="dateiauswahl">
Datei zum hochladen auswählen
<input type="file" name="fileToUpload" id="fileToUpload"> <br>
<input onclick="myFunction()" type="submit" value="Datei hochladen" name="submit"><br><br>
<input type="hidden" value="<?php echo $ek?>" id="id" name="submit"><br><br>
<label>Dateiart:
<select name="dateiart" form="dateiauswahl" size="5">
<option value="EK-Rechnung">EK-Rechnung</option>
<option value="Kaufvertrag">Kaufvertrag</option>
<option value="VK-Rechnung">VK-Rechnung</option>
<option value="Datenblatt">Datenblatt</option>
<option value="Sonstige">Sonstige</option>
</select>
</label>
</div>
</form>
upload.php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=', '', '');
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$ek = $_GET['id'];
$dateiart = $_GET['type'];
echo $dateiart;
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 50000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "pdf"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$statement = $pdo->prepare("INSERT INTO Dateien (Link, EKNR, Datei_Bezeichnung) VALUES (:Link, :EKNR, :Datei_Bezeichnung)");
$result = $statement->execute(array('Link' => $target_file, 'EKNR' => $ek, 'Datei_Bezeichnung' => $dateiart));
}
?>
Pass parameters as hidden inputs instead of printing them in the query string of action URL of the form. Use htmlspecialchars function to prevent security issues.
<?php
if (!isset($_GET['id']) || !isset($_GET['type'])){
die('Missing parameters');
}
?>
<form action="upload.php" target="_blank" method="post" enctype="multipart/form-data" id="dateiauswahl">
Datei zum hochladen auswählen
<input type="hidden" name="id" value="<?php echo htmlspecialchars($_GET['id']) ?>">
<input type="hidden" name="type" value="<?php echo htmlspecialchars($_GET['type']) ?>">
....... other inputs
</form>
The in the upload.php script get them from $_POST superglobal.
$ek = $_POST['id'];
$dateiart = $_POST['type'];