cURL save file and rename? - php

I'm downloading and saving a file from another server to my server, except the file I'm downloading comes attached with an access token.
http://www.example.com/video.mp4?versionId=c_.Qeh.dz.zqPA3zc57HFDKEAmKG3xr2
Loading the following results in a permission error:
http://www.example.com/video.mp4
Problem is, when I cURL with the following code:
$url = 'http://www.example.com/video.mp4?versionId=c_.Qeh.dz.zqPA3zc57HFDKEAmKG3xr2';
$fh = fopen(basename($url), "wb");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);
The file saves as video.mp4?versionId=c_.Qeh.dz.zqPA3zc57HFDKEAmKG3xr2 (with token) and not video.mp4, which means I can't do anything with it afterwards as it's not an .mp4
What's the solution here? I tried
rename(video.mp4?versionId=c_.Qeh.dz.zqPA3zc57HFDKEAmKG3xr2, video.mp4)
but it requires filenames and the access token is preventing that.

Try to use parse_url instead of basename or combine them. Take path from parse_url (without GET params) and then use basename function.
http://www.php.net/manual/en/function.parse-url.php

try basename( parse_url( $url, PHP_URL_PATH ) )

Related

how to open txt file from another server using php

I want to open and write a txt file from another server, but I don't know how to do it? Can anyone help me?
<?PHP
$fname=$_POST["fname"];
$groupid=$_POST["groupid"];
$myfile = fopen("Ji.txt", "a+") or die("Unable to open file!");
fwrite($myfile, $fname."|".$groupid."\r\n");
fclose($myfile)
?>
I want to replace Ji.txt with http://xxx.xxx.xx.x/ddd.txt
You can read the files over HTTP by using fopen or cURL.
You can't write to files over HTTP unless the server you are writing to is set up to understand an appropriate request. You could configure it to support PUT requests (make sure you have some kind of authn/authz system in place!) and make one using cURL.
Alternatively, you could use some other protocol to make the file available between servers (such as NFS).
Alternatively you can do it with the FTP functions
<?php
// Connect to remote FTP server
$conn = ftp_connect("ftp.example.com")or die("Cant connect to ftp server");
$login = ftp_login($conn, "username", "password");
// Open local (temporary) file handle
$fh = fopen("Ji.txt", "a+");
// Get remote file and save it to the previous file handle
if(ftp_fget($conn, $fh, "Ji.txt", FTP_ASCII))
{
// Local file has now been updated with the content of the remote Ji.txt
$fname = $_POST['fname'];
$groupid = $_POST['groupid'];
fwrite($fh, $fname.'|'.$groupid.'\r\n');
if(ftp_fput($conn, "Ji.txt", $fh, FTP_ASCII))
echo 'File saved to remote server';
else
echo 'Error saving to remote server';
}
else
echo 'Error downloading remote file';
ftp_close($conn);
fclose($fh);
?>
Read more about ftp_fput etc here: http://php.net/manual/en/function.ftp-fput.php
As long as allow_url_fopen is set to True you can pass an URL to fopen() and read the data. Writing however, is impossible. However, you can write a wrapper around the file that accepts both GET & POSTS requests. A GET returns the contents of the file and a POST (or PUT) saves content to the files. The downside of this is that you must add security and it's a lot more complex to save the data.
Assuming you have access to the other server and the text file is available at a web address (ie you can see it in a browser) then you can use fopen to grab it, make your edits or whatever and then post back to a script that will handle the post data and save the file using curl. Example code below copied from this answer
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '#/path/to/file.txt'));
curl_setopt($ch, CURLOPT_URL, 'http://server2/upload.php');
curl_exec($ch);
curl_close($ch);
Posting server should be something like this
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('ourfilename' =>'yourpath/test.txt'));
curl_setopt($ch, CURLOPT_URL, 'http://urlreceivepost/getfile.php');
curl_exec($ch);
curl_close($ch);
Then getfile.php at your above url
if ($_POST) {
$file= $_POST['ourfilename'];
$data = file_get_contents($file);
$new = 'test.txt';
file_put_contents($new, $data);
var_dump($new);}

php curl or file_get_contents too slow on hosted site

I'm using cUrl to get the file's contents of the same website's page, and writing to another file ( To convert dynamic php file into static php file for menu caching purpose )
$dynamic = 'http://mysite.in/menu.php';
$static = "../menu-static.php" ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$dynamic);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$file = curl_exec($ch);
file_put_contents($static, $file);
die();
It works perfect on localhost. But taking too much time when it is running on hosted website, and at last even the output file ($static = "../menu-static.php") is empty.
I can't determine where is the problem .. Please help
I've also tried file_get_contents instead of cUrl with no luck ..

Saving images from website to folder using curl php

