copy() Warning Filename cannot be empty - php

I'm trying to save the external images on my site
I have this code:
$file = $_GET['url'];
$newfile = $_SERVER['DOCUMENT_ROOT'] . '/images/name.jpg';
if ( copy($file, $newfile) ) {
echo "Copy saved";
}else{
echo "copy failed";
}
it works well and save images on my server OK, but when I try to use inside FOR, i have this warning:
Warning: copy(): Filename cannot be empty in /home/animesad/public_html/bot/getimg.php on line 18
My code is:
<?php
require "../functions.php";
$p = $_GET['p'];
$url = "http://www.mysite.net/en/movie/page/".$p."/";
$source = curl_get_contents("$url");
preg_match_all('#<li title="(.*?)"><a href#',$source,$name); //outputs title post
preg_match_all('#<img src="(.*?)" width="140" height="200"/>#',$source,$img); //outputs img url
for($i=0;$i<10;$i++){
//print_r($name[1][$i]."<hr />"); //that code show the names OK. (Title posts);
$namefile = slugify($name[1][$i]); //slugify is my function that convert titles in slug.
$newfile = $_SERVER['DOCUMENT_ROOT'] .'/img/'.$namefile.'.jpg';
if ( copy($file, $newfile) ) {
echo "copy saved <hr />";
}else{
echo "copy failed <hr />";
}
}
?>
Any idea is welcome.

you forgot your $file
$file = $_GET['url'];
for($i=0;$i<10;$i++){
$namefile = slugify($name[1][$i]); //slugify is my function that convert titles in slug.
$newfile = $_SERVER['DOCUMENT_ROOT'] .'/img/'.$namefile.'.jpg';
if ( copy($file, $newfile) ) {
echo "copy saved <hr />";
}else{
echo "copy failed <hr />";
}
}

Related

PHP - copy causing HTTP error 500

PHP on execute causing HTTP error 500. I have chmod -R 777 on driver_license.exe.
<?php
$agent= $_GET['agentid'];
$userid = $_GET['userid'];
$file = "/home/www/file/driver_license.exe";
$path = "/home/www/file/";
"
$newfile ="driver_license_userid_1.exe";
$file_to_save = $path . $newfile;
if (!copy($file, $file_to_save)) {
echo "FAILED";
}
else {
echo "<a href=https://download.example.com/{$newfile}>DOWNLOAD & INSTALL</a>";
}
1.You have extra " after $path = "/home/www/file/";.Remove that.
2.You forget to add quotes around href.Add that
So code need to be:-
<?php
$agent= $_GET['agentid'];
$userid = $_GET['userid'];
$file = "/home/www/file/driver_license.exe";
$path = "/home/www/file/";
//" need to remove or comment
$newfile ="driver_license_userid_1.exe";
$file_to_save = $path . $newfile;
if (!copy($file, $file_to_save)) {
echo "FAILED";
}
else {
echo "<a href='https://download.example.com/{$newfile}'>DOWNLOAD & INSTALL</a>"; // ' added around href
}
Important Note:- folders need to be permissioned for access (give 077 permission for home,www and file folders)

I am trying to download a file from mysql, I saved the file location in the database, now I am trying to make a download link for the user on my page

