How do I display images in php? - php

I am having trouble displaying an image in php. In the first file I have an input that gets the image. <input type="file" name="imageOrVideo" accept="video/*,image/*" multiple>. In a second php file I want to get the image and display it. I get the file using $imageOrVideo = $_POST['imageOrVideo']; If I echo $imageOrVideo all I get is a string. I tried using echo img echo "<img src=Image/".$imageOrVideo."/>"; and echo "<img src=".$imageOrVideo."/>"; But neither worked. I read that you can only echo strings so maybe I should not use echo but some other method to display an image. Here is the full code so as to see where the problem might be. Thanks for any help.
This is the first file.
<!DOCTYPE html>
<html>
<head>
<title>Create Recipe</title>
<link rel="stylesheet" type="text/css" href="../CSS/createRecipe.css">
</head>
<body>
<div class="topnav">
Sign Out
My Recipes
Home
</div>
<form action="includes/createRecipe.inc.php" method="post">
<div class="leftSide">
<input type="file" name="imageOrVideo" accept="video/*,image/*" multiple><br><br>
<!--
<input type="file" name="imageOrVideo" accept="image/*" ><br><br>
-->
<div class="prepTimeCookTime">
<label>Prep Time</label><br><br>
<textarea type="" name="prepTime" class="prepTime"> </textarea><br>
<label>Cook Time</label><br><br>
<textarea type="" name="cookTime" class="cookTime"> </textarea><br>
</div>
<div class="readyTimeNumberOfServings">
<label></label>Ready Time<br><br>
<textarea type="" name="readyTime" class="readyTime"> </textarea><br>
<label>Number of Servings</label><br><br>
<textarea type="" name="numberOfServings" class="numberOfServings"> </textarea><br>
</div>
</div>
<div class="rightSide">
<label>Recipe Title</label><br><br>
<textarea type="" name="recipeTitle" class="recipeTitle"> </textarea><br>
<label>Description</label><br><br>
<textarea type="" name="description" class="description"> </textarea><br>
<label>Ingrediants</label><br><br>
<textarea type="" name="ingredients" class="ingredients" placeholder="Put each ingrediant on its own line."></textarea><br>
<label>Directions</label><br><br>
<textarea type="" name="directions" class="directions" placeholder="Put each step on its own line."></textarea><br>
<button type="submit" name="recipe-submit">Submit</button>
</div>
</form>
</body>
</html>
Here is the second file.
<?php
if(isset($_POST['recipe-submit'])){
require 'dbh.inc.php';
session_start();
$imageOrVideo = $_POST['imageOrVideo'];
$uidUsers = $_SESSION['userUid'];
$prepTime = $_POST['prepTime'];
$cookTime = $_POST['cookTime'];
$readyTime = $_POST['readyTime'];
$numberOfServings = $_POST['numberOfServings'];
$recipeTitle = $_POST['recipeTitle'];
$description = $_POST['description'];
$ingredients = $_POST['ingredients'];
$directions = $_POST['directions'];
//echo "<img src='" . $_POST['imageOrVideo'] . "' alt='img'>";
//echo "<img src='/images/test/" . $_POST['imageOrVideo'] . "' alt='img'>";
//print $imageOrVideo;
//echo "<img src=".$imageOrVideo."/>";
//echo "<img src=Image/".$imageOrVideo."/>";
/*
$sql = "INSERT INTO recipes (videoOrImages, uidUsers, prepTime, cookTime, readyTime, numberOfServings, recipeTitle, description, ingredients, directions) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../createRecipe.php?error=sqlError");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "bsssssssss", $imageOrVideo, $uidUsers, $prepTime, $cookTime, $readyTime, $numberOfServings, $recipeTitle, $description, $ingredients, $directions);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success");
exit();
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
*/
}
else{
header("Location: ../createRecipe.php");
exit();
}

As i mentioned in the comment your not actually managing the uploaded file. try something like this :
$uidUsers = $_SESSION['userUid'];
$prepTime = $_POST['prepTime'];
$cookTime = $_POST['cookTime'];
$readyTime = $_POST['readyTime'];
$numberOfServings = $_POST['numberOfServings'];
$recipeTitle = $_POST['recipeTitle'];
$description = $_POST['description'];
$ingredients = $_POST['ingredients'];
$directions = $_POST['directions'];
$imageOrVideo = $_POST['imageOrVideo'];
$uploaddir = 'uploads/'; //or wherever you want to upload the file
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
$imageuploaded = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// then check to see if its actually an image
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image";
$imageuploaded = 1;
} else {
echo "File is not an image.";
$imageuploaded = 0;
}
// you can check to see if the file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$imageuploaded = 0;
}
// then process the file
if ($imageuploaded == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $uploadfile)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
if you wanted to make sure its a specific file type you can try something like this :
// 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;
}
i haven't tested the code but it should work or at least set you off on the right path

Related

Undefined index: fileToUpload while load a createpost page?

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;
}
...

File upload not working in the php back-end. No file being found once I read it

