I've worked with a few scripts to begin uploading files on my development machine. Problem is, despite the expected ease of this operation, Apache seems to time-out whenever I try to upload an image. Uploading is set to On and the tmp directory is set in php.ini.
I tried uploading the main gif from Google, an 8.36KB image. It should be fine and well within the limits to PHPs uploading capabilities.
Here is a copy of the script. There should be an easy fix. As requested, I changed the tilde to an actual directory.
<?php
if (!isset($_GET['upload'])) { ?>
<form method="post" action="index.php?upload=true" enctype="multipart/form-data">
<input type="file" name="file" class="form">
<input name="submit" type="submit">
</form>
<? } else if (isset($_GET['upload']) && $_GET['upload'] == 'true') {
$url = $_FILES['file']['name'];
$move = move_uploaded_file($_FILES['file']['tmp_name'], "/Users/<username>/Sites/file.jpg");
if ($move) {
echo "Success!";
} else {
echo "Err..."
}
} ?>
Thanks,
Dan
EDIT:
I fixed it, with help from a few of the answers, to one of which I will mark.
A few things here were causing this behavior.
Permissions on the images directory were not set to allow the _www user to access it. A chmod -R 777 images seemed to fix it, as well as a sudo chown _www images.
The form output may have been corrupting the PHP script itself. As suggested, an ECHO <<< ...END helped, I think.
What is it that leads you to believe that Apache is timing out rather than, say, outright failing in some way? Because what leaps out at me is that you're trying to move the file to ~/file.jpg, which I'm nearly certain will not work; ~ is a construct that only normally has meaning inside shells, unless one of PHP's freakish obscure features is processing it in contexts like this. Anyway, try putting the actual directory.
This is more than likely an issue with the size of the file and/or a permission issue between the Apache user and the directory specified. For instance make sure the Apache instance is not running under user (nobody).
Comment to chaos:
He is right the tilde (~) can cause issues, but would probably not cause a timeout; it would display a warning. Even if it does work on your system it would probably deposit the file into an unexpected directory or run into some issues if the Apache user (ie www) does not have a valid home directory set.
If the issue is filesize, add the following lines to your php.ini file and it should work:
upload_max_filesize = 500M ;
post_max_size = 500M ;
PHP by default has a 30 second timeout on the page. So if your upload takes longer than 30 seconds it will fail. Set the timeout either in your php.ini or put the following code at the top of the file.
ini_set(max_execution_time, 90);
The second argument represents the time in seconds before the page will timeout. Set it to whatever time you feel is appropriate. Also, chaos is correct in that '~' is a construct that commonly has meaning only inside shells.
Re: http://ca2.php.net/manual/en/ini.list.php
EDIT:
The problem is that you reopened the tag in the middle of a conditional. Trying your code I get a syntax error. It's strange that you were able to see any web form. This is the fixed code (that works for me).
<?php
if (!isset($_GET['upload'])) {
ECHO <<<END
<form method="post" action="index.php?upload=true" enctype="multipart/form-data">
<input type="file" name="file" class="form">
<input name="submit" type="submit">
</form>
END;
} else if (isset($_GET['upload']) && $_GET['upload'] == 'true') {
$url = $_FILES['file']['name'];
$move = move_uploaded_file($_FILES['file']['tmp_name'], "/Users/<username>/Sites/file.jpg");
if ($move) {
echo "Success!";
} else {
echo "Err...";
}
} ?>
Related
I am using a simple file operation on the PHP in order to edit the config file for network interface on CentOS 6.7(/etc/sysconfig/network-scripts/ifcfg-eth0
), after change in any value and save into the config file and try to restart the network interface i get this error:
does not seem to be present, delaying initialization.
[FAILED]
my PHP code is this:
<?php
// configuration
$file = '/etc/sysconfig/network-scripts/ifcfg-eth0';
// check if form has been submitted
if (isset($_POST['text']))
{
// save the text contents
file_put_contents($file, $_POST['text']);
// redirect to form again
header('Location: network.php');
exit();
}
// read the textfile
$text = file_get_contents($file);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea style="width:50%; height:50%;" name="text"><?php echo htmlspecialchars($text) ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
i need manually called the network script by command setup and do a modification in the device setting and save then i will be able to restart the network interface. appreciate if anyone help me why this issue happen while if i open the config file and edit it manually it wouldn't cause this issue.
It's most likely that the user name the server runs as (by default apache on most Red Hat-based distributions) doesn't have permission to write to/etc/sysconfig/network-scripts/ifcfg-eth0.
You should check the return values of:
file_put_contents($file, $_POST['text']);
From http://php.net/manual/en/function.file-put-contents.php
This function returns the number of bytes that were written to the file, or FALSE on failure.
I presume this script will only be run by your or trusted colleagues given that there's no validation of the user input. Indentation would also make the PHP code more readable.
I have the following code that attempts to take a users form input of a file, and upload it to the webserver.
This code does work on a Apache server, however I'm now trying to get the same code working on my Windows IIS 6 web server, which has PHP (Version 5.2.3) installed and working. I have set the PHP.INI file so that
file_uploads = On
upload_tmp_dir = "C:\Temp"
My form is
<form method="POST" action="do_upload.php" enctype="multipart/form-data">
<input type="file" name="img1" size="30">
<input type="submit" name="BtnUpload" value="Click To Upload Now">
</form>
My PHP code to do the upload is
$abpath = "C:\MyWebs\Website1\httdocs\images";
#copy($img1, "$abpath/$img1_name") or $log .= "Couldn't copy image 1 to server";
if (file_exists("$abpath/$img1_name"))
{
$log .= "File 1 was uploaded";
}
else
{
$log .= "File 1 is not an image";
}
For some reason when I check the value of $img1 e.g echo $img1; it is empty. Therefore I tried to get the file using $_FILES['img1']['name']. This worked fine, but still I couldn't upload any files
Any ideas why this is happening.
Your code should be:
move_uploaded_file($_FILES['img1']['tmp_name'], "$abpath/$img1_name");
Don't copy() uploaded files. There are a few edge cases where an uploaded file can be tampered with, which is why move_uploaded_file() exists - it checks for those particular types of tampering.
As well, be VERY careful with how you create your filenames when processing the upload. If you directly use ANYTHING provided in $_FILES as part of the destination path/name for the file, you are opening bad security holes on your server, and a malicious user can exploit that to scribble a file anywhere they want on your server.
I want to upload multiple files to the server.
As far as I can see files are not writable.
What can I do so my code can actually work and upload files.
PHP:
if(isset($_FILES ['uploaded_files']))
{
foreach($_FILES['uploaded_files']['name'] as $key=>$value)
{
if(is_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key]) && $_FILES['uploaded_files']['error'][$key] == 0)
{
$filename = $_FILES['uploaded_files']['name'][$key];
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
{
//code
}
else
{
die ('There was a problem uploading the pictures.');
}
}
else
{
die ('There is a problem with the uploading system.');
}
}
}
HTML:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" id="input_clone_id" name="input_clone_id" value="'.$row['id'].'"/>
<input type="hidden" id="input_clone_var" name="input_clone_var" value="V"/>
<input type="file" name="uploaded_files[]" id="input_clone" multiple="multiple" /><br />
<input type="submit" style="margin-left:0" value="Upload Files" />
</form>
I see two problems with this. The first is a security issue and the second is probably what is causing your problem
You have a security problem here:
$filename = $_FILES['uploaded_files']['name'][$key];
...
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
...
Problem a: Since $filename comes from the $_FILES array, it CANNOT be trusted. The user told your site what the name of their file was and put it there. They could feed you some bogus filename that could cause your script to fail in interesting ways. You need to sanitize that filename before using it in any way.
Problem b: By allowing the user to specify the filename, they could potentially overwrite other files in your "images/gallery" directory simply by specifying a conflicting filename. The way to avoid this is to use a database, generate a unique identifier for the uploaded file, store the file under that unique name, and in the database keep a record of the original filename and other information. That way you always know what the original filename was and you don't have the chance of someone trying to overwrite files in that directory.
Writing problem:*
Your "check for writable" statement is wrong. The filename that comes back is the one that the user used when submitting. This will not point to any point on your filesystem...it points to a spot on theirs (sometimes) which you cannot see. What you need to check is that your "../images/gallery" directory is writable rather than $filename. If that fails, you need to do either "chmod -R 777 gallery" while in the images folder if you have command line access or give it world write access through whatever FTP client you are using if you are using FTP to talk to your server.
So, what you should have instead for that check is:
if (is_writable("../images/gallery")) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
After doing that, if your script comes back and says "the file is writable", it should have been able to copy the file into your images/gallery folder (remember to not use the name of the file the user gave you). If not, perhaps you don't have permissions to move uploaded files.
As for the location of uploaded files, I think sometimes they are deleted after the script execution ends sometimes, but if not, you can echo the 'tmp_name' of the file and if you go to that directory you should find it sitting there. That would be just a verification test to make sure the file was actually getting to your server. So long as you have write permissions (that what chmod 777 does) on the directory you are moving the uploaded file to, you should be able to copy it there.
You are checking to see if a file that you recently uploaded, but not yet saved is writable, I don't think such a file will ever be writable.
Better remove that if, or just check if the folder you are uploading to is writable.
Other than that, I checked your code and it works.
I've searched SO for answers to this feature I desire, but what I need is somewhat unique?
I've got an input element, I type in the name of a sub-folder, hit submit, and a list of the image names within that specified folder is generated via PHP or other. This is local, nothing fancy.
<form action="Make_List.php" method="post">
<input type=text name="location"/>
<input type=submit/>
</form>
<div id="List_Generated"> //desired output.
<span>A.jpg</span>
<span>B.jpg</span>
<span>C.jpg</span>
<span>D.png</span>
</div>
I have no idea what to put in Make_List.php, or if it'll even work locally. I did find this online:
//path to directory to scan
$directory = "../images/team/harry/" ( + sub-folder name );
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
//print each file name
foreach($images as $image)
{
echo $image;
}
But Firefox doesn't know what to do, it asks me to open or save the .php file. Some similar questions on SO (the local part) imply that I don't need PHP for this?
Any tips or pointers would be helpful.
PHP needs a server environment to be processed. You can run a server locally on your own computer. Google installing apache + php. If you have hosting that supports the PHP language you can test your code there.
Your web browser does not run PHP code. An interpreter runs the scripts and their are modules to plug the PHP interpreter into an http server ie apache. Apache will then run the code and return the results if it is instructed to process the .php with a certain module through its configuration.
Use
//path to directory to scan
$directory = "full/path/to/images/team/harry/" . $_POST['location'];
foreach (glob($directory."*.jpg") as $filename) {
echo $filename;
}
Here is a better example for you to work with, no need to type a subdir:
<?php
//Get subfolder list
$folders = glob('../images/team/harry/*',GLOB_ONLYDIR);
?>
<form action="" method="post">
<select name="location" onchange="javascript:this.form.submit()">
<option>-Choose Subdir-</option>
<?php
foreach($folders as $folder){
echo '<option value="'.basename($folder).'">'.basename($folder).'</option>'.PHP_EOL;
}
?>
</select>
</form>
<?php
//List of files once post was submitted
if(isset($_POST['location'])){
echo '<div id="List_Generated">';
$files = glob('../images/team/harry/'.basename($_POST['location']).'/*.jpg');
foreach($files as $file){
echo '<span>'.basename($file).'</span>'.PHP_EOL;
}
echo '</div>';
}
?>
Yes, this sort of thing can be done but with limitations as follows:
Must use HTML5 (doctype and markup).
Google Chrome only (for now)
Application-specific "sandbox" area only, not your general file system.
Realistically, you are thus limited to your computer(s) or those in an intranet where each computer's environment is controlled; not the internet at large.
I'm not an expert but here's a good introduction. You need to read at least the Intro and the section entitled "Reading a directory's contents".
I have a form with the possibility to upload an image from the computer to a server, but it won't work. I don't get any error message, so that's quite annoying. (First I got permission denied, but that was solved by changing the rights), but now when I submit the form, everything goes normally, but the file isn't copied to the destination folder. (The folder exists: I tried it with file_exist()...)
Here's part of the code:
<form action='/changingfruit/index.php?item=bad' name='form' method='post' enctype='multipart/form-data'>
<tr>
<td><input type='text' name='titel_nl' value="titel nl" /><br/><input type='text' name='titel_fr' value="titel fr"/></td>
<td><input type='file' name='text_nl' id='text_nl' accept="image/*"/><br/><input type='file' name='text_fr' id="test_fr" accept="image/*"/></td>
<td class="vTop"><input type="submit" value="Bewaar"/></td>
</tr>
</form>
Part where the values are being send to the db:
$str_titel_nl = $_POST["titel_nl"];
$str_titel_fr = $_POST["titel_fr"];
$str_text_nl = $_FILES["text_nl"]["name"];
$str_text_fr = $_FILES["text_fr"]["name"];
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
(of course the above is just a part of the code: but it's this part that wont work:
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
The code below this part also works fine, so no error, but also no image.
Does someone knows where the problem could be?
Thanks so much in advance!
FOUND THE ANSWER
So it was indeed a permission problem. Everything was 777, but the last folder where the image was put had 755. (/fruits/img/2012/thumb/) the thumb was 755.I just overlooked it. Thanks everyone for the help!
Your upload code is very messy. Instead of using copy you should be using move_uploaded_file, and also validate that it actually worked and then perform whatever actions needed.
I'm also not sure why each of your line is starts with <?php and ends with ?> ?
You can write it all as one block instead, and i think it would also make more sense and would make your code cleaner for sure.
Last thing i would recommend is reading "Handling File Uploads" from the PHP Manual. It might shed some light on the problems you're having.
P.S. Try adding on top ini_set("display_errors","On"); error_reporting(E_ALL); and see if you're getting any error messages.
please have a look on below link.
PHP upload file to web server from form. error message
http://patelmilap.wordpress.com/2012/01/30/php-file-upload/
you can try this
$flag = #copy($temp, $move);
if ( $flag === true )
{
print "Uploaded";
}
I have posted a simple solution for file uploading without worrying about the implementation .
Click to see the thread
image uploading issue in codeigniter 2.1.0
Please read this section
in that $uploader->getMessage(); will return error string related to the upload failure . So you can understand why the uploading failed .
Thanks