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!";
?>
Related
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>
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
I have a form that on submit creates a unique .txt filename and posts form data into that file. That works well. The issue is after it creates the file, I need a way to append it without creating another text file. Because it is a form, when it submits, the code reruns each time submit is called and I'm not sure how to handle it.
Here is the form:
<body>
<form action="write_to_txt_file2.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
Here is the php:
I don't have to use the microtime as the unique variable name so if there is a better way, I'm open to changing it.
<?php
$myDate = round(10*microtime(TRUE));
$filename = "tmp/".$myDate.".txt";
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
Alternatively, you could utilize sessions also to this, set the filename if not set using that same generator, so that you could use it again after the next submissions.
Simple example:
session_start();
if(!isset($_SESSION['file'])) {
$_SESSION['file'] = round(10*microtime(TRUE)); // set a filename on initial load
}
if(isset($_POST['submit'])) { // if submitted
$myDate = $_SESSION['file'];
$filename = "tmp/".$myDate.".txt";
if(isset($_POST['field1'], $_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
}
if(isset($_POST['create'])) {
$_SESSION['file'] = round(10*microtime(TRUE)); // creates another filename
}
?>
<form action="" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data" />
<input type="submit" name="create" value="Create New" />
</form>
I have a single file named test.php. In this file, I written below codes to upload a picture (.PNG and .JPG). I also add some code to make a preview of pictures before being uploaded...
Nothing seems to be wrong but when I press the SUBMIT button, nothing happens...
Why? Where is my problem?
Update: I make changes and now I get this warning:
Warning: Invalid argument supplied for foreach() in...
test.php:
<script type="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<body>
<?php
if ( isset( $_POST[ 'submit' ] ) ) {
define ("UPLOAD_DIR" , "uploaded/pic/");
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
$info = getimagesize($_FILES["images"]["tmp_name"][$key]);
$image_type = $info[2];
$type = $_FILES['images']['type'][$key];
// if the image is .JPG or .PNG
if ( ($image_type == 3) || ($image_type == 2) ){
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $name);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["images"]["tmp_name"][$key], UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
echo "<h2>Successfully Uploaded Images</h2>";
}
else{
echo "<h2>format not supported... </h2>";
}
}
}
}
?>
<div id="upload_form">
<form id="frm1" name="frm1" method="post" action="test.php" enctype="multipart/form-data">
<p>
<label for="images">insert your image</label>
<input type="file" name="images" id="images" tabindex="80"/>
</p>
<img id="pic" name="pic" src="#" />
<button type="submit" id="submit" name="submit">Upload Files!</button>
</form>
<script type="text/javascript" language="javascript">
// Preview the picture before Uploading on the server!
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pic').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#images").change(function(){
readURL(this);
});
</script>
</div>
You need to put your name="images as an array using []
Like this:
<input type="file" name="images[]" id="images" tabindex="80"/>
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];