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>
Related
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 display the uploaded image and it's url after it has been processed using this code but I'm a bit stuck on how I would achieve this instead of the page returning with "done..."
http://llngg6czd-site.1tempurl.com/tester/index.php
Index.php
<!DOCTYPE html>
<html>
<head>
<title>Upload Files using normal form and PHP</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="upload_image.php">
<div class="row">
<label for="image">Select a File to Upload</label><br />
<input type="file" name="image" />
</div>
<div class="row">
<input type="submit" value="Upload" />
</div>
</form>
</body>
</html>
image_upload.php
<?php
require_once('ImageManipulator.php');
if ($_FILES['image']['error'] > 0) {
echo "Error: " . $_FILES['image']['error'] . "<br />";
} else {
// array of valid extensions
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
// get extension of the uploaded file
$fileExtension = strrchr($_FILES['image']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newNamePrefix = time() . '_';
$manipulator = new ImageManipulator($_FILES['image']['tmp_name']);
// resizing to 200x200
$newImage = $manipulator->resample(200, 200);
// saving file to uploads folder
$manipulator->save('uploads/' . $newNamePrefix . $_FILES['image']['name']);
echo 'Done ...';
} else {
echo 'You must upload an image...';
}
}
Imagemanipulator.php
https://gist.github.com/philBrown/880506
Any help would be greatly appreciated.
You save the file as
'uploads/' . $newNamePrefix . $_FILES['image']['name']
Therefor you can simply show it by giving back an IMG-Tag with the 'src' attribute:
echo '<img src="./uploads/' . $newNamePrefix . $_FILES['image']['name'] . '">';
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
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];
Does anyone know any good tutorial on how to upload a file with php and save the files path to a sql server?
To upload a file you need at least a HTML POST form with multipart/form-data encoding. Therein you put an input type="file" field to browse the file and a submit button to submit the form.
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
In the upload.php the uploaded file is accesible by $_FILES with the field name as key.
$file = $_FILES['file'];
You can get its name as follows:
$name = $file['name'];
You need to move it to a permanent location using move_uploaded_file(), else it will get lost:
$path = "/uploads/" . basename($name);
if (move_uploaded_file($file['tmp_name'], $path)) {
// Move succeed.
} else {
// Move failed. Possible duplicate?
}
You can store the path in database the usual way:
$sql = "INSERT INTO file (path) VALUES ('" . mysqli_real_escape_string($path) . "')";
// ...
From http://www.w3schools.com/php/php_file_upload.asp
HTML
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
PHP
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; //<- This is it
}
}
?>
Note that to upload the file you need to specify the path to save the file. If you save the file you already know it path.