I have a form which is meant to upload articles to my database within this form I have a file upload field the objectives of my file upload is as follows:
Limit file extensions to image format
Rename file to something random
Create a new directory based on the ID of the entry into the database
Keep the extension of the file that is uploaded
Every time I hit the submit button the form seems to think I have tried to upload a file that isn't in the list of allowed extensions, it prints this error (the fields however are uploaded to the database):
wrong files format , allowed only "Array"
I'm not quite sure why this is the case as I know I'm inputting the correct file format.
public function insert ($field) {
if ($stmt = $this->mysqli->prepare("INSERT INTO articles (title, story, storyb, storyc, author, date_created, section, youtubeid) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) {
/* Set our params */
$title = isset($_POST['title']) ? $this->mysqli->real_escape_string($_POST['title']) : '';
$story = isset($_POST['story']) ? $this->mysqli->real_escape_string($_POST['story']) : '';
$storyb = isset($_POST['storyb']) ? $this->mysqli->real_escape_string($_POST['storyb']) : '';
$storyc = isset($_POST['storyc']) ? $this->mysqli->real_escape_string($_POST['storyc']) : '';
$author = isset($_POST['author']) ? $this->mysqli->real_escape_string($_POST['author']) : '';
$date_created = isset($_POST['date_created']) ? $this->mysqli->real_escape_string($_POST['date_created']) : '';
$section = isset($_POST['section']) ? $this->mysqli->real_escape_string($_POST['section']) : '';
$youtubeid = isset($_POST['youtubeid']) ? $this->mysqli->real_escape_string($_POST['youtubeid']) : '';
/* Bind our params */
$stmt->bind_param('ssssssss', $title, $story, $storyb, $storyc, $author, $date_created, $section, $youtubeid);
/* Execute the prepared Statement */
$stmt->execute();
/* Echo results */
echo "Inserted {$title} into database\n";
/* Close the statement */
$stmt->close();
}
else {
/* Error */
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
// Handling file upload
$extensions = array(".jpg",".jpeg",".gif",".png", ".JPG", ".JPEG", ".PNG", ".GIF");
$extension = strrchr($_FILES['uploadImage']['name'], '.');
$path = "../files/uploads/articles_gallery/" . $this->mysqli->insert_id;
$filename = uniqid(rand(), true);
if (!in_array($extension, $extensions))
{
echo'<center>wrong files format , allowed only <strong>"'.$extensions.'"</strong></center>';
} else {
if (!is_dir($path))
{
die('Error: ' . $mysqli->error());
}
echo "<h3>1 record added</h3>";
mkdir($path, 0777);
move_uploaded_file($_FILES['uploadImage']['tmp_name'], $path, $filename);
} // File Upload End
}
Insert.php
<div id="form">
<form action="insert.php" method="post" name="insert" id="articleform">
<input type="input" name="title" id="title" class="detail" id="title"/>
<textarea name="story" id="story" class="detail" placeholder="Insert article here"></textarea>
<input id="uploadImage" type="file" name="uploadImage" onchange="PreviewImage();" class="" />
<img id="uploadPreview" style="width: 250px; height: 200px;" />
<textarea name="storyb" id="storyb" class="detail" spellcheck="true" placeholder="Insert article here"></textarea>
<textarea name="storyc" id="storyc" class="detail" spellcheck="true" placeholder="Insert article here"></textarea>
<input type="input" name="author" id="author" class="detail"/>
<? $today = date("l j M Y"); // Monday 13 April 2013 ?>
<input type="hidden" name="date_created" id="date_created" class="detail" value="<? echo $today;?>" />
<input type="hidden" name="section" id="section" class="detail" value="game"/>
<input type="input" name="youtubeid" class="detail" id="youtubeid" />
<input type="submit" id="submit" name="submit" value="Submit Article " />
</form>
strchr() will give you true/false if the character (in your case, ".") exists in the string. So to get the file extension, you could use something like:
$extension = end(explode('.', $filename));
.. But maybe a function like pathinfo() could be usefull in this case too.
Furthermore, in your error message you use $extensions. This is a var with type "array", and thus the string representation is "Array". I think you meant $extension (without the S) there. Or, maybe, you want to list all correct extensions this way: implode(',', $extensions).
Note that checking on extensions is not a safe way to check what kind of content is present. I can easily upload a .exe, by just renaming it to .jpg.
Oh, and chmod-ing a directory/file to mode 777 is highly discouraged due to security reasons.
if you want to display the available extension you can't just concat your array with your message. you have to iterate all values.
The code to get extension is wrong.
$extension = strrchr($_FILES['uploadImage']['name'], '.');
change it to
$extension = strtolower(substr($_FILES['uploadImage']['name'],-3,3));
if extension is 3 characters long or explode()
and get the last parametr. This is not good way anyway, I prefer to check MIME type
$extension = strtolower(end(explode('.', $_FILES['uploadImage']['name'])));
change your extension array to
$extensions = array("jpg","jpeg","gif","png");
also add to your form
enctype="multipart/form-data"
your error message is wrong because you want to echo array instead of string use implode() to join array
implode(";",$extensions)
update your form from:
<form action="insert.php" method="post" name="insert" id="articleform">
To :
<form action="insert.php" method="post" name="insert" id="articleform" enctype="multipart/form-data">
Related
The code uploads the files and is supposed to submit the file path to the database so I can use the file paths elsewhere.
All the files upload fine in the loop, but for some reason, after it successfully submits the first MySQL stmt insert, it somehow bypasses the inserts that come after when it goes through the loop again, to upload the next file in the $_FILES[] superglobal
Here is the markup for the form
<?php
session_start();
include 'includes/functions.php';
drawHeader();
echo'
<div class="main_content_container">
';
if ( isset($_SESSION['userId'])) {
$amz_numb = $_GET['amz_numb'];
echo'
<form action="http://Localhost/Tierrashop.ca/includes/upload.php"
method="post" enctype="multipart/form-data">
Send these files
<input name="amz_numb" type="hidden"
value="'. $amz_numb .'"/><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<button type="file">Upload Files</button>
</form>
<a href="http://localhost/Tierrashop.ca/content_upload.php">
<button>Go back to product details... </button></a>
';
} else {
echo '';
}
//close of main content div
echo '</div>';
drawFooter();
?>
PHP file that launches upon form submission
<?php
include 'config.php';
if (isset($_POST['amz_numb'])) {
$uploadlocation = "../product_images/";
$amz_numb = $_POST['amz_numb'];
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for ($i = 0; $i < $countfiles; $i++) {
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i], $uploadlocation . $filename);
$directory_location = $uploadlocation . basename($filename);
chmod($directory_location, 0644);
//insert amz numb and path into db
$stmt = mysqli_prepare($conn, "INSERT INTO images ( amz_product_code, filepath )
VALUES (?,?)");
mysqli_stmt_bind_param($stmt, 'ss', $amz_numb, $directory_location);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
}
Take a look at this please:
https://www.php.net/manual/en/mysqli-stmt.close.php
The user contributed note might be helpful for your case:
"if you are repeating an statement in an loop using bind_param and so on inside it for a larger operation. i thougt id would be good to clean it with stmt->close. but it broke always with an error after aprox. 250 operations . As i tried it with stmt->reset it worked for me."
This might be the better option: https://www.php.net/manual/de/mysqli-stmt.reset.php
Or - much better - use PDO!
UPDATE: More on PDO
If you don't know how to use the more modern standard "PDO" (if I recall it correctly it stands for "PHP Data Objects") this should be really helpful. I used this myself to make my own database handler.
https://culttt.com/2012/10/01/roll-your-own-pdo-php-class/
The only caveat: The link above is a bit US centric. If you use it like that you will be in trouble if you support other languages in addition to English(US).
In //Define Configuration you should add:
define("DB_CHARSET", "utf8mb4");
Then in the database class itself you should add:
private $charset = DB_CHARSET;
"Set DSN" should consequently be modified like this:
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . ';charset=' . $this->charset;
Apart from these minor changes the example is still very useful.
Yaaaaa, none of that resetting stuff helped.
Figured out you don't have to keep preparing the statement, however not sure if that's what was stopping it.
I had it uploading the file, than was preparing the stmt to then execute.
In the php.ini file I had:
max_file_uploads = 3, which explained why only three files were getting inserted and locking up the script in the loop.
Also I changed post_max_size = 150mb thinking that this allows all those files to be stored in the tmp_name key in the $_FILES superglobal
I have a problem that made me lose my temper really I have the following code
OK ?
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
$finalpath =realpath(dirname(__FILE__)."/Uploads/".$path);
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
$type = $_FILES["vedio"]['type'];
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
The first problem is supposed to be the process of uploading the file to file uploads
The file is not even uploaded to the same file as the page
Second, the goal is to write the name of the file uploaded within the text, but what is happening in reverse exactly that
So how to make the upload process successful
Inside the uploads / value received from the form section
And the new name of the received value of the form
<form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
<div id="inputs">
<label class="labels" for="name">Vedio Name: </label>
<input id="name" type="text" name="vedionamet" value="vedio"> </br>
<label class="labels" for="selectsection">Select Section :</label>
<select name="selectsection" id="section" >
<?php
foreach($sections as $pathat){
echo "<option value='$pathat'>" . "$pathat" . "</option>";
};
?>
</select></br>
<label class="labels" for="upup">Select Vedio : </label>
<input id="upload" type="file" name="vedio"></br>
<input id="subb" type="submit" name="uploadsub" value="Upload">
</
For the HTML part, you may change the action to "#" if you want to use a same page to handle the upload request.
For the PHP part, you may try the following codes, it works on my computer. Please also make sure that you have already established these sub video folders in Uploads folder
<?php
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
//add one condition to avoid warning when the page first loads
if(isset($_POST["selectsection"])){
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
//Use this to get the path
$finalpath = realpath(dirname(getcwd())) . '\\Uploads\\' . $path. '\\';
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
//Use this to get the extension of file name
$type = pathinfo($vedname, PATHINFO_EXTENSION);
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname.".".$type);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
}
?>
I have a mobile web app form where I access the mobile device camera and capture a photo along with some other details captured within other fields in the form. Using php I save the information captured in the form to a mysql database sucessfully, but the image is not stored. I have searched for a resolution but cannot find anything on using php with
<input type="file" accept="image/*;capture=camera">
to store the image in a database. The database field is currently blob but this can change if needed.
The form works perfectly for all other data, so the issue is with my lack of understanding of how to handle images or files with php. can anyone help or point me in the right direction please. The basis of my code is pasted below.
The form save is working fine as the bus_name input saves to the database, but the bus_img record is blank.
HTML
<div data-role="page" id="view_record">
<div data-role="header">
Back
<div data-role="main" class="ui-content">
<form method="post" enctype="multipart/form-data" action="saveRecord.php">
<label for="bus_name">Business Name:</label>
<input type="text" name="bus_name" id="bus_name" placeholder="Enter Business Name">
<label for="bus_type">Business Type:</label>
<input type="text" name="bus_type" id="bus_type" placeholder="Enter Business Type">
<label for="bus_tel">Business Tel:</label>
<input type="text" name="bus_tel" id="bus_tel" placeholder="Enter Business Tel No">
<label for="bus_img">Business Photo:</label>
<input type="file" name="bus_img" id="bus_img" accept="image/*;capture=camera">
<label for="comments">Comments:</label>
<textarea name="comments" id="comments" placeholder="Enter Comments"></textarea>
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
PHP
<?php
$bus_img = $bus_name = "";
$servername = "";
$username = "";
$password = "";
$dbname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());}
$bus_img = $_FILES["bus_img"];
$bus_img = mysqli_real_escape_string($conn, $bus_img);
$bus_name = $_POST["bus_name"];
$sql = "INSERT INTO tblLead(leadImage, occupantName)
VALUES ('$bus_img','$bus_name')";
if (mysqli_query($conn, $sql))
{
} else
{
echo "Error: " . $sql . mysqli_error($conn);
}
mysqli_close($conn);
exit();
}
?>
ANy help much appreciated. Thanks
Firstly, file handling requires $_FILES and not $_POST.
Your form tag does not contain a proper enctype to handle files.
As per the manual's example on files handling:
<form enctype="multipart/form-data" action="__URL__" method="POST">
Reference:
http://php.net/manual/en/features.file-upload.post-method.php
Then you need to escape that (file) data and there are a few ways to do this.
One of which being mysqli_real_escape_string($conn, $file)
Reference:
http://php.net/manual/en/mysqli.real-escape-string.php
Something you should also be using against all your data as it is presently open to an SQL injection.
I.e. and by replacing:
$bus_img = $_POST["bus_img"];
with:
$bus_img = $_FILES["bus_img"];
$bus_img = mysqli_real_escape_string($conn, $bus_img);
And make sure that the file does not exceed the maximum uploaded size allowed/set on your server.
Use proper error checking also.
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am currently creating a system where a user can upload both information a corresponding picture to a db. However, when I call the move_upload_file() function, it is not liking my syntax when specifying the new destination.
The line of code I am referring to looks like this:
if(move_uploaded_file($_FILES['upload']['tmp_name'], "images/{$_FILES['upload']['name']")){
And the error I'm getting is
Parse error: syntax error, unexpected '")){'
(T_CONSTANT_ENCAPSED_STRING), expecting '}' in
/Applications/XAMPP/xamppfiles/htdocs/serverside/phptut/addbyform.php
on line 27
I am also using Sublime Text 2 and ['upload'] highlights in bright pink.
For further context this is my entire script thus far:
<?php
printForm();
//when "submit" tie together values and variables
if($_POST['submit']=="Submit"){
$email = cleanData($_POST['email']);
$first = cleanData($_POST['first']);
$last = cleanData($_POST['last']);
$status = cleanData($_POST['status']);
//$image = cleanData($_POST['image']);
//echo "Data cleaned";
addData($email, $first, $last, $status);
}
else{
//printForm();
}
function checkUpload(){
//check for uploaded files
if(isset($_FILES['upload'])){ //upload refers to form element "upload"
$allowed = array ('image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/GIF');
if(in_array($_FILES['upload']['type'], $allowed)){//if upload if in the allowed file types
echo "uploading files...";
//move the file over
if(move_uploaded_file($_FILES['upload']['tmp_name'], "images/{$_FILES['upload']['name']")){
//moveuf method moves to tmp folder then moves to final location
echo "<p>The file has been uploaded 'dude'</p>";
$image="{$_FILES['upload']['name']}";
print "$image";
}//end of moving DAT IMG :3
else{
echo '<p>Please upload a JPEG, GIF or PNG image.<p>';
if($FILES['upload']['error'] > 0){
}
}
}
}
}
//cleans information
function cleanData($data){
if(!$status){ //everything except for status take out spaces
$data = trim($data);
}
$data = stripslashes($data);//no slashes
$data = htmlspecialchars($data);//no special characters
$data = strip_tags($data);//no html tags
return $data;
}
//inserts data into db
function addData($email, $first, $last, $status){
//echo "Ready to add data";
include("dbinfo.php");//access db
$image = checkUpload();
$sql = "INSERT INTO contacts VALUES(null, '$email', '$first', '$last', '$status', '$image')";
//null because of ID aka primary key automatically incremented:3
$result = mysql_query($sql) or die(mysql_error());
//takes sql arugment for query OR if it can't you get a BUMMER DUDE
echo <<<HERE
<b>The following has been added:</b>
<ul>
<li>E-mail: $email</li>
<li>First: $first</li>
<li>Last: $last</li>
<li>Status: $status</li>
<li>Image File:<br/> <img src="images/$image" /></li>
</ul>
HERE;
}
function printForm(){
$pageTitle ="Add a Contact";
include("header.php");
echo <<<EOD
<b>Add a Contact</b>
<form method = "POST" enctype="multipart/form-data">
<div>
<label for="email">Email*:</label>
<input type="text" name="email" id="email" required="required">
</div>
<div>
<label for="first">First Name*:</label>
<input type="text" name="first" id="first" required="required">
</div>
<div>
<label for="last">Last Name*:</label>
<input type="text" name="last" id="last" required="required">
</div>
<div>
<label for="status">Status*:</label>
<input type="text" name="status" id="status" required="required">
</div>
<div>
<label for="image">Image*:</label>
<input type="file" name="upload" size="30" id="upload" required="required"><br/>
<small>Must be less than 512kb. Only JPG, GIF, and PNG files</small>
</div>
<div id="mySubmit">
<input type="submit" name="submit" value="Submit">
</div>
</form>
EOD;
}
include("footer.php");
?>
Would anyone be able to let me know what I am doing wrong?
Thanks.
You missed one bracket !
if(move_uploaded_file($_FILES['upload']['tmp_name'], "images/{$_FILES['upload']['name']}")){
The one after ['name'] ...
I've managed to get a photo to be uploaded to the server and then written to the database thanks to quite a bit of help but I need to be able to upload three files and each needs to be written to the database accordingly. So at the moment only photo1 is being uploaded and written, I'd like to create another form input for photo2 and 3 and have them also written and uploaded. Sorry I'm almost a complete beginner with php, any help will be hugely appreciated! thanks in advance.
<?php
session_start();
include_once('../php/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_POST['title'], $_POST['content'], $_FILES['photo1'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
$name = $_FILES['photo1']['name'];
$tmp_name = $_FILES['photo1,']['tmp_name'];
$target = '../lifestyle/'.$name;
if (move_uploaded_file($tmp_name, $target)) {
$stmt = $pdo->prepare('INSERT INTO article (article_title, article_content, photo_1, photo_2) VALUES (?,?,?,?)');
$stmt->execute(array($title,$content,$name,));
header('Location: index.php');
exit();
}
}
?>
<form action="add.php" method="post" autocomplete="off" enctype="multipart/form-data"/>
<<input type="text" name="title" id="title"/>
<textarea name="content"></textarea></dt>
<input type="file" name="photo1" >
<input type="submit" id="add article"/>
</form>
Use attribute multiple and make some sort of array of the name:
<input type="file" name="photo[]" multiple >
OR
<input type="file" name="photo[]">
<input type="file" name="photo[]">
<input type="file" name="photo[]">
http://php.net/manual/en/features.file-upload.multiple.php