DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    <!-- source: http://www.apphp.com/index.php?snippet=javascript-redirect-with-dropdown-menu -->
<script type="text/javascript">
function do_redirect(site){
   window.location.href = site;
}
</script>
 
<select onchange="do_redirect(this.value)">
   <option value="#">What site would you like to see?</option>
   <option value="http://www.google.com">Google</option>
   <option value="http://www.yahoo.com">Yahoo</option>
   <option value="http://www.apphp.com">ApPHP</option>
</select>                
                    <!-- source: http://www.apphp.com/index.php?snippet=javascript-specify-referring-page -->
<script type="text/javascript">
   var allowed_referrer = "http://www.yourdomain.com/referring_page_name.html"; 
   if(document.referrer.indexOf(allowed_referrer) == -1){
      alert("You can access this page only from " + allowed_referrer);
      window.location = allowed_referrer;
   }
</script>                
                    <?php           
// source: http://www.apphp.com/index.php?snippet=php-post-request-by-socket-connection
// submit these variables to the server
$post_data = array("test"=>"yes", "passed"=>"yes", "id"=>"3");
 
// send a request to specified server
$result = do_post_request("http://www.example.com/", $post_data); 
if($result["status"] == "ok"){ 
    // headers 
    echo $result["header"]; 
    // result of the request
    echo $result["content"]; 
}else{
    echo "An error occurred: ".$result["error"]; 
}
 
