HTML file input not working in PHP - php

I'm making a social media website for a project. I have a PHP function that allows the user to upload an image to a post and inside the function is an html form to allow them to select a form.
echo "<form method='post' enctype='multipart/form-data'>";
echo "<input type='file' name='myFile'/>";
echo "<label for='myFile' id='fileLabel'>File input</label>";
echo "<input type='submit' name='submitFileForm' value='Upload' />";
echo "</form>";
When I process the form with this code and print_r($_FILES) is empty but if I echo $_POST['myFile'] it displays the correct file name.
if (isset($_POST['submitFileForm'])) {
print_r($_FILES);
$my_folder = "img/";
if (move_uploaded_file($_FILES['myFile']['tmp_name'], $my_folder . $_FILES['myFile']['name'])) {
echo 'Received file' . $_FILES['myFile']['name'] . ' with size ' . $_FILES['myFile']['size'];
} else {
echo 'Upload failed!';
var_dump($_FILES['myFile']['error']);
}
}
Thank you for the help , I have been trying to debug this for the last 2 hours. Also I forgot to mention, I already tried increasing upload_max_filesize = 100M and input_max_size = 100M and that is not the problem.

You have to change the if condition as following
if (isset($_POST['submitFileForm'])) {
It will be working

Related

PHP, using $_FILES and $_POST at the same time

I have a problem in using $_FILES and $_POST at the same the because I have a form to upload an image and some data bus when I use one of them it works but when I used the other one id doesn't work.
my code is :
<?php
include 'debugging.php';
//phpinfo();
echo '<br />';
echo '<h1>Image Upload</h1>';
//create a form with a file upload control and a submit button
echo <<<_END
<br />
<form method='post' action='uplaodex.php' enctype='multipart/form-data'>
Select File: <input type='file' name='picName' size='50' />
name: <input type='text' name='usName' size='50' />
username : <input type='text' name='usUsername' size='50' />
pass: <input type='password' name='usPass' size='50' />
email: <input type='text' name='usEmail' size='50' />
<br />
<input type='submit' value='Upload' />
<input type="hidden" name="submit" value="1" />
</form>
<br />
_END;
//above is a special use of the echo function - everything between <<<_END
//and _END will be treated as one large echo statement
//$_FILES is a PHP global array similar to $_POST and $_GET
if (isset($_FILES['picName'])and isset($_POST['submit'])) {
//we access the $_FILES array using the name of the upload control in the form created above
//
//create a file path to save the uploaded file into
$name = "images//" . $_FILES['picName']['name']; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if (move_uploaded_file($_FILES['picName']['tmp_name'], $name)) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
//we are going to store the file type and the size so we get that info
$type = $_FILES['picName']['type'];
$size = $_FILES['picName']['size'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//select the ID of the image just stored so we can create a link
//display success message
echo "<h1> Thankyou </h1><p>Image stored successfully</p>";
//this above line of code displays the image now stored in the images sub directory
echo "<p>Uploaded image '$name'</p><br /><img src='$name' height='200' width='200'/>";
//create alink to the page we will use to display the stored image
echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
} else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
}
} else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
echo "</body></html>";
?>
I don't know what is the problem, any help??
Everything inside that if (isset($_FILES['picName'])and isset($_POST['submit'])) doesn't work because the superglobal $_FILES is probably not having a key named picName. To check this out, try var_dump-ing the $_FILES, like var_dump($_FILES);
By the output of the var_dump you'd get to know if there is any content inside $_FILES. And if it is populated, just see what the key name is and, access the file by using that key.
But if the array is empty, there may be some mis-configurations in PHP, or APACHE.
One possible fix would be setting file_uploads = On in the ini file for php.
Hope it helps!
You have to validate the size of the file if you want to do an isset. I don't know if this is works, but the better way for do that is check first the size for validate if isset or was send to the server.
Then, in your <form method='post' action='uplaodex.php' enctype='multipart/form-data'> you have to create another PHP file with the name uplaodex.php where you'll send al the data. So, your code with be like the below code following and considering the step 1. This will be your uploadex.php
$name_file = $_FILES['picName']['name'];
$type = $name_file['type'];
$size = $name_file['size'];
$tmp_folder = $name_file['tmp'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
if ( $size > 0 ) {
//REMOVE another slash images//
$name = "images/" . $name_file; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if ( move_uploaded_file($tmp_folder, $name) ) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//USE PRINTF
printf('<h1> Thankyou </h1><p>Image stored successfully</p><br>
<p>Uploaded file: %s</p>. <img src="%s" height="200" width="200" />',
$name_file, $name );
#WHAT IS $fileId? In which moment was define?
//echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
}
else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
} //ENDIF OF if (move_uploaded_file($_FILES['picName']['tmp_name'], $name))
} //ENDIF OF if ( $size > 0 )
#ELSE OF YOUR if ( $size > 0 )
else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
I solved the problem, you can't perform $_FILES and $_post at the same time or one of them inside the other.
start with $_Post and then $_FILES and outside the $_FILES run your saving function
thats it

echo my images on my index page PHP

