I have a form for users to upload files into the folder.
HTML and PHP codes are as below:
<form enctype="multipart/form-data" method="post" action="test.php">
<input type="text" name="name"/><br/>
<input type="file" name="photo" /><br/>
<input type="submit"/>
</form>
<?php //test.php
move_uploaded_file($_FILES["photo"]["tmp_name"], "testFolder/".$_POST["name"]);
?>
The upload form works well, and uploaded files are in the folder testFolder/ .
Now I want to use glob() function to get all file names in the folder.
<?php
foreach(glob("testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
However, it doesn't echo anything.
The glob() function works well on other folders, which contains existing files, not uploaded files.
But why doesn't it work on this folder with uploaded files ?
Possbile wildcard extension could be the issue.
It may be that glob does not allow wildcard extensions, i dont see any mention of this in the docs. Have you tried a directory iterator?
$dir = new DirectoryIterator(__DIR__.'/testFolder);
foreach ($dir as $file) {
echo $file->getFilename();
}
UPDATE: THE PATH IS NOT THE ISSUE
You are using a relative file path, therefore glob probably isn't finding the directory you are trying to search for.
Either the script calling the function needs to sit inside the parent directory of 'testFolder' or you need to use an absolute path like so.
<?php
foreach(glob("/absolute/path/to/testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
If you do want to use a relative path you could do the following:
<?php
//__DIR__ is a PHP super constant that will get the absolute directory path of the script being ran
// .. = relative, go up a folder level
foreach(glob(__DIR__."/../testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
Obviously the paths above are examples but should get you on the right track.
Hope this helps
Because I didn't give the extension for the uploaded file, that's why glob("testFolder/*.*") doesn't get anything.
Two solutions:
Give uploaded files an extension.
$ext = strrchr($_FILES["photo"]["name"], ".");
move_uploaded_file($_FILES["photo"]["tmp_name"],
"testFolder/".$_POST["name"].$ext);
Then, glob("testFolder/*.*") will be able to get these uploaded files with an extension.
Just change glob("testFolder/*.*") to be glob("testFolder/*")
Related
I am looking for a PHP script that connects *.PDF to *.PNG files in a directory. Due to lack of PHP knowledge, I only know how to do this manually in HTML. Could PHP do this for me automatically by connecting A.pdf with A.png, B.pdf with B.png, C.pdf with C.png and so on? Then all I need to be able doing is to change the folder name in PHP.
<div><img src="FOLDER/A.png"></div>
<div><img src="FOLDER/B.png"></div>
<div><img src="FOLDER/C.png"></div>
etcetera...
I'm not sure if I understood this correctly, but the code below will get all .pdf files from a directory and return the HTML for each .pdf file. This will also check to see if the .png exists, but will not echo anything if it does not exist.
// get all .pdf files from directory
$directory = "directory/";
$files = glob($directory."*.{[pP][dD][fF]}", GLOB_BRACE);
foreach ($files as $item) {
// get pathinfo to get the filename
$fileInfo = pathinfo($item);
$fileName = $fileInfo['filename'];
// check if the .png exists
if (file_exists($directory.$fileName.".png")) {
// echo
echo "<div><a href='".$directory.$fileName.".pdf'><img src='".$directory.$fileName.".png'></a></div>";
}
}
I am trying to make a simple file upload form using PHP. Here's my code:
<?php
$uploads_dir = '/uploads';
if(isset($_FILES['thefile'])){
$errors= array();
$file_name = $_FILES['thefile']['name'];
$file_size =$_FILES['thefile']['size'];
$file_tmp =$_FILES['thefile']['tmp_name'];
$file_type=$_FILES['thefile']['type'];
$tmp_name = $_FILES['thefile']["tmp_name"];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($tmp_name, "$uploads_dir/$file_name");
echo "Success";
}
else{
print_r($errors);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="thefile" />
<input type="submit"/>
</form>
</body>
</html>
I realize that I'm not limiting file types, but I'll worry about that once I can get a simple .jpg or .zip file uploaded. Using the above code, I go to the page on my local server located at
C:\wamp\www\simpleupload (this contains index.php, the file posted above)
When I select a small image file and click submit, I'm presented with the following errors:
Warning: move_uploaded_file(/uploads/session_timeout_formatting_bug.png): failed to open stream: No such file or directory in C:\wamp\www\project_fileshare\index.php on line 18
and
Warning: move_uploaded_file(): Unable to move 'C:\wamp\tmp\phpEFDE.tmp' to '/uploads/session_timeout_formatting_bug.png' in C:\wamp\www\project_fileshare\index.php on line 18
Line 18 is the line that calls the move_uploaded_file() function.
How do I fix this error? I have an 'uploads_dir' folder located in the same folder as my index.php file. (reference the file path above). What am I doing wrong here? I must be misunderstanding some small part of this process and have put my directory in the wrong place, or I'm doing something wrong in the code.
Can someone spot my mistake and tell me what I need to do to fix it?
You are working on windows and you've told PHP a location that is inaccessible (i.e. /uploads linux path).
Since you are working in windows and your document root is C:\wamp\www\simpleupload
Which means, your files are located like this:
C:\wamp\www\simpleupload\index.php (your upload script)
C:\wamp\www\simpleupload\uploads (where the files should be uploaded)
Why don't you use absolute path like this:
$uploads_dir = getcwd() . DIRECTORY_SEPARATOR . 'uploads';
The getcwd() function will return the current working directory for the executing PHP script (in your case index.php), so the $uploads_dir will now look like this: C:\wamp\www\simpleupload\uploads
Try this.
If your upload directory is in the same location as your index.php remove the "/" in your $uploads_dir variable. This, or add a "." before the slash because now it refers to the root which might be something else then your current working directory. Speaking of the devil; http://php.net/manual/en/function.getcwd.php
$uploads_dir = getcwd() . '\uploads';
$uploads_dir = __DIR__ . '\uploads'; #php > 5.6
Also, check if your directory is writeable for php:
http://php.net/manual/en/function.is-writable.php
Also what Latheesan said, better to go cross platform as I made the same mistake seen in my edit.
<?php
function buildPath(...$segments){
return join(DIRECTORY_SEPARATOR, $segments);
}
echo buildPath(__DIR__, 'uploads');
?>
And i would change
if(isset($_FILES['thefile'])){
for this
if($_FILE['thefile']['error'] === UPLOAD_ERR_OK){
Because I think that this is the best way to know if the user upload a file or the input is blank.
Or
if (isset($_FILE["thefile"]["name"])){
I want to use PHP and MySQL to delete an image from a folder inside the server. The image name is inside the database (the format [jpg] is already included on the image name). I tried many ways and the following is one of them, but it's not working yet. Help please.
if(isset($_POST['submit2'])) {
$numeroimagem = $_POST["numero"];
$imagem=mysqli_query($con,"SELECT imagem FROM galeria WHERE numero='$numeroimagem'");
$nomeimagem=mysqli_fetch_row ($imagem);
$target = '../imgs/galeria/'.$nomeimagem;
if (file_exists($target)) {
unlink($target);
}
}
The form:
<form action="" method="post">
<input name="numero" type="text" size="3" maxlength="3"><input type="submit" name="submit2" value="Delete"><br>
</form>
You forgot to delete the file. You can use the function unlink for that:
http://php.net/manual/en/function.unlink.php
We cannot know exactly the error, but the main issue was the File what not with realpath function.
Realpath function resolves if a path is correcty
if you try realpath('../imgs/galeria/') php will resolve full path.
If realpath return false or null, the path cannot be resolved, when you have to try accoplish the right path.
If you are running script from folder scripts/delete-imagem.php, and the files at public/imgs/galeria, you should use realpath('../public/images/) to get full path.
Once you get the full path, you should try to remove it using "unlink()"
$path = realpath('../public/imgs/galeria/');
if(is_dir($path)) {
if(is_file($path.'/'.$fileName)) { //Note that realpath trim the final "/" from filepath.
unlink($path.'/'.$fileName);
{
}
This code will force it works.
I just found out the problem. I was getting Array on the file name it was solved by adding [0] like this:
$target = '../imgs/galeria/'.$nomeimagem[0];
Thanks for the tips anyways :)
if(isset($_POST['submit'])){
if(!empty($_FILES['files']['name'])){
$Zip = new ZipArchive();
$Zip->open('uploads.zip', ZIPARCHIVE::CREATE);
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
$Zip->close();
}
else {
echo "no files selected";
}
}
What is wrong here ? I have just watched a tutorial of creating archives and adding files in it but it is not working ...I am using php 5.4 . It is not even giving me any error. Can any one please guide me what i am doing wrong here.
Below is the form
<form action="" method="POST" enctype="multipart/form-data">
<label>Select files to upload</label>
<input type="file" name="files">
<input type="submit" name="submit" value="Add to archieve">
</form>
These lines don't make any sense
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
At that point in the code you posted, no uploaded files have been moved to a uploads/ directory, and looping though the $_FILES["files"] element - which is an associative array of various values, only one of which is the actual file name - and adding each value to the ZIP as a file, is nonsensical. - You should read the PHP docs relating to file uploading. It's clear you don't really know how PHP handles file uploads yet, which you should learn before attempting things like this.
One solution would be to move the uploaded file to the uploads/ directory using move_uploaded_file, but seeing as you are only really using the file there to add it to the archive, that step is pretty redundant; you can just add it directly from the temp location. First you need to verify it, though, which you can do with the is_uploaded_file function.
// Make sure the file is valid. (Security!)
if (is_uploaded_file($_FILES["files"]["tmp_name"])) {
// Add the file to the archive directly from it's
// temporary location. Pass the real name of the file
// as the second param, or the temporary name will be
// the one used inside the archive.
$Zip->addFile($_FILES["files"]["tmp_name"], $_FILES["files"]["name"]);
$Zip->close();
// Remove the temporary file. Always a good move when
// uploaded files are not moved to a new location.
// Make sure this happens AFTER the archive is closed.
unlink($_FILES["files"]["tmp_name"]);
}
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".