I have made a form on php and I am adding an image input option there.
<form action="./assets/actions/gallery_post.php" id="upload-form" method="POST">
<input type="text" name="title" placeholder="Image title..." class="form-control" required>
<br>
<input type="text" name="description" placeholder="Image description..." class="form-control">
<br>
<input type="file" name="file", class="form-control" required>
<br>
<button type="submit" name="picture-submit" class="form-control submit">Upload Photo</button>
</form>
The following is my php code to upload the file.
// Check if the button was pressed
if (isset($POST['picture-submit'])) {
echo "Entered";
// Get the inputs
$newfilename = 'gallery';
$title = $_POST['title'];
$description = $_POST['description'];
$file = $_FILES['file'];
if($file){
echo "FILE";
}else{
echo "No File found";
}
console.log($file);
// Obtaining some file information
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileError = $file['error'];
$fileType = $file['type'];
// Checking file extensions
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
echo "$fileActualExt";
// Allowed extensions
$allowed = array('jpeg', 'jpg', 'png', 'JPG');
// if extension is allowed
if(in_array($fileActualExt, $allowed)){
// check if any error
if($fileError === 0){
// Creating a unique file name
$fileNew = $newfilename. "." . uniqid('', true) . "." . $fileActualExt;
$fileDest = "assets/images/gallery/" . $fileNew;
// Function to upload file
move_uploaded_file($fileTmpName, $fileDest);
// Making a database connection
include_once ('dbh.php');
$stmt = mysqli_stmt_init($conn);
// Move to the database as well using prepared statements
$sql = "INSERT into gallery(location, title, description) VALUES(?, ?, ?)";
echo $sql;
// Binding parameters
mysqli_stmt_bind_param($stmt, "sss", $fileDest, $title, $description);
mysqli_stmt_execute("$stmt");
// Perform a query, check for error
mysqli_query($conn, $sql) or die(mysqli_error($conn));
echo "Query Sent";
header("Location: ../gallery.php?upload=sucess");
}else {
echo "There was an error in file upload.";
}
}else {
echo "You cannnot upload files of this type!";
}
}
It is not even entering the if condition in the above scenario. When I remove the if condition, I get "No file Found". Sort of stumped here now because I have made it work in the past. I even tried the basic HTML query format like this mysqli_query($conn, $sql) or die(mysqli_error($conn)); and this does not work either.
Your form tag has to be enabled enctype="multipart/form-data".
Try this code.
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?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 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.";
}
}
}
?>

Uploading a images in MySql using PHP

I'm trying to upload an image through a contact form, to get a server in a particular folder and its time to visualize the database. When I submit the form I get this error:
File is an image - image/jpeg. Notice: Undefined index: fileToUpload
in C:\xampp\htdocs\Web\form.php on line 68 Notice: Trying to access
array offset on value of type null in C:\xampp\htdocs\Web\form.php on
line 68 Notice: Undefined index: image in C:\xampp\htdocs\Web\form.php
line 82
This is the code:
HTML:
<div class="container-form">
<form action="form.php" method="post" enctype="multipart/form-data">
<div class="image">
Прикачете ваша снимка! (максимален размер 20МБ)<br>
<input type="file" name="image" id="image" size="40" required="true" />
</div>
<div class="submit">
<input type="submit" name="submit" value="Изпращане" id="submit" />
</div>
</form>
</div>
PHP:
// Connect to MyQSL
$link = mysqli_connect("localhost", "root", "", "form");
$link->query("SET NAMES 'UTF8'");
// Check our connection
if ($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["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["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["fileToUpload"]["size"] > 20000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" ) {
echo "Sorry, only JPG, JPEG and PNG files are allowed.";
$uploadOk = 0;
}
// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$date = mysqli_real_escape_string($link, $_REQUEST['date']);
$image = mysqli_real_escape_string($link, $_REQUEST['image']);
// Insert our data
$sql = "INSERT INTO form (name, date, image) VALUES ('$name', '$date', '$image')";
// Print response from MyQSL
if (mysqli_query($link, $sql))
{
echo "<div class='echo-complete'> <div class='echo-text'> Формата беше приета успешно. Благодарим ви.";
}
else
{
echo "<div class='echo-error'> <div class='echo-text'> ГРЕШКА: Не може да се изпълни $sql." .
mysqli_error($link);
}
// Close our connection
mysqli_close($link);
Database:
image column is type BLOB
<div class="container-form">
<form method="post" enctype="multipart/form-data">
<div class="image">
<input type="file" name="image" id="image" size="40" required="true" />
</div>
<div class="submit">
<input type="submit" name="submit" value="Upload" id="submit" />
</div>
</form>
</div>
<!--Now we will connect to the database.-->
<?php
// define file
if (isset($_POST["submit"])) {
$fname = $_FILES["image"]["name"];
$fsize = $_FILES["image"]["size"];
$ferror = $_FILES["image"]["error"];
$ftype = $_FILES["image"]["type"];
$ftmp = $_FILES["image"]["tmp_name"];
// Get the extension of the file and verify if we support it
$allowed = array(
"png",
"jpeg",
"jpg",
"gif"
); //make sure it's not capital letters.
$actual_extension = explode(".", $fname); // Get what we have after the . on the file name
$extension = end($actual_extension); // make sure we got the extension
//check if the extension is supported.
if (!in_array($extension, $allowed)) {
echo "Sorry! We do not support this format" . "<br>";
}
// Now check if we have a file error, else: upload
if ($ferror == 1) { // Check if we have an error
echo "Something went wrong" . "<br>";
} else {
if ($fsize > 100000) { // check if the uploaded file matches the size we allow.
echo "Your file is BIG" . "<br>";
} else {
$new_name = uniqid('', true); // we will give the uploaded file a unique id
$path = "uploads/" . $new_name . "." . $extension; // Define the path and upload the file with new name+ "." + the file extension.
if (move_uploaded_file($ftmp, $path)) {
echo "file uploaded succesfully";
} else {
echo "something went wrong with the file upload";
}
}
}
$link = mysqli_connect("localhost", "root", "", "sadik");
$query = "INSERT INTO `table` (`image`) VALUES ($new_name) ";
mysqli_query($link, $query);
// ...
}
?>

PHP Post in URL without using GET

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'];

Undefined index: image

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.";
}
}
}
?>

Categories