i built a CMS and my image shows succesfully in the admin page(back-end) once i upload an image with the form but once on the main index page(front-end) it shows that "broke image link"
here is my function to post the uploaded image on my admin page:
function gettestimony() {
$query = mysql_query("SELECT * FROM testimony") or die(mysql_error());
while($post = mysql_fetch_assoc($query)){
echo "<img src =\"" . $post['photo']."\">";
echo "<p>" . $post['imagename'] . "</p>";
echo "<br>";
echo "<p>" . $post['test'] . "</p>";
echo "<br>";
echo "<p>" . $post['author'] . "</p>";
echo "<br>";
echo "Delete";
echo "Edit";
echo "<br>";
}
}
and the directory is htdoc/blah/admin/include/functions.php
and the image is saved in htdoc/blah/admin/image/
for my main index, this is the function to post it:
function gettestimony() {
$query = mysql_query("SELECT * FROM testimony") or die(mysql_error());
while($post = mysql_fetch_assoc($query)){
echo "<div class='column second'>";
echo "<p>" . $post['test'] . "</p>";
echo "<img src =\"" . $post['photo']."\">";
echo "</div>";
}
}
this is the code i use in both functions:
echo "<img src =\"" . $post['photo']."\">";
so like i said it works fine in admin page but my main page it doesn't....someone please help
Your image's path relative to the path of your function is irrelevant. As far as that function is concerned the path to the image is just a string.
You need to make sure the path to the image is correct relative to the HTML file that's viewing it. The easy way to make it work is to just use the full URL to the image:
www.something.com/admin/images/myimage.php

Refresh php script on submit

i have a question on a short php script here. I have created a script to edit a txt file, the script works just fine, no problem with it. Im trying to make the script reload automaticaly on submit and im really stack here.
Here is the script:
<?
if($_POST['Submit']){
$open = fopen("../youtubelink.txt","w+");
$text = $_POST['update'];
fwrite($open, $text);
fclose($open);
$file = file("../youtubelink.txt");
foreach($file as $text) {
echo $text."<br />";
}
}else{
$file = file("../youtubelink.txt");
echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
echo "<textarea Name=\"update\" cols=\"50\" rows=\"10\">";
foreach($file as $text) {
echo $text;
}
echo "</textarea>";
echo "<input name=\"Submit\" type=\"submit\" value=\"Update\" />\n
</form>";
}
?>
Any help please?
use Ajax and query every x Minutes a script that checks the text file for changes. If the Ajax returns "yes, updates available" reload the page with Javascript.

Updating a File Script Issue

I'm using this code to update a given file;
<?php
if($_POST['submit']){
$open = fopen("textfile.php","w+");
$text = $_POST['update'];
fwrite($open, $text);
fclose($open);
echo "File updated.<br />";
echo "File:<br />";
$file = file("textfile.php");
foreach($file as $text) {
echo $text."<br />";
}
}else{
$file = file("textfile.php");
echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
echo "<textarea Name=\"update\" cols=\"50\" rows=\"10\">";
foreach($file as $text) {
echo $text;
}
echo "</textarea>";
echo "<input name=\"submit\" type=\"submit\" value=\"Update\" />\n
</form>";
}
?>
But somehow its showing this error:
Although the file does updated with this code when I submit my text and no error or submission, however the error its showing on the screenshot bugs me, so any way I could remove those errors?
Thanks!
Change line 2 to this:
if(isset($_POST['submit'])){
Change line 15 to this:
echo "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\">";
Assuming that your submit button is named submit checking for $_POST['submit'] is unreliable (as not all browsers POST the submit button), you should check for another field name that is posted OR better yet, change to if($_SERVER['REQUEST_METHOD'] == 'POST'){.
Also, $PHP_SELF is assuming you have register globals on (which shouldn't be), you should use $_SERVER['PHP_SELF'] instead.
Joe has it. You want isset(). # (error suppression) is the coward's way out. Be a man and use isset() ;-)

PHP File Delete Issue?

I have the following HTML form:
<form action='delete.php' method='POST'>
<table>
<div class = '.table'>
<?php
$dir = '../uploads/store/';
$newdir = ereg_replace('\.','',$dir);
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!preg_match('/^(\.(htaccess|\.)?|index\.html)/',$file)) {
echo "<tr><td><font color = 'white'><a href='$newdir$file'>$file</a></font></td>";
echo "<td><input type='submit' value ='Delete'></td></tr>";
echo "<input align='right' type='hidden' value='$file' name='file'>";
}
}
closedir($dh);
}
}
?>
</div>
</table>
</form>
Which links to the following PHP script:
<?php
session_start();
$file = $_POST['file'];
$dir = '../uploads/store/';
$file = $dir . $file;
opendir($dir);
if(unlink($file)) {
echo "File sucessfully deleted";
$_SESSION['username'] = 'guitarman0831';
header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html');
} else {
echo "Error: File could not be deleted";
$_SESSION['username'] = 'guitarman0831';
header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html');
}
?>
However, when the Delete button is pressed in the HTML form, the item above the one intended to delete is deleted.
Hope this makes sense.
NOTE: I'm not going for security with these scripts, I'm going to work on that later. It's only me using this service right now.
Your HTML form needs to have the various submit buttons pass the value for $file instead of using hidden fields.
The problem is that all of the hidden fields are POSTed to delete.php when you submit the form. Then, since you haven't used the PHP-friendly HTML array variable syntax, PHP uses only the last of these to set the value of $_POST['file']. If you do a var_dump of $_POST in delete.php, you will see what the POSTed input is.
The easiest thing to do, with your current markup, is just to have each submit button be named file and pass $file as its value. i.e. you could do:
<button name="file" value="example.txt" type="submit">Delete</button>
Alternately, you could use radio buttons or some other markup.

Categories