function do_post_request($url, $data, $referer = ""){
    // convert the data array into URL Parameters like a=1&b=2 etc.
    $data = http_build_query($data);
    // parse the given URL
    $url = parse_url($url); 
    
    if($url["scheme"] != "http"){ 
        die("Error: only HTTP requests supported!");
    }
 
    // extract host and path from url
    $host = $url["host"];
    $path = $url["path"];
 
    // open a socket connection with port 80, set timeout 40 sec.
    $fp = fsockopen($host, 80, $errno, $errstr, 40);
    $result = "";
 
    if($fp){ 
        // send a request headers
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n"); 
        if($referer != "") fputs($fp, "Referer: $referer\r\n"); 
        fputs($fp, "Content-type: application/x-www-form-urlencode
d\r\n");
        fputs($fp, "Content-length: ".strlen($data)."\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data); 
        
        // receive result from request
        while(!feof($fp)) $result .= fgets($fp, 128);
    }else{ 
        return array("status"=>"err", "error"=>"$errstr ($errno)");
    }
 
    // close socket connection
    fclose($fp);
 
    // split result header from the content
    $result = explode("\r\n\r\n", $result, 2);
 
    $header = isset($result[0]) ? $result[0] : "";
    $content = isset($result[1]) ? $result[1] : "";
 
    // return as structured array:
    return array(
        "status" => "ok",
        "header" => $header,
        "content" => $content
    );
}
 
?>                
                    <?php
// source: http://www.apphp.com/index.php?snippet=php-using-gravatars-in-your-script
function show_my_gravatar($email, $size, $default, $rating)
{
  $params = '?gravatar_id='.md5($email).'&default='.$default.'&size='.$size.'&rating='.$rating;
  $output = '<img src="http://www.gravatar.com/avatar.php'.$params.'" width="'.$size.'px" height="'.$size.'px" />';
  echo $output;
}
?>                
                    <?php
// source : http://www.apphp.com/index.php?snippet=php-compress-multiple-css-files
header('Content-type: text/css');
ob_start('compress_css');
 
function compress_css($buffer) {
  /* remove comments in css file */
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  /* also remove tabs, spaces, newlines, etc. */
  $buffer = str_replace(array("\r", "\n", "\r\n", "\t", '  ', '    ', '    '), '', $buffer);
  return $buffer;
}
 
/* a list of your css files */
include('style.css');
include('css/menu.css');
include('css/typography.css');
include('css/print.css');
include('inc/css/footer.css');
 
ob_end_flush();
?>                
                    //Sample Code for Splitting Excel Documents at Amazon S3 Storage

SaasposeApp::$AppSID  = "77***********************************";
SaasposeApp::$AppKey = "9a*******************************";
SaasposeApp::$OutPutLocation = getcwd() . "\\Output\\";

$AmazonS3StorageName = "AmazonS3Storage";
$AmazonS3BucketName = "Saaspose";
$AmazonS3Folder = $AmazonS3BucketName . "/Folder1"; // use $AmazonS3Folder = $AmazonS3BucketName for root folder

//build URI to split sheets
$strURI = 'http://api.saaspose.com/v1.0/cells/Sample1.xlsx/split?format=png&storage=' . $AmazonS3StorageName . '&folder=' . $AmazonS3Folder; 

//sign URI
$signedURI = Utils::Sign($strURI);

$responseStream = Utils::processCommand($signedURI, "POST", "", "");
$json = json_decode($responseStream);

//iterate throug each document in the result to find output sheets
foreach ($json->Result->Documents as $splitSheet) { 
	$splitFileName = $splitSheet->link->Href;
	
	//build URI to download split sheets 
	$strURI = 'http://api.saaspose.com/v1.0/storage/file/'. $AmazonS3Folder . '/' . $splitFileName . '?storage=' . $AmazonS3StorageName;
	
	//sign URI
	$signedURI = Utils::Sign($strURI);

	$responseStream = Utils::processCommand($signedURI, "GET", "", "");
	//save split PDF pages
	$outputFile = SaasposeApp::$OutPutLocation . $splitFileName;
	Utils::saveFile($responseStream, $outputFile);
}

                
                        /* Source : http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url  */
     
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
    var match = url.match(regExp);
    if (match&&match[2].length==11){
        return match[2];
    }else{
        //error
    }
                
                    //Sample Code for Splitting all pages to new PDFs

SaasposeApp.AppSID  = "77***********************************";
SaasposeApp.AppKey = "9a*******************************";
string outputPath = "C:\\TempFiles\\";

//build URI to split PDF pages
string strURI = "http://api.saaspose.com/v1.0/pdf/4pages.pdf/split";
//sign URI
string signedURI = Utils.Sign(strURI);
StreamReader reader = new StreamReader(Utils.ProcessCommand(signedURI, "POST"));
//further process JSON response
string strJSON = reader.ReadToEnd();
//Parse the json string to JObject
JObject parsedJSON = JObject.Parse(strJSON);
SplitPDFResponse responseStream = JsonConvert.DeserializeObject<SplitPDFResponse>(parsedJSON.ToString());

foreach (LinkResponse splitPage in responseStream.Result.Documents) 
{
    string splitFileName = System.IO.Path.GetFileName(splitPage.Href);
    //build URI to download split pages 
    strURI = "http://api.saaspose.com/v1.0/storage/file/" + splitFileName;
    //sign URI
    signedURI = Utils.Sign(strURI);
    //save split PDF pages as PDF
    using (Stream fileStream = System.IO.File.OpenWrite(outputPath + splitFileName))
    {
        Utils.CopyStream(Utils.ProcessCommand(signedURI, "GET"), fileStream);
    }
}
// class definitions
public class SplitPDFResponse : Saaspose.Common.BaseResponse
{
    public SplitPdfResult Result { get; set; }
}
public class SplitPdfResult
{
    public LinkResponse[] Documents { get; set; }
}

//Split specific pages to new PDFs

SaasposeApp.AppSID  = "77***********************************";
SaasposeApp.AppKey = "9a*******************************";
string outputPath = "C:\\TempFiles\\";

//build URI to split PDF pages
string strURI = "http://api.saaspose.com/v1.0/pdf/4pages.pdf/split?from=2&to=3";
//sign URI
string signedURI = Utils.Sign(strURI);
StreamReader reader = new StreamReader(Utils.ProcessCommand(signedURI, "POST"));
//further process JSON response
string strJSON = reader.ReadToEnd();
//Parse the json string to JObject
JObject parsedJSON = JObject.Parse(strJSON);
SplitPDFResponse responseStream = JsonConvert.DeserializeObject<SplitPDFResponse>(parsedJSON.ToString());

foreach (LinkResponse splitPage in responseStream.Result.Documents) 
{
    string splitFileName = System.IO.Path.GetFileName(splitPage.Href);
    //build URI to download split pages 
    strURI = "http://api.saaspose.com/v1.0/storage/file/" + splitFileName;
    //sign URI
    signedURI = Utils.Sign(strURI);
    //save split PDF pages as PDF
    using (Stream fileStream = System.IO.File.OpenWrite(outputPath + splitFileName))
    {
        Utils.CopyStream(Utils.ProcessCommand(signedURI, "GET"), fileStream);
    }
}

//Split PDF pages to any supported format

SaasposeApp.AppSID  = "77***********************************";
SaasposeApp.AppKey = "9a*******************************";
string outputPath = "C:\\TempFiles\\";

//build URI to split PDF pages
string strURI = "http://api.saaspose.com/v1.0/pdf/4pages.pdf/split?from=2&to=3&format=tiff";
//sign URI
string signedURI = Utils.Sign(strURI);
StreamReader reader = new StreamReader(Utils.ProcessCommand(signedURI, "POST"));
//further process JSON response
string strJSON = reader.ReadToEnd();
//Parse the json string to JObject
JObject parsedJSON = JObject.Parse(strJSON);
SplitPDFResponse responseStream = JsonConvert.DeserializeObject<SplitPDFResponse>(parsedJSON.ToString());

foreach (LinkResponse splitPage in responseStream.Result.Documents) 
{
    string splitFileName = System.IO.Path.GetFileName(splitPage.Href);
    //build URI to download split pages 
    strURI = "http://api.saaspose.com/v1.0/storage/file/" + splitFileName;
    //sign URI
    signedURI = Utils.Sign(strURI);
    //save split PDF pages as PDF
    using (Stream fileStream = System.IO.File.OpenWrite(outputPath + splitFileName))
    {
        Utils.CopyStream(Utils.ProcessCommand(signedURI, "GET"), fileStream);
    }}
                
                    / :- The root of overall file system. The starting directory of unix directory structure. 

/bin :- It contains all the standard system commands like ls, cp, rm etc. 

/dev :-This directory contains logical device names. 

/etc :- This directory contains configuration files. 

/home :- Home directory for users.

/export :- The default directory for shared file system's. eg;- User's home directories and other shared file systems.

/kernel :- This contains kernel files that are required as part of the booting process.

 /lib :- The contents of this directory are shared executable files that are used by many applications at the same time. Library files are part of executables (these are also executables) so that you don't have to write same code again and again. 

/mnt :- A temporary mount point for external file systems.

 /opt :- Directory used for installation of external software's and applications. 

/sbin :- This directory contains files that are used by system during booting process. it contains system specific commands. The executables in this directory are very important and are user during system failure. 

/usr :- Programs and files or executables available for normal system users. Basically /usr/bin and /bin are symbolic links to each other.

/var :- Directory for saving system and admin logs. we call it var directory because it contains files that vary from time and time and by that we mean log files. All system administration logs are under var directory.

/devices :- the primary directory for physical device names.

/proc :- stores current process related information. all the processes currently running have directories and subdirectories in this directory. these directories are named with the PID of the process. 

/tmp :- This directory is used to store temporary files. This directory gets cleared if system is down.                 
                    if (!empty($_SERVER["HTTP_CLIENT_IP"]))
{
//check for ip from share internet
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
// Check for the Proxy User
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else
{
$ip = $_SERVER["REMOTE_ADDR"];
}
// This will print user's real IP Address
// does't matter if user using proxy or not.
echo $ip;