I have a form I'm building that uploads the form content into a database (mysql) and a separate page to display the contents of the database. So far everything works great. I need the users to be able to upload an image file along with the form and I need the image itself to display on the page with the database contents.
How do I accomplish this by modifying the existing code? I've included the form code, the code that posts to the database and the page code that displays the content below.
Thank you!!
Form:
<form name="sponsor-registration" method="post" enctype="multipart/form-data" action="sponsor-registration.php">
<div class="formcentered">
<div class="formfield"><input type="text" name="yourname" size="30" maxlength="70" value="" required></div><div class="formlabel">Your Name:</div>
<br class="clearfloat" />
<div class="formfield"><input type="text" name="email" size="30" maxlength="70" value="" required></div><div class="formlabel">Email:</div>
<br class="clearfloat" />
<div class="formfield"><input type="text" name="phone" size="30" maxlength="20" value="" required></div><div class="formlabel">Phone</div>
<br class="clearfloat" />
<div class="formfield"><input type="text" name="sponsorname" size="30" maxlength="70" value="" required></div><div class="formlabel">Sponsor Name:</div>
<br class="clearfloat" />
<div class="formfield"><input type="text" name="sponsorshiplevel" size="30" maxlength="70" value="" required></div><div class="formlabel">Sponsorship Level: </div>
<br class="clearfloat" />
<p class="pagecentered"><input type="submit" name="submit" value="submit"> </p>
</div>
</form>
Posts to the database:
<?php //start php tag
//include connect.php page for database connection
include('connect.php');
//if submit is not blanked i.e. it is clicked.
{
$sql="insert into sponsors2015(yourname,email,phone,sponsorname,sponsorshiplevel,logofile) values('".$_REQUEST['yourname']."', '".$_REQUEST['email']."', '".$_REQUEST['phone']."', '".$_REQUEST['sponsorname']."', '".$_REQUEST['sponsorshiplevel']."')";
$res=mysql_query($sql);
if($res)
{
Echo header('Location: sponsor-registration-success.php');
}
Else
{
Echo header('Location: sponsor-registration-problem.php');
}
}
?>
Displays the contents of the database
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, yourname, email, phone, sponsorname, sponsorshiplevel, logofile FROM sponsors2015";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. "<br>". " Name: " . $row["yourname"]. "<br>". " Email: " . $row["email"]. "<br>". " Phone: " . $row["phone"]. "<br>". "Sponsor Name: " . $row["sponsorname"]. "<br>". "Sponsorship Level: " . $row["sponsorshiplevel"]. "<br>". "<hr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
to add an image,you need a file input tag
After this,you would need to process the file as below <input type="file" name="profilepic" accept=".jpeg,.jpg,.png" />
<?php function imagEupload()
{
global $picerror;
if ($_FILES['profilepic']['error'] == 4) {
$picerror[] = "<p class='formerrors'>No picture was uploaded,kindly upload one.</p>";
}
if ($_FILES['profilepic']['error'] >= 1) {
$picerror[] = "<p class='formerrors'> There was an error processing your image," . $_FILES['profilepic']['name'];
} else {
$validfiletype = ['jpg', 'jpeg', 'png']; // starts an array to hold the valid file extensions.
$max_file_size = 1024 * 3072; // 3Mb
$uploadpath = "uploads/";
$uploadedfilename = $_FILES['profilepic']['name'];
if ($_FILES['profilepic']['size'] > $max_file_size) {
$picerror[] = "<p class='formerrors'>The uploaded file," . " $uploadedfilename" . " is too large</p>";
} else {
// get the file extension and check it to make sure it tallies with the valid extensions set in the array
if (!in_array(pathinfo($_FILES['profilepic']['name'], PATHINFO_EXTENSION), $validfiletype)) {
$picerror[] = "<p class='formerrors'> The uploaded file," . " $uploadedfilename" . " is not a valid image</p>";
} else {
$fileext = pathinfo($_FILES['profilepic']['name'], PATHINFO_EXTENSION);
$filename = uniqid($_FILES['profilename']['name']) . ".$fileext";
if (file_exists($uploadpath . $filename)) {
$picerror[] = "<p class='formerrors'>The uploaded File," . " $uploadedfilename" . " exists,please upload another or do consider renaming it.</p>";
} else {
$filepath = $uploadpath . $filename;
if (move_uploaded_file($_FILES['profilepic']['tmp_name'], $filepath)) {
global $newfilepath;
$newfilepath = $filepath; // input this to your database, to echo the image, it would be something like this <img src='<?php echo $_row['image'] ;' />
} else {
$picerror[] = "<p class='formerrors'>We could not process your image due to an unavoidable error,Please contact us or try again</p>";
}
}
}
}
}
}
?>
you can also refer to the php manual http://php.net/manual/en/features.file-upload.php
and by the way, the mysql extension is deprecated,do consider using mysqli or PDO , the header('location') ; works without echo ..I hope this helps
Related
I have a php function to create a file in a directory on submission of a form.
The code is:
<form id="myForm" onSubmit="<?php
error_reporting(E_ALL);
$directory = __DIR__ . "/images/"; $filecount = 0; $files = glob($directory . "*"); if ($files){
$filecount = count($files); }
$filecount = $filecount + 1;
$pagename = 'image_'.$filecount;
$newFileName = './images/'.$pagename;
$newFileContent = 'Page Content';
if (file_put_contents($newFileName, $newFileContent) !== false) {
echo "File created (" . basename($newFileName) . ")";
} else {
echo "Cannot create file (" . basename($newFileName) . ")";
}
?>">
<input placeholder="Username 0/25" name="user" id="user" maxlength="25" required>
<input placeholder="Password 0/45" name="password" id="password" maxlength="45" required>
<input placeholder="Image Name" name="name" id="name">
<input type="file" placeholder="Image" accept="image/*" name="img" required>
<button type="submit">Upload</button>
</form>
The problem is that it auto activates on page load.. is there a way to fix that
The problem is that it auto activates on page load
to prevent auto loading the page when you press on submit, you could use this trick "return false; \"..." but it doesn't create the image file :/ just stop the page from action.
if (file_put_contents($newFileName, $newFileContent) !== false) {
echo "return false; \"File created (" . basename($newFileName) . ")";
} else {
echo "return false; \" Cannot create file (" . basename($newFileName) . ")";
}
I try to imitate you're project, however i used txt files instead of images.
I used AJAX
index.html
<html>
<body>
<form id="myForm">
<button type="submit">create a file</button>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
document.getElementById('myForm').onsubmit = function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open('GET','creating.php');
xhr.onreadystatechange = function(){
console.log(xhr.readyState)
if(xhr.readyState == XMLHttpRequest.DONE)
if(xhr.response.startsWith('Woow'))
alert('File created successfully!');
else
alert('Something went wrong!');
}
xhr.send();
}
creating.php
<?php
$directory = __DIR__ . "/files/";
$filecount = count(glob($directory . "*")) + 1;
$newFileName = $directory.'txt_'.$filecount.'.txt';
$newFileContent = "some text... in a file number $filecount.";
if(file_put_contents($newFileName, $newFileContent))
echo "Woow!";
else
echo "Oups!";
?>
I am inserting file record in table with title of file, path, filename.
The issue is when I enter title without the spaces the record gets inserted in the database but if I add spaces in title then the record is not getting inserted.
Only the file gets uploaded on the server if I add space in title and record dose not get inserted in the database.
If I do not add space in title it works well.
Main page
<?php
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
session_start();
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
?>
<!DOCTYPE html>
<html>
<head> </head>
<body>
<title>File upload</title>
<form action="fileUpload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<br><br>
<input name = "file" type="file" id="fileToUpload"><br><br>
Enter title : <input name="title" id="title" type="text"><br><br>
Select question type : <br><br>
<?php
if (isset($_SESSION['type']))
{
$type = $_SESSION["type"]; ?>
<div id="types">
SSgt <input name="type" type="radio" id="t2" value="SSgt" <?=($type==1?"checked":"");?>>
TSgt <input name="type" type="radio" id="t1" value="TSgt" <?=($type==2?"checked":"");?>>
MSgt <input name="type" type="radio" id="t3" value="MSgt" <?=($type==3?"checked":"");?>>
</div> <br><br>
<?php
}
else {
?>
<div id="types">
SSgt <input name="type" type="radio" id="t2" value="SSgt">
TSgt <input name="type" type="radio" id="t1" value="TSgt">
MSgt <input name="type" type="radio" id="t3" value="MSgt">
</div> <br><br>
<?php
}
?>
<input type="submit" value = "Upload File">
</form>
</body>
</html>
File upload
<?php
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
session_start();
$file_result = "";
if($_FILES["file"]["error"] > 0)
{
$file_result .= "No file uploaded or invalid file.";
$file_result .= "Error code : " . $_FILES["file"]["error"] . "<br>" ;
}
else{
$target_dir = "files/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$file_result .=
"Upload " . $_FILES["file"]["name"] . "<br>" .
"type " . $_FILES["file"]["type"] . "<br>" .
"temp file " . $_FILES["file"]["tmp_name"] . "<br>";
if(move_uploaded_file($_FILES["file"]["tmp_name"],$target_file)){
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded, and your information has been added to the directory";
$type = $_POST['type'];
$title = $_POST['title'];
if(strcmp($type,'SSgt') == 0)
{
$queType = 1;
}
elseif(strcmp($type,'TSgt') == 0)
{
$queType = 2;
}
elseif(strcmp($type,'MSgt') == 0)
{
$queType = 3;
}
$dbh = new PDO('mysql:host=;dbname=air','airman', 'ai');
//Writes the information to the database
$stmt = $dbh->prepare("INSERT INTO files (file,type,title,path) VALUES (?,?,?,?)");
$stmt->execute(array($_FILES['file']['name'],$queType,$title,$target_file));
if ($dbh->lastInsertId())
{
//echo 'File inserted .';
$_SESSION["type"] = $queType;
echo '<br> Upload another file.';
}
else
{
echo($title);
echo 'File could not insert.';
}
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
I am beginner in web development, can anyone help me with these please? Thank you..
Enable PDO Exceptions with
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION`);
after your connect
I'm trying to upload multiple images to multiple directories. What I'm really doing here is form will allow users to upload two images, it will rename both the images with the same name to two directories and log it to the database. But my below code doesn't show any error while processing and after 180 seconds I'm getting an error for exceeding maximum execution time at line 11 (while (file_exists($target_full)) {). Images are 100% taken but not found on the server and also it is not being logged in the database.
I'm doing it in the simplest way. I think the problem occurs at the renaming of images from file exist. Could someone help me fix this?
function.php
<?php
$target_full = "/test/av-full/";
$target_tp = "/test/av-tp/";
$tmp = explode(".", $_FILES["photo_full"]["name"]);
$photo_full = time() . '_' . rand(100, 999) . '.' . end($tmp);
$photo_tp = "$photo_full";
$target_full = ($_SERVER['DOCUMENT_ROOT'] . "/test/av-full/");
$target_tp = ($_SERVER['DOCUMENT_ROOT'] . "/test/av-tp/");
while (file_exists($target_full)) {
$tmp = explode(".", $_FILES["photo_full"]["name"]);
$photo_full = time() . '_' . rand(100, 999) . '.' . end($tmp);
$target_full = ($_SERVER['DOCUMENT_ROOT'] . "/test/av-full/");
}
while (file_exists($target_tp)) {
$photo_tp = "$photo_full";
$target_tp = ($_SERVER['DOCUMENT_ROOT'] . "/test/av-tp/");
}
$con = mysqli_connect("localhost", "username", "password") or die("MySQL Login problem!");
mysqli_select_db($con, "database") or die("Could not connect to database!");
if (move_uploaded_file($_FILES['photo_full']['tmp_name'], $target_full)) {
if (move_uploaded_file($_FILES['photo_tp']['tmp_name'], $target_tp)) {
mysqli_query($con, "INSERT INTO table (photo_full,photo_tp)
VALUES ('$photo_full','$photo_tp')");
} else {
echo "photo 340px error.";
}
echo "The file <b>" . basename($_FILES['photo_full']['name']) . "</b> & <b>" . basename($_FILES['photo_tp']['name']) . "</b> has been uploaded, and renamed to <b>$photo_tp</b>. This is for your information.";
} else {
echo "error occured";
}
?>
index.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="function.php" enctype="multipart/form-data" method="post">
<label>upload image to database</label><br>
<br>
<label>full size image :</label> <input name="size" type="hidden" value="350000"> <input name="photo[]" type="file"><br>
<br>
<label>340px size image :</label> <input name="size" type="hidden" value="350000"> <input name="photo[]" type="file"><br>
<br>
<br>
<input name="upload" title="Add data to the Database" type="submit" value="Add Member">
</form>
</body>
</html>
Sorry if this question is really long winded but i want to be as detailed as i can in hope of getting an answer to my problem.
Basically i have a multipart form that i want to add file upload capabilities to. I have the form created, a function to handle saving the image to a directory and also a script to handle posting the form values to the database. My problem is that the i have the image storing where i want it to now on submit of the form but none of the form values are being sent to the database. I think my problem is that i am trying to store the new path name as a variable which i then call in the POST script but i think this is wrong?
The error that is thrown up is:
Notice: Undefined index: image in C:\xampp\htdocs\web_design_cms\create_wireframe.php on line 13
Here's the code for the form:
<form action="create_wireframe.php" method="post" enctype="multipart/form-data">
<!-- page_title -->
<p>
<label>Title:</label><br/>
<input type="text" class="text small" name="wireframe_title" id="wireframe_title" value="" />
<span class="note">*required</span>
</p>
<!-- page_meta_title -->
<p>
<label>Browser Title:</label><br/>
<input type="text" class="text small" name="browser_title" id="browser_title" value="" >
<span class="note">*required</span>
</p>
<!-- url_key -->
<p>
<label>Permanent Link:</label><br/>
<input type="text" class="text small" name="url_key" id="url_key" value=""/>
</p>
<!-- page_image -->
<div style="float:left" >
<!-- wireframe_type -->
<p>
<label>Type:</label><br/>
<select name="wireframe_type" id="wireframe_type" class="styled" style="width:240px">
<option value="design" > Design Draft</option>
<option value="wireframe" selected > Wireframe</option>
</select>
<span class="note">*required</span>
</p>
</div>
<div style="clear:both"></div>
<div class="message info"><p>
Allowed file types for upload: jpg,jpeg,gif,png.<br/>
Max file size: 10Mb<br/>
Picture size: 4096x4096 px
</p></div>
<p>
<label>Upload Image:</label><br/>
<input type="file" name="page_main_image" id="page_main_image" value="" />
</p>
<!-- page_bg_color -->
<p>
<label>Color:</label><br/>
<input type="text" class="text small" maxlength="6" size="6" style="width:60px" id="colorpickerField" name="page_bg_color" value="ffffff" />
<span id="colorSelector" style="background-color:#ffffff;padding:7px 10px;"> </span>
<span class="note">*required</span>
</p>
<p>
<input type="submit" class="submit small" value="Save" name="submit" />
</p>
</form>
Here's the php script 'create_wireframe.php' handling the form data:
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
if (isset($_POST['submit'])) {
//Process the form
$image = upload_file();
$wireframe_title = mysql_prep($_POST["wireframe_title"]);
$browser_title = $_POST["browser_title"];
$url_key = $_POST["url_key"];
$wireframe_type = $_POST["wireframe_type"];
$image = $_POST["page_main_image"];
$page_bg_color = $_POST ["page_bg_color"];
$query = "INSERT INTO wireframes (";
$query .= " wireframe_title, browser_title, url_key, wireframe_type, page_main_image, page_bg_color";
$query .= " ) VALUES (";
$query .= " '{$wireframe_title}', '{$browser_title}', '{$url_key}', '{$wireframe_type}', '{$image}', '{$page_bg_color}' ";
$query .= ")";
echo $query;
try { $result = mysqli_query($connection, $query);
} catch (Exception $e) {
return 'Caught exception: '+ $e->getMessage()+ "\n";
}
//Test if there was a query error
if ($result) {
//Success
// would normally use a redirect ie redirect_to("somepage.php");
//$message = "Subject created.";
redirect_to("wireframes.php");
}else {
//failure
//$message = "Subject creation failed.";
//redirect_to("add_project.php");
echo $query;
}
} else {
// This is probably a GET request
redirect_to("add_edit_wireframe.php");
}
?>
<?php
// Close database connection
if(isset($connection)){ mysqli_close($connection); }
?>
And finally the function i created for handling the storing of my images in the directory:
function upload_file(){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["page_main_image"]["name"]);
$extension = end($temp);
if ((($_FILES["page_main_image"]["type"] == "image/gif")
|| ($_FILES["page_main_image"]["type"] == "image/jpeg")
|| ($_FILES["page_main_image"]["type"] == "image/jpg")
|| ($_FILES["page_main_image"]["type"] == "image/pjpeg")
|| ($_FILES["page_main_image"]["type"] == "image/x-png")
|| ($_FILES["page_main_image"]["type"] == "image/png"))
&& ($_FILES["page_main_image"]["size"] < 200000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["page_main_image"]["error"] > 0) {
echo "Return Code: " . $_FILES["page_main_image"]["error"] . "<br>";;
}
else {
echo "Upload: " . $_FILES["page_main_image"]["name"] . "<br>";
echo "Type: " . $_FILES["page_main_image"]["type"] . "<br>";
echo "Size: " . ($_FILES["page_main_image"]["size"] / 1024) . " kb<br>";
if (file_exists("uploads/" . $_FILES["page_main_image"]["name"]))
{
echo $_FILES["page_main_image"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["page_main_image"]["tmp_name"],
"uploads/" . $_FILES["page_main_image"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["page_main_image"]["name"];
$image="{$_FILES['page_main_image']['name']}";
}
}
}
else {
echo "Invalid file";
}
return $image;
}
I'm not entirely sure but i think the problem is something to do with the variable $image that im trying to store the path name in? At the end of the function i return the variable and in the post script then try to take this value and post it into the 'page_main_image' field in the database but clearly i'm doing something wrong?
Sorry again for long post but any help you can give me will really be appreciated! Thanks
When dealing with uploaded files, such as images, you need to use $_FILES instead of $_POST to access the data.
Check out this documentation.
Edit
You need to change the main logic.
$image = upload_file(); //Good
$wireframe_title = mysql_prep($_POST["wireframe_title"]);
$browser_title = $_POST["browser_title"];
$url_key = $_POST["url_key"];
$wireframe_type = $_POST["wireframe_type"];
//Delete this, you're throwing out the value from upload_file()
$image = $_POST["page_main_image"];
would you help for my code , i need to do the multiple upload but i cant so will you help me please. i need so bad.
here's my code
i made multiple upload the form but it is not working. the output is "error array"
//HTML
<html>
<head>
<form name="Image" enctype="multipart/form-data" action="upload.php" method="POST">
<h1><font face="tahoma"> UPLOAD FILES</h1>
<label for="file">Filename:</label>
<input type="file" name="Photo[]" accept="image/*" multiple="multiple"/><br/><br/>
<input type="hidden" id="pageName" name="pageName">
<script type="text/javascript">
//get page name from parent
var value = window.opener.pageName
document.getElementById("pageName").value = value;
</script>
<INPUT type="submit" class="button" name="Submit" value=" Upload ">
<INPUT type="reset" class="button" value="Cancel"><br/><br/>
</form>
</head>
</html>
//PHP this is were upload is do.
<?php
include('global.php');
?>
<?
$uploadDir = 'directory/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'][0];
$fileName1 = $_FILES['Photo']['name'][1];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName . $fileName1;
//upload error
if ($_FILES["Photo"]["error"] > 0)
{
echo "Error: " . $_FILES["Photo"]["error"] . "<br />";
}
//photo already exixts
else
//insert image into DB
{
move_uploaded_file($tmpName, $filePath);
$filePath = addslashes($filePath);
$filePath = stripslashes($filePath);
$filePath = mysql_real_escape_string($filePath);
$query = "INSERT INTO images (image , category ) VALUES ('$filePath', '$pageName')";
mysql_query($query) or die('Error, query failed');
echo" Upload Successful. <br/> <br/>";
echo "Stored in: " . "directory/" . $_FILES["Photo"]["name"];
?>
<br/><br/>
<img width="300" height="400" src="directory /<?=$_FILES["Photo"]["name"]?>"><br/>
<?
}
}
?>
Error: Array is telling you that the error being returned is actually an Array object, not a string. If you want to see the actual error message, you need to view the full contents of the array. Something like print_r($_FILES["Photo"]["error"]); or looping through the array like so
foreach($_FILES["Photo"]["error"] as $err) {
echo "error: " . $err . "<br>";
}
Or you can just print the first error returned just as you have returned the first file in your name array echo $_FILES["Photo"]["error"][0];