I am able to save images from a website using curl like so:
//$fullpath = "/images/".basename($img);
$fullpath = basename($img);
$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawData = curl_exec($ch);
curl_close($ch);
if(file_exists($fullpath)) {
unlink($fullpath);
}
$fp = fopen($fullpath, 'w+');
fwrite($fp, $rawData);
fclose($fp);
However, this will only save the image on the same folder in which I have the php file that executes the save function is in. I'd like to save the images to a specific folder. I've tried using $fullpath = "/images/".basename($img); (the commented out first line of my function) but this results to an error:
failed to open stream: No such file or directory
So my question is, how can I save the file on a specific folder in my project?
Another question I have is, how can I change the filename of the image I save on the my folder? For example, I'd like to add the prefix siteimg_ to the image's filename. How do I implement this?
Update: I have managed to solve first problem with the path after trying to play around with the code a bit more. Instead of using $fullpath = "/images/".basename($img), I added a variable right before fopen and added it to the fopen method like so:
$path = "./images/";
$fp = fopen($path.$fullpath, 'w+');
Strangely that worked. So now I'm down to one problem which would be renaming the file. Any suggestions?
File paths in PHP are server paths. I doubt you have a /images folder on your server.
Try constructing a relative path from the current PHP file, eg, assuming there is an images folder in the same directory as your PHP script...
$path = __DIR__ . '/images/' . basename($img);
Also, why don't you try this much simpler script
$dest = __DIR__ . '/images/' . basename($img);
copy($img, $dest);

When downloading a file with PHP, nothing happens?

I'm having trouble downloading a remote file via PHP.
I've tried using cURL and streaming, neither of which produces an error.
Here's my current code for streaming.
$url = "http://commissiongeek.com/files/text.txt";
$path = "/files/cb.txt";
file_put_contents($path, file_get_contents($url));
I'll be downloading a zip file when I get this working, but in theory this should work just fine...
The folder's permissions are set to 777, and as said before, no errors are being thrown.
What could cause this?
Split this up into multiple sections, so you can verify that each stage is working:
$url = 'http://...';
$txt = file_get_contents($url);
var_dump($txt);
var_dump(file_put_contents('/files/cb.txt', $txt));
The first dump SHOULD show you whatever that text that url returns. The second dump should output a boolean true/false depending on if the file_put failed or not.
It seems you have an absolute path that you are trying to save in. I believe you want the path changed to "files/cb.txt" instead and do not have any access to /files/
If you have allow_url_fopen set to true:
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
Else use cURL:
$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

PHP filesize for absolute path

I was surprised PHP's filesize() fails on absolute paths??
My files are on my own server, how can I get the filesize except from converting them to relative (a mess)
EDIT
example:
$filename = 'http://172.16.xx.x/app/albums/002140/tn/020.jpg';
echo $filename . ': ' . filesize($filename) . ' bytes';
Warning: filesize() [function.filesize]: stat failed for http://172.16.xx.x/app/albums/002140/tn/020.jpg in /Applications/XAMPP/xamppfiles/htdocs/app/admin/+tests/filesize.php on line 26
END EDIT
I found this example for remote files:
$filename = 'http://www.google.com/logos/2010/stevenson10-hp.jpg';
$headers = get_headers($filename, 1);
echo $headers['Content-Length']; // size in bytes
Does this work without downloading the files?
http://172.16.xx.x/app/albums/002140/tn/020.jpg is not an absolute path, it is an URL. The absolute path for it would be something like /var/www/app/albums/002140/tn/020.jpg. You should use that absolute path in filesize().
filesize() supports only URL wrappers that support stat(). HTTP and HTTPS doesn't support that as mentioned in the manual page for HTTP and HTTPS wrappers.
Yes It will be work fine .
$filename = 'http://172.16.xx.x/app/albums/002140/tn/020.jpg';
$headers = get_headers($filename, 1);
$fsize = $headers['Content-Length'];
You can use like this ... for get file size by URL
$ch = curl_init('http://172.16.xx.x/app/albums/002140/tn/020.jpg');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
$data = curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
echo $size;
As I suspected, you're trying to give an HTTP URL to filesize(), which will not work. filesize() works on local filesystem URLs, such as those listed at http://www.php.net/manual/en/wrappers.file.php.
Presumably, as you're trying to access files on your own server, you must have the filesystem URL, rather than just an HTTP URL?
To use Function filesize();
you should have absolute path not the urls
http://www.php.net//manual/en/function.filesize.php
get_headers() will send a GET to your server, this add load to your web server.
I don't get it, your filesize() fails on absolute path ? It should not. According to php.net :
http://www.php.net/manual/en/wrappers.file.php
Edit:
I'm not sure about the error PHP will give you if allow_url_fopen is set to 0, but check this line in your PHP.ini (and restart apache then) : http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
If it's off, filesize() will not handle URL. Let me know if it was that.
I think you would have to use the filesize() function.
http://php.net/manual/en/function.filesize.php
echo filesize( $filename );

Categories