Im trying to make a website with users on it, and I'm trying to create a script so that whenever a new user registers it will automatically create a user folder and profile for them but when I try to register it doesn't create the files, could someone please help me with this, Thanks
<?php
include "inc/header.php";
$newfolder = $username;
if (!mkdir($newfolder, 0777, true)) {
die('Failed to create folders...');
}
$pagename = $username;
$newFileName = './u/'.$username.'/'.$pagename.".php";
$newFileContent = '<?php echo "something..."; ?>';
?>
To make a directory/file
if (!file_exists("parent_folder/$username")) {
//Create a file with read write execute PERMISSIONS ENABLED
//Please check : your parent folder also must have 0777 permissions to avoid any kind of read write error
mkdir("parent_folder/$username", 0777);
//now u have to create a FILE with .php
//now this file_put_contents is VERY importnant !
$pagename = $username ;
$newFileName = './parent_folder/$username/'.$pagename.".php";
$newFileContent = '<?php echo "something..."; ?>';
if (file_put_contents($newFileName, $newFileContent) !== false) {
//notify file is created
echo "File created (" . basename($newFileName) . ")";
} else {
//notify u have error
echo "Cannot create file (" . basename($newFileName) . ")";
}
//now create ur .php file in user folder
}
else {
echo "Your parent folder does not exist"
}
Now the possible error and some tips
1) Most of people do fopen("filename_with_PATH", "w")
and expect that file will be generated in PATH folder !
Some times it might fall wrong (depends on version)
fopen is meant to create a file in the directory where your php resides
2) check ur php permission in php.ini if u dont give php permission to write,remote access then u might get some errors (it will be displayed that u have error in my script)
3)For more info and tinkering file_put_contents
Hope this will be helpful for you ..
Related
Hello ive searched everywhere to find the answer however none of the solutions ive tried helped
What i am building is a site which connects to Youtube to allow users to search and download videos as MP3 files. I have built the site with the search etc however i am having a problem with the download part (ive worked out how to get the youtube audio file). The format for the audio is originally audio/mp4 so i need to convert it to mp3 however first i need to get the file on the server
So on the download page ive made a script that sends an ajax request to the server to start downloading the file. It then sends a request to a different page every few seconds to find out the progress and update it on the page the user is viewing.
However the problem is while the video is downloading the whole website freezes (all the pages dont load until the file is fully downloaded) and so when the script tries to find out the progress it cant until its fully done.
The file which downloads:
<?php
session_start();
if (isset($_GET['yt_vid']) && isset($_GET['yrt'])) {
set_time_limit(0); // to prevent the script from stopping execution
include "assets/functions.php";
define('CHUNK', (1024 * 8 * 1024));
if ($_GET['yrt'] == "gphj") {
$vid = $_GET['yt_vid'];
$mdvid = md5($vid);
if (!file_exists("assets/videos/" . $mdvid . ".mp4")) { // check if the file already exists, if not proceed to downloading it
$url = urlScraper($vid); // urlScraper function is a function to get the audio file, it sends a simple curl request and takes less than a second to complete
if (!isset($_SESSION[$mdvid])) {
$_SESSION[$mdvid] = array(time(), 0, retrieve_remote_file_size($url));
}
$file = fopen($url, "rb");
$localfile_name = "assets/videos/" . $mdvid . ".mp4"; // The file is stored on the server so it doesnt have to be downloaded every time
$localfile = fopen($localfile_name, "w");
$time = time();
while (!feof($file)) {
$_SESSION[$mdvid][1] = (int)$_SESSION[$mdvid][1] + 1;
file_put_contents($localfile_name, fread($file, CHUNK), FILE_APPEND);
}
echo "Execution time: " . (time() - $time);
fclose($file);
fclose($localfile);
$result = curl_result($url, "body");
} else {
echo "Failed.";
}
}
}
?>
I also had that problem in the past, the reason that it does not work is because the session can only be once open for writing.
What you need to do is modify your download script and use session_write_close() each time directly after writing to the session.
like:
session_start();
if (!isset($_SESSION[$mdvid])) {
$_SESSION[$mdvid] = array(time(), 0, retrieve_remote_file_size($url));
}
session_write_close();
and also in the while
while (!feof($file)) {
session_start();
$_SESSION[$mdvid][1] = (int)$_SESSION[$mdvid][1] + 1;
session_write_close();
file_put_contents($localfile_name, fread($file, CHUNK), FILE_APPEND);
}
i want to upload images outside web root directory, but i don't know how to do it.
For example i want to put images in var/media3/, i set the media directory to permissions 777, now i need to modify the code to put images because that can not work.
I tryed even using $_SERVER['DOCUMENT_ROOT'] but it doesn't work (and honestly I have never tried this kind of thing).
This is the upload.php script:
<?php
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'var/media3/'.$_FILES['upl']['name'])){ // <--The problem is in this string, it won't work
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
Thanks XD
Add a leading slash /var/media
I am trying to create and save a file to the root directory of my site, but I don't know where its creating the file as I cannot see any. And, I need the file to be overwritten every time, if possible.
Here is my code:
$content = "some text here";
$fp = fopen("myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
How can I set it to save on the root?
It's creating the file in the same directory as your script. Try this instead.
$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.
<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>
This question has been asked years ago but here is a modern approach using PHP5 or newer versions.
$filename = 'myfile.txt'
if(!file_put_contents($filename, 'Some text here')){
// overwriting the file failed (permission problem maybe), debug or log here
}
If the file doesn't exist in that directory it will be created, otherwise it will be overwritten unless FILE_APPEND flag is set.
file_put_contents is a built in function that has been available since PHP5.
Documentation for file_put_contents
fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.
This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.
Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:
$fp = fopen("myText.txt","wb");
if( $fp == false ){
//do debugging or logging here
}else{
fwrite($fp,$content);
fclose($fp);
}
Let's say i want to generate a download link and put it into <a> tag.
my php script:
function download_link(){
$this_id = "d"; //this is the name of file from server
$original_filename = 'xample.pdf'; //This come from database
$ext = pathinfo($original_filename, PATHINFO_EXTENSION);
$file = '../uploads/'.$this_id.'.'.$ext;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/'.$ext);
header('Content-Disposition: attachment; filename='.$original_filename);//Rename the file with its original filename
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
return readfile($file);//Here where i want to return the generated url
}
return '#'; //Or return nothing if file doesn't exist
echo ''; //And put it here, the generated url
now, my directory location is ../uploads/.
i am expecting a result like: so when the user click this tag the file will be downloaded. but instead, when i reload the page it is automatically downloading without clicking the download button which is the <a> tag.
note: i am trying to rename the filename when botton download is clicked.
i know there is a problem in my logic. maybe this can be done with JQUERY? or AJAX? im searching for solution but did not find the answer.
here's what i did with JQUERY AJAX:
HTML tag
<a id="server_name_file_name">download</a>
JQUERY AJAX:
$('a').click(function(e) {
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'download.php',
data: { server_file_name: id,},
success: function(response) {
if(response == 1){
alert("Unable to download, Maybe the file is corrupted. Please try to reload the page.");
}else{
window.location.href = response;
return false;
}
}})
});
download.php
$this_id = $_POST['server_file_name'];
$original_filename = 'xample.pdf'; //This come from database
$ext = pathinfo($original_filename, PATHINFO_EXTENSION);
$file = '../uploads/'.$this_id.'.'.$ext;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/'.$ext);
header('Content-Disposition: attachment; filename='.$original_filename);//Rename the file with its original filename
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
echo readfile($file);//Here where i want to return the generated url
exit();
} die('1');
but doesnt work.
anyone can help me here? Thank you!!!!
You're returning the actual contents of the file with readfile.
Thats why browser starts to download the file you return.
What you need to do is to generate the string which will point to the file.
If your "uploads" dir is accessible by url, then your downloads.php should look like this:
$this_id = $_POST['server_file_name'];
$original_filename = 'xample.pdf'; //This come from database
$ext = pathinfo($original_filename, PATHINFO_EXTENSION);
$file = '../uploads/' . $this_id . '.' . $ext;
if (file_exists($file)) {
echo 'www.myserver.com/uploads/' . $this_id . '.' . $ext;
exit();
}
die('1');
If your uploads dir is not accessible from outside, then you need to copy the file into the public directory first.
At a first glance, i can identify a couple of problems.
Your download function does not return the link of the file but rather it outputs the file itself, so it is logical that when refreshing the page, the file is downloading.
Plus, I can see that you are calling your function useing function download_link() whereas it should be directly download_link().
The proper way this should be done is having the download link to a file executing the download_link function (ex: http://yoursite.com/download_file.php?file=filename)
Of course it is advisable to have an id instead of filename in the URL and apply all the security you need etc...
Inside download_file.php file, you can call download_link($filename) or better download_link($id) and get the file name from the database or wherever you are storing it and then output the file as you are doing now.
I have a php file named "savegame.php".
I use xampp. When i enter "localhost/morabaraba/savegame.php" as a url manually it works
i have a file "index.html" in the same folder as my "savegame.php" file and using window.location = "savegame.php" redirects
to c:\....\morabaraba\savegame.php but it does not echo back or update the database as the code in "savegame.php" says it should
code in savegame.php
<?php
print 'i am working';
//database updating details
?>
When i say enter localhost/morabaraba/savegame.php i mean typing it in the window, not coding it as window.location = "local/morabaraba/savegame.php" in the index.html file