I noticed that Kindle recognizes the file types by their extension. So, I wrote a small script on my website that downloads a file, adds ".azw" extension and provide a download link. It works well sometimes but...
The problem is that I'm not a PHP developer and I'm sure the script is not written in the best way. A problem is that the script doesn't download some files (exe) but loads another exe. It gives an error saying that it cannot find the file and creates a filename.exe.azw file with 0 length. This issue appears only on the Kindle, but on the PC it's ok.
Also it seems that it can download only files smaller than 9 Mb.
The code is here:
<?php
if(!isset($_POST['link'])) {
?>
<form method="post" action="file.php">
<p>
Enter link: http://
<input type="text" name="link" size="20"/>
<input type="submit" name="submit" value="submit" />
</p>
</form>
<?php
} else {
$remote = 'http://' . $_POST['link'];
$download = download($remote);
echo 'Download: ' . $download . '';
}
function download($url) {
$lastDashPos = strrpos($url, '/');
$local = substr($url, $lastDashPos + 1, strlen($url) - $lastDashPos) . '.azw';
$handle = file_get_contents($url);
file_put_contents($local, $handle);
return $local;
}
?>
The script is at http://forexsb.com/test/file.php if you want to test it.
Related
I have a page, and I want it to allow users to upload a file to my server so that I can see it later. I have already gotten started, but when you click submit, it takes you to 500 error. Here is what code I have so far:
HTML:
<form action="uploadfile.php" enctype="multipart/form-data" method="POST">
Choose File:
<input name="userfile" type="file">
<p></p>
<p class="section-content"><input type="submit" value="Upload File"></p>
</form>
PHP: (named uploadfile.php)
<?php
$path = "files/"; $path = $path . basename( $_FILES['userfile']['name']);
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $path)) {
echo "Success uploading". basename($_FILES['userfile']['name']);
} else{
echo "Error when uploading file.";
}
?>
In HTML, there is a button to choose the file and one to submit. The submit button takes you to uploadfile.php, and that appears as 500 - internal server error. Note that it does not just say 'Error when uploading file' like it should when there is an error.
I am new to PHP, so I don't know if I am doing something completely wrong, or maybe there is a way to do it in Javascript, which I am slightly more experienced in?
Thank you in advance.
Edit: I have tried 2 different browsers (Chrome and Edge)
corrected
use $_SERVER['DOCUMENT_ROOT'] instead of basename()
$path = $_SERVER['DOCUMENT_ROOT'].'/your root file name/files';
$name = $_FILES['userfile']['name'];
$tmp_name = $_FILES['userfile']['tmp_name'];
move_uploaded_file($tmp_name, $path.'/'.$name);
i am just transloading multiple files from one server to another, if it comes less then this script work perfect, if its crossing to thousands URL's then requests increase and then server block for accessing files.
Here is script
<?php
// Check if form has been submitted
if(#$_POST['submit']){
ini_set("max_execution_time", 0); // no time-outs!
ignore_user_abort(true); // Continue downloading even after user closes the browser.
// URLS -- One on each line
$URL = $_POST['url'];
// Relative path to Save downloaded images
// Default is "downloads"
// Make sure that it is writable (chmoded correctly)
$folder = $_POST['folder'];
// Check if User has provided a local folder
if (!$folder || !isset($folder)){
// Generate error if left blank by user.
die ("Please specify local folder name");
}
// Split all URLS into an array
$urls = split("\n", $URL);
// Remove Carriage Returns (useful for Windows-based browsers)
$urls = str_replace("\r", "", $urls);
$mh = curl_multi_init();
foreach ($urls as $i => $url) {
$path = pathinfo($url);
$g=$folder . "/" . $path["basename"] ;
// Check if file already exists on local folder.
if(file_exists($g)){
// If exists, delete the file so it always contains the latest update.
unlink($g) or die("Unable to delete existing '$g'!");
}
// Update the user of what's going on
echo "$i) Downloading: from <b>$url</b> to <b>$g</b><br />";
if(!is_file($g)){
$conn[$i]=curl_init($url);
$fp[$i]=fopen ($g, "w");
curl_setopt ($conn[$i], CURLOPT_FILE, $fp[$i]);
curl_setopt ($conn[$i], CURLOPT_HEADER ,0);
// curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,1000);
curl_multi_add_handle ($mh,$conn[$i]);
}
}
do {
$n=curl_multi_exec($mh,$active);
}
while ($active);
foreach ($urls as $i => $url) {
curl_multi_remove_handle($mh,$conn[$i]);
curl_close($conn[$i]);
fclose ($fp[$i]);
}
curl_multi_close($mh);
} // task closed
?>
<br />
<br />
<fieldset>
<legend>
<label for="url">Server to Server Upload Script</label>
</legend>
<form method=POST>
<label for="url">Insert Files URL, One Per Line: </label><br />
<textarea rows=15 cols=75 id="url" name="url"><?= $URL ?></textarea><br />
<label for="folder">Folder Name: </label><input type=text id="folder" name="folder" value="uploads"/>
<input type=submit name="submit" value="Start Uploading Files!" />
</form>
</fieldset>
With this script if i add 5000 URL's it suddenly starts sending request and transloading the files. (Server block it due to huge requests.)
How do i add code once the first file transloaded then the other
request should be sent. ?
I'm trying to develop for homework a MVC PHP app that archives some files, app which I'm building on a Zend Server in Windows 7 (if it matters).
Here's the setup : I have this form in a view :
<div class="box">
<h3>What would you like to store?</h3>
<form action="<?php echo URL; ?>archives/archiveAction" method="POST" enctype='multipart/form-data'>
<label>Select the files you'd like to store</label>
<input type="file" name="upload[]" multiple>
<input type="hidden" name="user_id" value="<?php echo $_SESSION['id']; ?>" >
<label>Select your favorite compression algorithm</label>
<select name="type_of_archive">
<option value="zip">ZIP</option>
<option value="tar">TAR</option>
<option value="gzip">GZIP</option>
<option value="bzip2">BZIP2</option>
</select>
<input type="submit" name="add_files" value="Submit" />
</form>
</div>
And then I'm passing it to the responsible controller action:
public function archiveAction()
{
if(isset($_POST["user_id"]) && isset($_POST["type_of_archive"]) && isset($_FILES['upload']))
{
$time = new DateTime();
if ($_POST['type_of_archive'] == 'zip')
{
Helper::zipFiles($_FILES['upload'],"./".$_SESSION['username']."/",$_SESSION['username']." - ".$time->format('Y-m-d H:i:s'));
}
}
}
The zipFiles function itself is below :
static public function zipFiles($files, $dir, $name)
{
$location = $dir.$filename.".zip";
$zip = new ZipArchive();
if ($zip->open($location, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$num_of_files = count($files['name']);
for($i = 0;$i<$num_of_files;$i++ )
{
$zip->addFile($files['tmp_name'][$i]);
}
$zip->close();
return $location;
}
The problem is that I'm not getting any errors. What I'm trying to do is create a zip file in a directory. All I'm getting is that my browser is downloading an empty file called archiveAction. Anything I'm missing here? If I keep retrying the script just hangs after a while.
This happens because you use $files['tmp_name'][$i]. If you print_r your $_FILES you will see that $files['tmp_name'][0] (for example) is just a file name without a path. So when you execute archiveAction script tries to find file $files['tmp_name'][$i] in a directory where it is (script) is run. Sure there's no such file, as it is stored in your /tmp or some other directory for temporary files.
So, you should either first copy your uploaded files (move_uploaded_file function) to some specific location, path to which you know, and create zip archive using these copied files and full path to them. For example, copy them to uploads folder of you site. And use:
$zip->addFile($_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $somefile_name);
Or you can find out path to your temporary files folder (check php.ini) and use:
$zip->addFile($temporary_path . $files['tmp_name'][$i]);
I am using php to upload and move a file to a desired location...
while using move_uploaded_file, it says that the file has moved successfully but the file does not show up in the directory.
THE HTML AND PHP CODE IS BELOW...
<form action="test_upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="test_pic">Testing Picture</label>
<input type="file" name="test_pic" size="30" /><br />
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
THe php goes like :
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
?>
when i run this page and upload a legitimate file - the test_upload.php echoes file uploaded successfully. but when i head on to the folder "vidit" in the root of the web page. the folder is empty...
I am using wamp server .
You need to append filename into your destination path. Try as below
$doc_path = realpath(dirname(__FILE__));
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$doc_path.$upload_dir.'/'.$_FILES[$image_fieldname]['name']) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
See PHP Manual for reference. http://php.net/manual/en/function.move-uploaded-file.php
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if (move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir . '/' . $_FILES[$image_fieldname]['name'] && is_writable($upload_dir)) {
$display_message = "file moved successfully";
} else {
$display_message = " STILL DID NOT MOVE";
}
?>
Added indenting as well. The file name needs to be applied, or it's like uploading the file as a extensionless file.
Use this it may work
$upload_dir = "vidit/";
$uploadfile=($upload_dir.basename($_FILES['test_pic']['name']));
if(move_uploaded_file($_FILES['test_pic']['tmp_name'], $uploadfile) ) {
}
Create tmp directory in root(www) and change directory path definitely it works
/ after your directory name is compulsory
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/tmp/';
This question already has answers here:
Saving image from PHP URL
(11 answers)
Closed 6 years ago.
How can I use php to download an image from URL (eg: https://www.google.com/images/srpr/logo3w.png) then save it?
This is what I came up with so far, it gives me an error in 'file_put_contents' function.
<form method="post" action="">
<textarea name="text" cols="60" rows="10">
</textarea><br/>
<input type="submit" class="button" value="submit" />
</form>
<?php
$img = "no image";
if (isset($_POST['text']))
{
$content = file_get_contents($_POST['text']);
$img_path = '/images/';
file_put_contents($img_path, $content);
$img = "<img src=\"".$img_path."\"/>";
}
echo $img;
?>
It gives me the error:
[function.file-put-contents]: failed to open stream: No such file or directory in C:\wamp\www\img.php
The /images/ directory is located in the same directory of the php file and is writable.
You cannot save the image with your existing code because you do not provide a file name. You need to do something like:
$filenameIn = $_POST['text'];
$filenameOut = __DIR__ . '/images/' . basename($_POST['text']);
$contentOrFalseOnFailure = file_get_contents($filenameIn);
$byteCountOrFalseOnFailure = file_put_contents($filenameOut, $contentOrFalseOnFailure);
file_put_contents() requires first parameter to be file name not the path.
What is your error ? But you have the right way to do what you want to do.
Just take care in your code, I can see file_put_contents($img_path, but $img_path is a path to a folder.
You need to write something like :
example
$img_path="home/downloads/my_images";
file_put_contents($img_path."/flower.jpg");
file_put_contents($img_path, $content);
To what are you putting to?? i think you have made a mistake with get and put. or missed to specify the full path including the file name and extension
I added one condition to accepted answer to check the image type as follows,
if (exif_imagetype($_POST['text']) == IMAGETYPE_PNG) {
$filename = './images/'.basename($_POST['text']);
file_put_contents($filename, $content);
}
from above example I show how to check png images before download the files and for more content types you can find here .