Unable to create the download link. I am fetching the path saved from database and then try to make a link for it to download, but nothing happens.
Below is my code:
$query_print="SELECT vitae_pi FROM pi WHERE username='t124'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
echo ' this is file path '.$query_print_path;
Here I am simply trying to create the download link for user t124, instead of using the current user for testing purposes?
This is hyperlink code:
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
Any suggestions?
This my move file function:
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
//echo $filename;
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$_SESSION['current_filename']=$this->newName;
echo $_SESSION['current_filename'];
$result .= ', and was renamed ' . $this->newName;
}
else{
$_SESSION['current_filename']=$file['name'];
echo $_SESSION['current_filename'];
}
//$result .= '.';
//echo $this->newName;
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
Updating the table with file path:
$file_path_variable1= $destination1.$_SESSION['current_filename'];
echo '$file_path_variable1 : '.$file_path_variable1;
$query1="UPDATE proposal SET whitepaper_prop='$file_path_variable1' WHERE userName_prop='$currentuser'";
$result_query1=mysqli_query($conn,$query1);
....................
SOLUTION CODE IS:
Solution code is :
$query_print="SELECT vitae_pi FROM pi WHERE username='t115'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
$dir= 'uploaded/';
$path=opendir($dir);
<?php
}while($query_pi_array=mysqli_fetch_assoc($query_pi_result));?>
<div>
<?php while($file=readdir($path)){
if($file != "." || $file !=".."){
if($file==$query_print_path){ ?>
Proposal Whitepaper
What does this display ?
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
DOWNLOAD should be part of the PHP string, if not, it will be considered as a constant :
<?php echo "<a href='".$query_print_path."'>DOWNLOAD</a>"; ?>
Also, use double quotes for HTML attributes :
<?php echo "DOWNLOAD"; ?>
And the optimized way (to avoid useless string parsing) :
<?php echo 'DOWNLOAD'; ?>

file_put_contents Failed to open stream: invalid argument

I have this code written in PHP, im using zend server on win 7 as localhost.
<?php
$dir = $_POST['link'];
// Create DOM from URL or file
require_once 'library/simple_html_dom.php';
$html = file_get_html($dir);
foreach($html->find('img') as $element){
$image = $element->src;
$imglink = $dir . $image;
$filename = $element->src;
$parsed_url = parse_url($filename, PHP_URL_PATH);
$basename = basename($filename).PHP_EOL;
$filenameOut = __DIR__ . "/images/" . $basename;
$pos = strpos($image, 'data:image');
if ($pos===false){
$parsing = parse_url($filename, PHP_URL_HOST);
if ($parsing != NULL){
file_put_contents($filenameOut, file_get_contents($image));
}
else{
file_put_contents($filenameOut, file_get_contents($imglink));
}
}
}
?>
And it gives me this error
file_put_contents(C:\Program Files (x86)\Zend\Apache2\htdocs/images/chrome-48.png ): failed to open stream: Invalid argument
Ive tried putting ways i've read from other questions from this site, but doesnt work.

If a URL get clicked a file name has to be changed, how do i do that?

I have this snippet in a HTML file. But I want that a file name gets changed if its opened from 1unread.txt to 1read.txt so it will get in the list of read.
<h2>Unread</h2>
<?php
foreach (glob("*1unread.txt") as $filename) {
echo "<a href='$filename'>Download {$filename}</a><br>" . "\n" ;
}
?>
<h2>Read</h2>
<?php
foreach (glob("*1read.txt") as $filename) {
echo "<a href='$filename'>Download {$filename}</a><br>" . "\n" ;
}
?>
If have read on php.net that I can change a file name with this:
bool rename ( string $oldname , string $newname [, resource $context ] )
but how do I make this happen when the download linked is used? And what does the variable $context do? I am kinda new to PHP so don't expect much from me to understand :P
Thanks anyway
download.php:
<?php
//Only offer file to download which are having "unread" or "read" in their filename.
if(!strstr($_GET['file'], 'unread') || !strstr($_GET['file'], 'read']))
die('Invalid file.');
//Make sure the file exists.
if(!file_exists($_GET['file']))
die('File not found.');
echo file_get_contents($_GET['file']);
if(strstr($_GET['file'], 'unread')) {
//rename 1unread.txt to 1read.txt
$newFileName = str_replace('unread', 'read', $_GET['file']);
rename($_GET['file'], $newFileName);
echo sprintf("RENAMED '%s' TO '%s'!", $_GET['file'], $newFileName); //Debug
} else {
//rename 1read.txt to 1unread.txt
$newFileName = str_replace('read', 'unread', $_GET['file']);
rename($_GET['file'], $newFileName);
echo sprintf("RENAMED '%s' TO '%s'!", $_GET['file'], $newFileName); //Debug
}
?>
Replace the download button with this:
echo "<a href='download.php?file=$filename'>Download {$filename}</a><br>" . "\n" ;

I'm trying to retrieve files from an ubuntu server using php 5.3.5 on a win7 machine

I'm trying to get all .log and .txt files from an Ubuntu server using php 5.3.5 (WAMP). This is my third day using php ... total beginner. I'm reading some doc, but trying to accomplish useful tasks along the way, as to reinforce my learning. Additionally, when I use the code below, the .txt and .log files are printed in the browser but there is no structure (hard to read). How can I print each path on a single line (not sure if it should be apart of the sub process like echo -e \n in the ssh2exec function or a line I should add to the php code? Any help is appreciated ... thanks!
<?php
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
if(!($ssh = ssh2_connect('10.5.32.12', 22))) {
echo "fail: unable to establish connection\n";
} else {
if(!ssh2_auth_password($ssh, 'root', '********')) {
echo "fail: unable to authenticate\n";
} else {
echo "Okay: Logged in ... \n";
$stream = ssh2_exec($ssh, 'find / -name *.log -o -name *.txt');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
fclose($stream);
echo $data; // user
}
}
?>
In a shell, a new line is established by newline character ("\n"). In HTML, you'll need to either use CSS to make these newlines count:
echo '<div style="white-space: pre;">';
echo htmlspecialchars($data);
echo '</div>';
or insert <br/> elements:
echo nl2br(htmlspecialchars($data));
Here is a complete example, including download links and functionality:
<?php
if (! ($ssh = ssh2_connect('10.5.32.12', 22))) {
throw new Exception('Connection failed');
}
if (!ssh2_auth_password($ssh, 'root', '*******')) {
throw new Exception('Authentication failed');
}
if (isset($_GET['download'])) {
$fn = $_GET['download'];
if (! preg_match('/^[a-zA-Z0-9 .-_\\/]+(\\.txt|\\.log)$/', $fn)) {
throw new Exception('access denied');
}
header('X-Content-Type-Options: nosniff');
header('Content-Type: text/plain');
$sftp = ssh2_sftp($ssh);
$url = 'ssh2.sftp://' . $sftp . $fn;
readfile($url);
exit();
}
$stream = ssh2_exec($ssh, 'find / -name "*.log" -o -name "*.txt"');
stream_set_blocking($stream, true);
$data = stream_get_contents($stream);
$files = explode("\n", $data);
echo '<ul>';
foreach ($files as $f) {
if ($f == '') continue;
$url = $_SERVER['PHP_SELF'] . '?download=' . urlencode($f);
echo '<li><a href="' . htmlspecialchars($url) . '">';
echo htmlspecialchars($f);
echo '</a></li>';
}
echo '</ul>';

Categories