I have been struggling for some time with getting this single button upload to work, i have tried several methods to submit the upload and this one i have seems to work up to the point of the php but then something in the php seems to not like the submit, without the js this works as a regular select file and upload, but soon as i add the js (which appears to work) the php then doesnt work.
Im totally confused why this is happening!
Any advice appreciated thanks!
The upload form
<form name="form" method="POST" enctype="multipart/form-data" action="updateProfilePic_script.php">
<div class="update_header_pic">
<input type = 'button' value = 'Choose image'
onclick ="javascript:document.getElementById('Photo').click();">
<input id='Photo' type='file' style='visibility: hidden;' name='Photo' onchange='submit();'/>
</div>
</form>
The php
<?
session_start();
$user = $_SESSION['username'];
$hostname = "localhost";
$db_user = "xxxusername";
$db_password = "xxxpassword";
$database = "xxxdatabase";
$db_table = "user_profile_pic"; // image table
# THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db);
$uploadDir = 'usermedia/users/images/profileimages/'. $user .'/';//Image Upload Folder
if (!is_dir($uploadDir) && !mkdir($uploadDir)){
die("Error creating folder $uploadDir");
}
if(isset($_POST['submit'])) {
$date = date("Y-m-d H:i:s");
$unique = substr(number_format(time() * rand(),0,'',''),0,10);
$fileName = $unique .'-'.$_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image , username , datetime , filesize , filetype ) VALUES ('$filePath' , '$user' , '$date' , '$fileSize' , '$fileType' )";
mysql_query($query) or die('Error, query failed');
header('Location: edit_myProfile.php');
}
?>
In your HTML form there is no [input type=submit] then why in your PHP code you did:
if(isset($_POST['submit'])) {
//...
//..
}
You can simply change it to:
if(isset($_FILES['Photo'])) {
//the your uploading procedure
}
Related
Hi stackoverflow family ,
my problem is that i want to upload multiple files (php/html/css etc..) and keep my old version of files like github does, like to upload new files and when i want go back to my olds files i find it and i can download it i searched in stackoverflow if there's someone that asked about this topic to help me and i didn't find anything
the main idea is that i can upload files (html/css/sql etc..) and when i want to upload new files i can anytime go back and find the old version of files like github exactly
<form method="POST" action="php/upload.php" enctype="multipart/form-data">
<div class="control-panel">
<label>Project folder name</label>
<input type="text" name="directoryName"><br>
<label>Project name</label>
<input type="text" name="projectName"><br>
<label>Project description</label>
<textarea name="description"></textarea><br>
<span>PUSH PROJECT</span>
<input type="file" name="uploadedFile" />
</div>
<input type="submit" class="uploadBtn button5" name="uploadBtn" value="Push" />
</form>
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "github";
$description = $_POST["description"];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_SESSION["username"];
$message = '';
echo "hello";
if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Push')
{
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK)
{
// get details of the uploaded file
$fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
$fileName = $_FILES['uploadedFile']['name'];
$fileSize = $_FILES['uploadedFile']['size'];
$fileType = $_FILES['uploadedFile']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
// sanitize file-name
$newFileName = (date("Y-m-d")."_".time()."_". $fileName) . '.' . $fileExtension;
// check if file has one of the following extensions
$allowedfileExtensions = array('jpg', 'php', 'html', 'zip', 'txt', 'xls', 'doc');
if (in_array($fileExtension, $allowedfileExtensions))
{
// directory in which the uploaded file will be moved
$dirc = $_POST["directoryName"];
mkdir($dirc);
$uploadFileDir = './'.$dirc.'/';
$dest_path = $uploadFileDir . $newFileName;
$projectName=$_POST["projectName"];
$sql = "INSERT INTO project
VALUES ('$user', '$dest_path','$description','$projectName')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if(move_uploaded_file($fileTmpPath, $dest_path))
{
$message ='File is successfully uploaded.';
}
else
{
$message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
}
}
else
{
$message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions);
}
}
else
{
$message = 'There is some error in the file upload. Please check the following error.<br>';
$message .= 'Error:' . $_FILES['uploadedFile']['error'];
}
}
$_SESSION['message'] = $message;
//begin *********************************************************************
header("Location: ../");
I am trying to upload a image to MySQL databases using php5 script. And I am receiving an notice error.
Error, query failed
UploadImage.php
<?php
session_start();
?>
<HTML>
<HEAD>
<TITLE> Image Upload</TITLE>
</HEAD>
<BODY>
<FORM NAME="f1" METHOD="POST" ACTION="uploadImage2.php" ENCTYPE="multipart/form-data">
<table>
<tr><td> Image Upload Page </td></tr>
<tr><td> <input type="file" name="imgfile"/></td></tr>
<tr><td> <input type="submit" name="submit" value="Save"/> </td></tr>
</table>
</FORM>
</BODY>
</HTML>
UploadImage2.php
<?php
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['submit']) && $_FILES['imgfile']['size'] > 0)
{
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
mysql_query($query) or die('Error, query failed'.mysql_errno($dbconn) . ": " . mysql_error($dbconn) . "\n");
$imgid = mysql_insert_id(); // autoincrement id of the uploaded entry
//mysql_close($dbconn);
echo "<br>Image successfully uploaded to database<br>";
echo "View Image";
}else die("You have not selected any image");
?>
I have upload an image file but still have error on it.
But now I have counter another error for view Image.
<?php
// get the file with the id from database
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['id']))
{
$id = $_REQUEST ['id'];
$query = "SELECT img_name, img_type, img_size, img_data FROM img_tbl WHERE id = ‘$id’";
$result = mysql_query($query) or die(mysql_error());
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
print $content;
mysql_close($dbconn);
}
?>
The error code:
Notice: Undefined variable: id� in C:\xampp\htdocs\sandbox\Testing\uploadImage2_viewimage.php on line 12
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '�' at line 1
Please advise...
Remove the ' ' from table fields in query .use this query :
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
also please start to use PDO or mysqli as your query is open for sql injection
This should work:
$query = "
INSERT INTO `img_tbl`
(`img_name`, `img_type`, `img_size`, `img_data` )
VALUES
('".$fileName."', '".$fileType."', '".$fileSize."', '".$imgContent."')
";
Seems that some special characters in $imgContent is breaking the query string
Please use mysql_real_escape_string to format your data before sending to the database
mysql_real_escape_string
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
UPDATE
If the first solution didn't fix the problem , please check are there any NULL values , you have some database columns which set to NOT NULL . so you cannot insert NULL values to them .
Hope this helps :)
I have an image submission form that just uses a simple action="" to get to a PHP page that adds the submission details to the DB and creates a unique page for the submission. That works fine. However, I want it to redirect to their submission page (created with fwrite()) How would I do this? Code below.
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "templates/";
$submissions_path = "submissions/";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_GET['right_form_title'];
$filename = $_GET['right_form_url'];
$submitter = $username;
$type = exif_imagetype($_GET['right_form_url']);
list($width, $height) = getimagesize($filename);
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
$php_file_name = $name.".php";
$path_for_link = $submissions_path.$php_file_name;
$tpl = file_get_contents($tpl_path.$tpl_file);
$tpl_and_values = preg_replace("(%([a-z_][a-z0-9_]*)%)ie",'$$1',$tpl);
$fh = fopen($submissions_path.$php_file_name, "w");
fwrite($fh, $tpl_and_values);
fclose($fh);
?>
Adding this after you close the file would work just fine.
header('location: '.$submissions_path.$php_file_name);
I believe all you need to do is stick a header at the bottom of that file which will redirect to the newly created file. Try adding this at the bottom of your file.
header('Location: '.$submissions_path.$php_file_name);
Here's the code:
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "templates/";
$submissions_path = "submissions/";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_POST['name'];
$filename = $_POST['filename'];
$submitter = $username;
list($width, $height) = getimagesize("$filename");
$type = exif_imagetype($_POST['filename']);
$checkuser = mysql_query("SELECT filename FROM images WHERE filename='$filename'");
$filename_exist = mysql_num_rows($checkuser);
if($filename_exist > 0){
echo "I'm sorry but this image has already been submitted. Please feel free to try another.";
unset($filename);
include 'upload.php';
exit();
}
if (exif_imagetype($_POST['filename']) == IMAGETYPE_GIF) {
echo "Sorry, but we can't accept GIFs. Please feel free to try uploading another.";
unset($filename);
include 'upload.php';
exit();
}
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "Thanks for your submission!<br/> Upload another <a href='/~lyons/upload.php'>here</a>!";
$tpl = file_get_contents($tpl_path.$tpl_file);
$php_file_name = $name.".php";
$fh = fopen($submissions_path.$php_file_name, "w");
fwrite($fh, $tpl);
fclose($fp);
?>
When a user submits a picture, it is supposed to automatically create a page based on a template. Here's the code for the template:
<html>
<title><?php echo $name; ?></title>
<head>
</head>
<body>
<h1><?php echo $name ?></h1>
Posted by: <?php echo $username ?>
<br/>
<img src="<?php echo $filename ?>"/>
</body>
</html>
As you might have already guessed, I want it to put in values for name, username, and filename that were derived in the first script where they submit the picture. However, it seems they don't carry over. The page is created, but where ever it's supposed to echo the values for the variables, it is blank. How can I include the values for those variables that I want to use in the created page?
Thanks in advance to whoever can help me.
I would suggest using a string like %name%, %username% etc. to mark placeholders for variables.
Then, before writing to the file, try something like this:
$tpl = preg_replace("(%([a-z_][a-z0-9_]*)%)ie",'$$1',$tpl);
This will find, for example, %filename% and replace it with the contents of the variable $filename.
Look up PHP Sessions
It is a built-in feature to PHP used for exactly what you're doing.
Sessions store data on a per-user basis however, so if you're wanting other people to see the variables, you're going to have to use either a database or saving to a file.
Here is the site.
I have the submit page, and a form action to a page that queries the submission info into my database. I'll include that code below. What I want to do, is have it create an individual page for each submission. However, I'm getting tons of errors when I try to upload. It uploads but it definitely doesn't create new page. the I have a template form which I'll show you, but first, here's the upload page:
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_POST['name'];
$filename = $_POST['filename'];
$submitter = $username;
list($width, $height) = getimagesize("$filename");
$type = exif_imagetype($_POST['filename']);
$checkuser = mysql_query("SELECT filename FROM images WHERE filename='$filename'");
$filename_exist = mysql_num_rows($checkuser);
if($filename_exist > 0){
echo "I'm sorry but this image has already been submitted. Please feel free to try another.";
unset($filename);
include 'upload.php';
exit();
}
if (exif_imagetype($_POST['filename']) == IMAGETYPE_GIF) {
echo "Sorry, but we can't accept GIFs. Please feel free to try uploading another.";
unset($filename);
include 'upload.php';
exit();
}
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "Thanks for your submission!<br/> Upload another <a href='/~lyons/upload.php'>here</a>!";
$placeholders = array("{name}", "{filename}", "{username}");
$tpl = file_get_contents($tpl_path.$tpl_file);
$new_member_file = str_replace($placeholders, $data, $tpl);
$php_file_name = $username.".php";
$fp = fopen($submissions_path.$php_file_name, "w");
fwrite($fp, $new_submission_file);
fclose($fp);
?>
And here's the template file (submission.php)
<html>
<title>{name}</title>
<head>
</head>
<body>
<h1>{name}</h1>
Posted by: {username}
<br/>
<img src="{filename}"/>
</body>
</html>
It looks like you might have a path issue. When you use the path "/~lyons" you may not be pointing to the directory you want. Try making the changes below:
// For use in creating individual page
$tpl_file = "submission.php";
//$tpl_path = "/~lyons/templates/";
$tpl_path = "templates/";
And then please post the new error message(s), if any.
To help you in debugging, try turning error reporting and error display on.
// add after <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Opening the file is probably failing, for better error control try this:
$fp = #fopen($submissions_path.$php_file_name, "w");
if (!$fp) {
die('Failed to open file! Reason: ' . $php_errormsg);
}
I think your paths are incorrect, most likely the following 2 lines need to be changed to use a full path.
// change
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// to
$tpl_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/templates/";
$submissions_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/submissions";
When you go to open the file, it is trying to open /~lyons/templates/ which is a directory that does not exist, it is probably something like /home/lyons/public_html/templates/ or /home/something/public_html/~lyons/templates or /usr/local/apache2/htdocs/~lyons/templates etc. $_SERVER['DOCUMENT_ROOT'] should fill in the correct value, but in few cases you may need to manually set the correct path and prepend it to your $tpl_path and $submissions_path.
**save the "submission.php" in root folder**
`$tpl_file = "submission.php";`
**create "templates/`" folder in root folder**
`$tpl_path = "templates/";`